From f3cec564fbe1a1d90bec1ab2922d8958e66f3ca8 Mon Sep 17 00:00:00 2001 From: WizardOfYendor1 Date: Sun, 15 Nov 2026 18:08:52 -0500 Subject: [PATCH 01/13] added per-user ownership of live tv recordings The plugin now keeps which users own each timer, series rule and recording in its own state file (livetv-recording-owners.json, versioned, written atomically), and stamps a readable "Recorded by " tag on recordings as a backup the store can be rebuilt from. A recording can have several owners. Ownership follows the recording through Jellyfin's lifecycle: owners attach when a recording starts or is stopped before a sync, survive a timer moving between duplicate series rules, and are kept for 7 days as a tombstone when a recording leaves the library. A returning file only gets them back if it was last written before it left, so a rerun on the same path is a new recording. Renamed and deleted users are followed, a failed user lookup never counts as a deletion, and a store written by a newer plugin is never overwritten. --- .../Services/EmbyLiveTvRecordingHost.cs | 210 +- Jellyfin/backend/Helpers/UserReflection.cs | 25 + .../backend/Services/LiveTvRecordingHost.cs | 345 ++- shared/LiveTv/ILiveTvRecordingHost.cs | 60 +- shared/LiveTv/IncompleteRecordingModels.cs | 58 +- shared/LiveTv/IncompleteRecordingService.cs | 223 +- shared/LiveTv/RecordingOwnershipModels.cs | 130 ++ shared/LiveTv/RecordingOwnershipService.cs | 1899 +++++++++++++++++ shared/LiveTv/RecordingOwnershipWatcher.cs | 278 +++ 9 files changed, 3209 insertions(+), 19 deletions(-) create mode 100644 shared/LiveTv/RecordingOwnershipModels.cs create mode 100644 shared/LiveTv/RecordingOwnershipService.cs create mode 100644 shared/LiveTv/RecordingOwnershipWatcher.cs diff --git a/Emby/Emby.Plugins.Moonfin/Services/EmbyLiveTvRecordingHost.cs b/Emby/Emby.Plugins.Moonfin/Services/EmbyLiveTvRecordingHost.cs index a7627089..11e9bbaa 100644 --- a/Emby/Emby.Plugins.Moonfin/Services/EmbyLiveTvRecordingHost.cs +++ b/Emby/Emby.Plugins.Moonfin/Services/EmbyLiveTvRecordingHost.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using System.Linq; +using System.Reflection; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -58,6 +59,8 @@ public EmbyLiveTvRecordingHost( _libraryManager.ItemAdded += OnItemAdded; _libraryManager.ItemUpdated += OnItemUpdated; _libraryManager.ItemRemoved += OnItemRemoved; + _userManager.UserUpdated += OnUserUpdated; + _userManager.UserDeleted += OnUserDeleted; } public event EventHandler? ScheduleChanged; @@ -74,6 +77,10 @@ public EmbyLiveTvRecordingHost( public event EventHandler? ItemRemoved; + public event EventHandler? UserUpdated; + + public event EventHandler? UserDeleted; + public void Dispose() { _liveTvManager.TimerCreated -= OnTimerCreated; @@ -86,6 +93,8 @@ public void Dispose() _libraryManager.ItemAdded -= OnItemAdded; _libraryManager.ItemUpdated -= OnItemUpdated; _libraryManager.ItemRemoved -= OnItemRemoved; + _userManager.UserUpdated -= OnUserUpdated; + _userManager.UserDeleted -= OnUserDeleted; } public Task> GetTimersAsync(CancellationToken cancellationToken) @@ -103,6 +112,7 @@ public Task> GetTimersAsync(CancellationToken canc PrePaddingSeconds = t.PrePaddingSeconds, PostPaddingSeconds = t.PostPaddingSeconds, Status = t.Status.ToString(), + SeriesTimerId = string.IsNullOrEmpty(t.SeriesTimerId) ? null : t.SeriesTimerId, }) .ToList(); return Task.FromResult(timers); @@ -220,6 +230,100 @@ public IReadOnlyList FindProgramsByName(string name, DateTime afte .ToList(); } + public Task> GetSeriesTimersAsync(CancellationToken cancellationToken) + { + return Task.FromResult>(ListSeriesRules()); + } + + private List ListSeriesRules() => + _liveTvManager.GetSeriesTimers(new SeriesTimerQuery()).Items + .Where(t => !string.IsNullOrEmpty(t.Id)) + .Select(t => new SeriesRule(t.Id, string.IsNullOrEmpty(t.SeriesId) ? null : t.SeriesId, t.Name)) + .ToList(); + + public async Task CreateSeriesTimerAsync(string programId, IReadOnlyDictionary? overrides, CancellationToken cancellationToken) + { + try + { + var before = new HashSet(ListSeriesRules().Select(r => r.Id), StringComparer.OrdinalIgnoreCase); + var defaults = _liveTvManager.GetNewTimerDefaults(programId, cancellationToken); + ApplyOverrides(defaults, overrides); + + var created = await _liveTvManager.CreateSeriesTimer(ToSeriesTimerInfo(defaults), cancellationToken).ConfigureAwait(false); + + // The API id of the new rule is the one that wasn't there before. The id the + // service returned is the fallback when the list can't tell. + var added = ListSeriesRules().Where(r => !before.Contains(r.Id)).ToList(); + var rule = added.Count == 1 + ? added[0] + : added.FirstOrDefault(r => r.SeriesId != null && r.SeriesId == defaults.SeriesId) + ?? added.FirstOrDefault(r => r.Name == defaults.Name); + return new SeriesRuleCreation(rule?.Id ?? (string.IsNullOrEmpty(created?.Id) ? null : created!.Id)); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // The reason reaches the client, which opens its Premiere dialog on a Premiere refusal. + _logger.Warn("{0}", "Could not create a series rule for program " + programId + ": " + ex.Message); + return SeriesRuleCreation.Failed(ex.Message); + } + } + + // The client's settings map names the rule's properties directly (RecordNewOnly, KeepUpTo, ...). + private void ApplyOverrides(SeriesTimerInfoDto rule, IReadOnlyDictionary? overrides) + { + if (overrides == null) + { + return; + } + + foreach (var pair in overrides) + { + var property = typeof(SeriesTimerInfoDto).GetProperty(pair.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); + if (property == null || !property.CanWrite || property.Name is "Id" or "ServerId" or "ProgramId") + { + continue; + } + + try + { + property.SetValue(rule, JsonSerializer.Deserialize(pair.Value.GetRawText(), property.PropertyType)); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or ArgumentException) + { + _logger.Warn("{0}", "Ignored series rule setting " + pair.Key + ": " + ex.Message); + } + } + } + + // Emby creates a series timer from its own SeriesTimerInfo, while the defaults come as a DTO. + private static SeriesTimerInfo ToSeriesTimerInfo(SeriesTimerInfoDto dto) => new SeriesTimerInfo + { + Id = dto.Id, + ChannelId = dto.ChannelId, + ChannelIds = dto.ChannelIds, + ParentFolderId = long.TryParse(dto.ParentFolderId, NumberStyles.None, CultureInfo.InvariantCulture, out var folder) ? folder : 0, + ProgramId = dto.ProgramId, + Name = dto.Name, + Overview = dto.Overview, + StartDate = dto.StartDate, + EndDate = dto.EndDate, + RecordAnyTime = dto.RecordAnyTime, + KeepUpTo = dto.KeepUpTo, + KeepUntil = dto.KeepUntil, + SkipEpisodesInLibrary = dto.SkipEpisodesInLibrary, + MatchExistingItemsWithAnyLibrary = dto.MatchExistingItemsWithAnyLibrary, + RecordNewOnly = dto.RecordNewOnly, + Days = dto.Days, + Priority = dto.Priority, + PrePaddingSeconds = dto.PrePaddingSeconds, + PostPaddingSeconds = dto.PostPaddingSeconds, + IsPrePaddingRequired = dto.IsPrePaddingRequired, + IsPostPaddingRequired = dto.IsPostPaddingRequired, + SeriesId = dto.SeriesId, + MaxRecordingSeconds = dto.MaxRecordingSeconds, + Keywords = dto.Keywords, + }; + public Task ScheduleProgramAsync(string programId, CancellationToken cancellationToken) { try @@ -234,7 +338,8 @@ public Task ScheduleProgramAsync(string programId, CancellationT } _liveTvManager.CreateTimer(timer); - return Task.FromResult(ScheduleResult.Created); + var timerId = FindTimerId(programId); + return Task.FromResult(ScheduleResult.CreatedWith(timerId, timerId)); } catch (ArgumentException) { @@ -242,8 +347,25 @@ public Task ScheduleProgramAsync(string programId, CancellationT } catch (Exception ex) { + // The reason reaches the client, which opens its Premiere dialog on a Premiere refusal. _logger.Warn("{0}", "Could not schedule program " + programId + ": " + ex.Message); - return Task.FromResult(ScheduleResult.Failed); + return Task.FromResult(ScheduleResult.FailedWith(ex.Message)); + } + } + + // The timer just created, by its program. Null when the lookup fails; the recording is scheduled regardless. + private string? FindTimerId(string programId) + { + try + { + return _liveTvManager.GetTimers(new TimerQuery()).Items + .FirstOrDefault(t => string.Equals(t.ProgramId, programId, StringComparison.OrdinalIgnoreCase) + && t.Status != RecordingStatus.Cancelled && !string.IsNullOrEmpty(t.Id))?.Id; + } + catch (Exception ex) + { + _logger.Warn("{0}", "Could not look up the timer for program " + programId + ": " + ex.Message); + return null; } } @@ -360,6 +482,74 @@ public bool DeleteItem(Guid itemId) return true; } + public ServerUser? GetUser(Guid userId) + { + try + { + var user = _userManager.GetUserById(userId); + return user == null ? null : ToServerUser(user); + } + catch (Exception ex) + { + _logger.Warn("{0}", "Could not read user " + userId + ": " + ex.Message); + return null; + } + } + + public bool? UserExists(Guid userId) + { + try + { + return _userManager.GetUserById(userId) != null; + } + catch (Exception ex) + { + _logger.Warn("{0}", "Could not check whether user " + userId + " exists: " + ex.Message); + return null; + } + } + + public IReadOnlyList GetUsers() => + _userManager.Users.Where(u => u != null).Select(ToServerUser).ToList(); + + // The image tag comes from the user's DTO; a DTO that can't be built costs only the image. + private ServerUser ToServerUser(User user) + { + string? imageTag = null; + try + { + imageTag = _userManager.GetUserDto(user).PrimaryImageTag; + } + catch (Exception ex) + { + _logger.Warn("{0}", "Could not read the image of user " + user.Id + ": " + ex.Message); + } + + return new ServerUser(user.Id, user.Name ?? string.Empty, imageTag, user.Policy?.IsDisabled == true); + } + + // Emby has no recording folder list to place an item under, and its recordings listing + // without a user may miss items, so it can't tell; owners then treat every item as one. + public bool? IsLiveTvRecording(Guid itemId) => null; + + public IReadOnlyList FindItemsWithTagPrefix(string prefix) + { + // Tags only match whole values in a query, so the recordings are listed and filtered here. + var recordings = _liveTvManager.GetRecordings(new InternalItemsQuery { Recursive = true }, CancellationToken.None).Items; + var result = new List(); + foreach (var recording in recordings) + { + if (Guid.TryParse(recording.Guid, out var id) + && _libraryManager.GetItemById(id) is { } item + && (item.Tags ?? Array.Empty()).Any(t => t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + { + result.Add(ToLibraryItem(item)); + } + } + + return result; + } + private static string? SeriesIdOf(LiveTvProgram? program) => program != null && program.SeriesId > 0 ? program.SeriesId.ToString(CultureInfo.InvariantCulture) : null; @@ -490,6 +680,22 @@ private void OnItemUpdated(object? sender, ItemChangeEventArgs e) } } + private void OnUserUpdated(object? sender, GenericEventArgs e) + { + if (e.Argument != null) + { + UserUpdated?.Invoke(this, ToServerUser(e.Argument)); + } + } + + private void OnUserDeleted(object? sender, GenericEventArgs e) + { + if (e.Argument != null) + { + UserDeleted?.Invoke(this, e.Argument.Id); + } + } + private void OnItemRemoved(object? sender, ItemChangeEventArgs e) { if (e.Item != null) diff --git a/Jellyfin/backend/Helpers/UserReflection.cs b/Jellyfin/backend/Helpers/UserReflection.cs index 69e02b32..ad3fef5d 100644 --- a/Jellyfin/backend/Helpers/UserReflection.cs +++ b/Jellyfin/backend/Helpers/UserReflection.cs @@ -1,6 +1,7 @@ using System.Collections; using System.Reflection; using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Dto; namespace Moonfin.Server.Helpers; @@ -39,6 +40,30 @@ internal static class UserReflection return userManager == null ? null : GetUserById.Invoke(userManager, [userId]); } + /// Whether this server's user manager can be asked for a user by id, so a null from means there is no such user. + public static bool CanResolveUsers(IServiceProvider services) => + GetUserById != null && UserManager(services) != null; + + private static readonly MethodInfo? GetUserDtoMethod = UserManagerType? + .GetMethods() + .Where(m => m.Name == "GetUserDto" && typeof(UserDto).IsAssignableFrom(m.ReturnType)) + .OrderBy(m => m.GetParameters().Length) + .FirstOrDefault(); + + /// A user as the DTO, which kept its shape across versions, or null when it can't be built. + public static UserDto? ToDto(IServiceProvider services, object user) + { + var userManager = UserManager(services); + if (userManager == null || GetUserDtoMethod == null) + { + return null; + } + + var args = new object?[GetUserDtoMethod.GetParameters().Length]; + args[0] = user; + return GetUserDtoMethod.Invoke(userManager, args) as UserDto; + } + public static object? UserManager(IServiceProvider services) => UserManagerType == null ? null : services.GetService(UserManagerType); diff --git a/Jellyfin/backend/Services/LiveTvRecordingHost.cs b/Jellyfin/backend/Services/LiveTvRecordingHost.cs index f77a118a..5d266a53 100644 --- a/Jellyfin/backend/Services/LiveTvRecordingHost.cs +++ b/Jellyfin/backend/Services/LiveTvRecordingHost.cs @@ -1,6 +1,9 @@ +using System.Reflection; using System.Text.Json; using Jellyfin.Data.Events; using Jellyfin.Data.Enums; +using Jellyfin.Data.Events.Users; +using MediaBrowser.Controller.Events; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -14,6 +17,29 @@ namespace Moonfin.Server.Services; +/// Tells the recording host a user was deleted, which the user manager has no event for. +public sealed class RecordingHostUserDeletedConsumer : IEventConsumer +{ + private readonly JellyfinLiveTvRecordingHost _host; + + public RecordingHostUserDeletedConsumer(JellyfinLiveTvRecordingHost host) + { + _host = host; + } + + public Task OnEvent(UserDeletedEventArgs eventArgs) + { + // The User the event carries changed type in 10.11, so its id is read by reflection. + var user = eventArgs.GetType().GetProperty("Argument")?.GetValue(eventArgs); + if (user?.GetType().GetProperty("Id")?.GetValue(user) is Guid id) + { + _host.NotifyUserDeleted(id); + } + + return Task.CompletedTask; + } +} + /// The Jellyfin implementation of . public sealed class JellyfinLiveTvRecordingHost : ILiveTvRecordingHost, IDisposable { @@ -65,8 +91,165 @@ public JellyfinLiveTvRecordingHost( public event EventHandler? ItemRemoved; + private readonly object _userEventLock = new(); + private EventHandler? _userUpdated; + private EventInfo? _userUpdatedEvent; + private Delegate? _userUpdatedHandler; + private object? _userUpdatedSource; + + // Subscribed on first use rather than in the constructor, so a host nobody watches for user + // changes never touches the user manager's event. + public event EventHandler? UserUpdated + { + add + { + _userUpdated += value; + SubscribeUserUpdated(); + } + remove => _userUpdated -= value; + } + + public event EventHandler? UserDeleted; + + /// Raised by the user deleted event consumer, since the user manager has no event of its own for it. + internal void NotifyUserDeleted(Guid userId) => UserDeleted?.Invoke(this, userId); + + private void SubscribeUserUpdated() + { + lock (_userEventLock) + { + if (_userUpdatedHandler != null) + { + return; + } + + try + { + // The event's argument carries Jellyfin's User type, which changed in 10.11, so the + // handler is bound to whichever event argument type the running server uses. + var userManager = UserReflection.UserManager(_services); + var updated = userManager?.GetType().GetInterfaces() + .Select(i => i.GetEvent("OnUserUpdated")) + .FirstOrDefault(e => e != null); + if (userManager == null || updated?.EventHandlerType is not { IsGenericType: true } handlerType) + { + return; + } + + var method = typeof(JellyfinLiveTvRecordingHost) + .GetMethod(nameof(OnUserUpdatedRaw), BindingFlags.Instance | BindingFlags.NonPublic)! + .MakeGenericMethod(handlerType.GetGenericArguments()[0]); + var handler = Delegate.CreateDelegate(handlerType, this, method); + updated.AddEventHandler(userManager, handler); + _userUpdatedEvent = updated; + _userUpdatedHandler = handler; + _userUpdatedSource = userManager; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not subscribe to user changes"); + } + } + } + + private void OnUserUpdatedRaw(object? sender, TArgs e) + { + try + { + var user = typeof(TArgs).GetProperty("Argument")?.GetValue(e); + var serverUser = user == null ? null : ToServerUser(user); + if (serverUser != null) + { + _userUpdated?.Invoke(this, serverUser); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not read an updated user"); + } + } + + private ServerUser? ToServerUser(object user) + { + var dto = UserReflection.ToDto(_services, user); + return dto == null ? null : new ServerUser(dto.Id, dto.Name ?? string.Empty, dto.PrimaryImageTag, dto.Policy?.IsDisabled == true); + } + + public ServerUser? GetUser(Guid userId) + { + try + { + var user = UserReflection.ResolveUser(_services, userId); + return user == null ? null : ToServerUser(user); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not read user {UserId}", userId); + return null; + } + } + + // Only the lookup by id: the DTO a ServerUser is built from can fail on its own, which says + // nothing about whether the user exists. + public bool? UserExists(Guid userId) + { + try + { + if (!UserReflection.CanResolveUsers(_services)) + { + return null; + } + + return UserReflection.ResolveUser(_services, userId) != null; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not check whether user {UserId} exists", userId); + return null; + } + } + + public IReadOnlyList GetUsers() + { + var result = new List(); + if (UserReflection.AllUsers(_services) is { } users) + { + foreach (var user in users) + { + if (user == null) + { + continue; + } + + // One user whose DTO can't be built is left out rather than failing the whole list. + try + { + if (ToServerUser(user) is { } serverUser) + { + result.Add(serverUser); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not read a user while listing users; leaving them out"); + } + } + } + + return result; + } + public void Dispose() { + lock (_userEventLock) + { + if (_userUpdatedHandler != null) + { + _userUpdatedEvent!.RemoveEventHandler(_userUpdatedSource, _userUpdatedHandler); + _userUpdatedHandler = null; + } + } + _liveTvManager.TimerCreated -= OnTimerCreated; _liveTvManager.TimerCancelled -= OnTimerCancelled; _liveTvManager.SeriesTimerCreated -= OnTimerEvent; @@ -113,6 +296,7 @@ public async Task> GetTimersAsync(CancellationToke PrePaddingSeconds = t.PrePaddingSeconds, PostPaddingSeconds = t.PostPaddingSeconds, Status = t.Status.ToString(), + SeriesTimerId = string.IsNullOrEmpty(t.SeriesTimerId) ? null : t.SeriesTimerId, IsManual = manual.TryGetValue(t.ServiceName + "\0" + t.ExternalId, out var isManual) ? isManual : null, }) .ToList(); @@ -207,6 +391,69 @@ public IReadOnlyList FindProgramsByName(string name, DateTime afte }).Items.OfType().Select(p => ToGuideProgram(p, channels)).ToList(); } + public async Task> GetSeriesTimersAsync(CancellationToken cancellationToken) + { + var result = await _liveTvManager.GetSeriesTimers(new SeriesTimerQuery(), cancellationToken).ConfigureAwait(false); + + // The public DTO carries no guide series id, so rules are identified by their API id alone. + return result.Items + .Where(t => !string.IsNullOrEmpty(t.Id)) + .Select(t => new SeriesRule(t.Id, null, t.Name)) + .ToList(); + } + + public async Task CreateSeriesTimerAsync(string programId, IReadOnlyDictionary? overrides, CancellationToken cancellationToken) + { + try + { + var before = (await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false)) + .Select(r => r.Id) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var rule = await _liveTvManager.GetNewTimerDefaults(programId, cancellationToken).ConfigureAwait(false); + ApplyOverrides(rule, overrides); + + await _liveTvManager.CreateSeriesTimer(rule, cancellationToken).ConfigureAwait(false); + + // The server returns no id, so the new rule is the one that wasn't there before. + var created = (await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false)) + .Where(r => !before.Contains(r.Id)) + .ToList(); + return new SeriesRuleCreation((created.Count == 1 ? created[0] : created.FirstOrDefault(r => r.Name == rule.Name))?.Id); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + _logger.LogWarning(ex, "Could not create a series rule for program {ProgramId}", programId); + return SeriesRuleCreation.Failed(ex.Message); + } + } + + // The client's settings map names the rule's properties directly (RecordNewOnly, KeepUpTo, ...). + private void ApplyOverrides(SeriesTimerInfoDto rule, IReadOnlyDictionary? overrides) + { + if (overrides == null) + { + return; + } + + foreach (var (name, value) in overrides) + { + var property = typeof(SeriesTimerInfoDto).GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); + if (property is not { CanWrite: true } || property.Name is "Id" or "ServerId" or "ProgramId") + { + continue; + } + + try + { + property.SetValue(rule, value.Deserialize(property.PropertyType)); + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or ArgumentException) + { + _logger.LogWarning(ex, "Ignored series rule setting {Setting}", name); + } + } + } + public async Task ScheduleProgramAsync(string programId, CancellationToken cancellationToken) { try @@ -222,7 +469,8 @@ public async Task ScheduleProgramAsync(string programId, Cancell } await _liveTvManager.CreateTimer(timer, cancellationToken).ConfigureAwait(false); - return ScheduleResult.Created; + var created = await FindTimerAsync(programId, cancellationToken).ConfigureAwait(false); + return ScheduleResult.CreatedWith(created?.TimerId, created?.ApiId); } catch (ArgumentException) { @@ -231,8 +479,25 @@ public async Task ScheduleProgramAsync(string programId, Cancell } catch (Exception ex) { + // The reason reaches the client, which shows it (a tuner conflict, say). _logger.LogWarning(ex, "Could not schedule program {ProgramId}", programId); - return ScheduleResult.Failed; + return ScheduleResult.FailedWith(ex.Message); + } + } + + // The timer just created, by its program. Null when the lookup fails; the recording is scheduled regardless. + private async Task FindTimerAsync(string programId, CancellationToken cancellationToken) + { + try + { + return (await GetTimersAsync(cancellationToken).ConfigureAwait(false)) + .FirstOrDefault(t => string.Equals(t.ProgramId, programId, StringComparison.OrdinalIgnoreCase) + && t.Status != nameof(RecordingStatus.Cancelled)); + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + _logger.LogWarning(ex, "Could not look up the timer for program {ProgramId}", programId); + return null; } } @@ -350,6 +615,82 @@ public bool DeleteItem(Guid itemId) return true; } + // A finished recording's DTO type is Episode, Movie or Video, so only its place under the + // recording locations tells it apart from any other library item. + public bool? IsLiveTvRecording(Guid itemId) + { + try + { + if (_libraryManager.GetItemById(itemId) is not { IsFolder: false } item) + { + return false; + } + + var locations = RecordingLocations(); + if (!string.IsNullOrEmpty(item.Path) && locations.Any(l => IsUnderLocation(item.Path, l))) + { + return true; + } + + // Elsewhere means "not a recording" only once the recording locations are known to + // the library; with none of them resolving, this server's setup can't be read. + return RecordingFolderIds(locations).Length == 0 ? null : false; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not check whether item {ItemId} is a Live TV recording", itemId); + return null; + } + } + + /// Whether a file path lies inside a folder, ignoring case and either separator. + internal static bool IsUnderLocation(string path, string location) + { + var folder = location.TrimEnd('/', '\\'); + return folder.Length > 0 + && path.Length > folder.Length + && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase) + && path[folder.Length] is '/' or '\\'; + } + + // GetRecordingFolders builds its folder infos from the configured paths and never sets their + // ItemId, so the paths are all there is to go on. + private string[] RecordingLocations() => + _recordingsManager.GetRecordingFolders() + .SelectMany(f => f.Locations ?? Array.Empty()) + .Where(l => !string.IsNullOrWhiteSpace(l)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + // The library folders at the recording locations, found the way LiveTvManager finds them. + private Guid[] RecordingFolderIds(IEnumerable locations) => + locations + .Select(l => _libraryManager.FindByPath(l, true)) + .Where(f => f != null) + .Select(f => f!.Id) + .Distinct() + .ToArray(); + + public IReadOnlyList FindItemsWithTagPrefix(string prefix) + { + var folders = RecordingFolderIds(RecordingLocations()); + if (folders.Length == 0) + { + return Array.Empty(); + } + + // Tags only match whole values in a query, so the recordings are listed and filtered here. + return _libraryManager.GetItemsResult(new InternalItemsQuery + { + AncestorIds = folders, + IsFolder = false, + IsVirtualItem = false, + }).Items + .Where(i => (i.Tags ?? Array.Empty()).Any(t => t.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))) + .Select(ToLibraryItem) + .ToList(); + } + private bool IsVisibleTo(Guid itemId, object user) { var item = _libraryManager.GetItemById(itemId); diff --git a/shared/LiveTv/ILiveTvRecordingHost.cs b/shared/LiveTv/ILiveTvRecordingHost.cs index 70f0a5c9..c0e5c3b8 100644 --- a/shared/LiveTv/ILiveTvRecordingHost.cs +++ b/shared/LiveTv/ILiveTvRecordingHost.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -14,9 +15,20 @@ public interface ILiveTvRecordingHost /// A timer or series timer was created or cancelled. event EventHandler? ScheduleChanged; + /// + /// A timer was created. Only TimerId, ProgramId and (Emby) ApiId are set. TimerId is the id the + /// server's event carries: on Jellyfin the service's id for the built-in DVR (DefaultLiveTvService) + /// and the API id for services with new-timer-ids; on Emby the one id it has. Use GetTimersAsync + /// for the full timer with both ids. + /// event EventHandler? TimerCreated; - /// The id from the server's timer cancellation event. + /// + /// The id from the server's timer cancellation event. Jellyfin: the service's id when the + /// built-in DVR cancels a timer, the API id when the Live TV manager cancels one for another + /// service, so match it against both ScheduledTimer.TimerId and ScheduledTimer.ApiId. Emby: the + /// timer's id, which is both. + /// event EventHandler? TimerCancelled; /// The server's Refresh Guide task finished. @@ -28,7 +40,15 @@ public interface ILiveTvRecordingHost event EventHandler? ItemRemoved; - /// All timers the server knows, including cancelled and completed ones. + /// A server user was renamed, disabled or otherwise changed. + event EventHandler? UserUpdated; + + event EventHandler? UserDeleted; + + /// + /// All timers the server knows, including cancelled and completed ones, with both ids set: + /// TimerId is the service's id and ApiId the id clients see (the same on Emby). + /// Task> GetTimersAsync(CancellationToken cancellationToken); /// The file a timer is writing right now, or null when it isn't recording. @@ -47,7 +67,20 @@ public interface ILiveTvRecordingHost /// Guide programs with a name starting after a time, on every channel. IReadOnlyList FindProgramsByName(string name, DateTime after); - /// Schedules a one-off recording of a program with the server's timer defaults. + /// All series rules the server knows, by the API id clients see. + Task> GetSeriesTimersAsync(CancellationToken cancellationToken); + + /// + /// Creates a series rule from the server's timer defaults for a program, with the client's + /// settings applied by property name. Returns the new rule's API id (SeriesRule.Id), or a null + /// id when it couldn't be created or found, with the server's reason when it refused. + /// + Task CreateSeriesTimerAsync(string programId, IReadOnlyDictionary? overrides, CancellationToken cancellationToken); + + /// + /// Schedules a one-off recording of a program with the server's timer defaults. The result + /// carries the timer's service id and API id, or on failure the server's reason when it gave one. + /// Task ScheduleProgramAsync(string programId, CancellationToken cancellationToken); LibraryItem? FindItemByPath(string path); @@ -80,4 +113,25 @@ public interface ILiveTvRecordingHost /// something other than an episode, which is left alone. /// bool DeleteItem(Guid itemId); + + /// A user, or null when there is no such user or the user can't be read right now. + ServerUser? GetUser(Guid userId); + + /// + /// Whether a user account exists: false only when the server definitely has no such user, + /// null when it can't tell (the lookup failed or this server version can't be asked). Owners + /// are only ever dropped on false, never on a failed read. + /// + bool? UserExists(Guid userId); + + IReadOnlyList GetUsers(); + + /// + /// Whether a library item is a Live TV recording: true when it is under the server's recording + /// folders, false when it isn't (or doesn't exist), null when this server can't tell. + /// + bool? IsLiveTvRecording(Guid itemId); + + /// Live TV recordings that carry a tag starting with the prefix. + IReadOnlyList FindItemsWithTagPrefix(string prefix); } diff --git a/shared/LiveTv/IncompleteRecordingModels.cs b/shared/LiveTv/IncompleteRecordingModels.cs index d50df9a0..f2a32378 100644 --- a/shared/LiveTv/IncompleteRecordingModels.cs +++ b/shared/LiveTv/IncompleteRecordingModels.cs @@ -307,9 +307,25 @@ public sealed class CompleteShowingRequest /// Opened by a user from the Record prompt, so it survives the automatic setting being turned off. public bool Explicit { get; set; } + /// + /// The first user who asked, kept so files written before OwnerUserIds still load: a request + /// read with no owners but this set is seeded with it. + /// public Guid? RequestedByUserId { get; set; } - internal CompleteShowingRequest Copy() => (CompleteShowingRequest)MemberwiseClone(); + /// + /// Everyone waiting for this episode: each user who asked, and for an automatic request the + /// owners of the incomplete recording. The timer it schedules or adopts gets them all as owners. + /// None means nobody in particular, so any airing may be picked. + /// + public List OwnerUserIds { get; set; } = new(); + + internal CompleteShowingRequest Copy() + { + var copy = (CompleteShowingRequest)MemberwiseClone(); + copy.OwnerUserIds = new List(OwnerUserIds); + return copy; + } public DateTime OpenedAt { get; set; } @@ -359,14 +375,27 @@ public sealed class ScheduledTimer /// Whether a user made or cancelled the timer by hand; null when the server doesn't say. public bool? IsManual { get; set; } - /// The API id, which some cancellation events use instead of the service's timer id. + /// + /// The id the Live TV API and clients know the timer by. Jellyfin: an MD5 the server derives + /// from the service's id (TimerInfoDto.Id). Emby: the same as TimerId. Set by GetTimersAsync; + /// null on timers built from a TimerCreated event, which can't cheaply derive it. + /// public string? ApiId { get; set; } - /// The service's own timer id. + /// + /// The service's own timer id (Jellyfin: TimerInfoDto.ExternalId; Emby: TimerInfoDto.Id). On a + /// timer from a TimerCreated event this is whatever id the event carried, see that event. + /// public string TimerId { get; set; } = string.Empty; public string? ProgramId { get; set; } + /// + /// The series rule that made this timer, as the Live TV API knows it (equal to SeriesRule.Id). + /// Null for one-off timers, and on timers built from a TimerCreated event. + /// + public string? SeriesTimerId { get; set; } + public string? ChannelName { get; set; } public DateTime StartDate { get; set; } @@ -511,13 +540,34 @@ public sealed class SuggestedShowing }; } -public enum ScheduleResult +public enum ScheduleOutcome { Created, AlreadyScheduled, Failed, } +/// +/// What scheduling a program did. For a created timer, TimerId is the service's own id (the kind +/// ScheduledTimer.TimerId and GetActiveRecordingPath use) and ApiId is the id the Live TV API and +/// clients know the timer by (ScheduledTimer.ApiId). On Emby the two are the same value. Either is +/// null when the lookup after creation found nothing; the timer exists regardless. A failure may +/// carry the server's reason in Error (an Emby Premiere refusal, say), for the client to show. +/// +public readonly record struct ScheduleResult(ScheduleOutcome Outcome, string? TimerId = null, string? ApiId = null, string? Error = null) +{ + public static ScheduleResult Created => new(ScheduleOutcome.Created); + + public static ScheduleResult AlreadyScheduled => new(ScheduleOutcome.AlreadyScheduled); + + public static ScheduleResult Failed => new(ScheduleOutcome.Failed); + + /// A failure with the server's reason, when it gave one. + public static ScheduleResult FailedWith(string? error) => new(ScheduleOutcome.Failed, Error: string.IsNullOrWhiteSpace(error) ? null : error); + + public static ScheduleResult CreatedWith(string? timerId, string? apiId) => new(ScheduleOutcome.Created, timerId, apiId); +} + /// Server-wide settings for the feature. public sealed class IncompleteRecordingSettings { diff --git a/shared/LiveTv/IncompleteRecordingService.cs b/shared/LiveTv/IncompleteRecordingService.cs index 852106d9..c31fc603 100644 --- a/shared/LiveTv/IncompleteRecordingService.cs +++ b/shared/LiveTv/IncompleteRecordingService.cs @@ -34,6 +34,10 @@ public sealed class IncompleteRecordingService : IDisposable private readonly Func _utcNow; private readonly string _storePath; private readonly Func _settings; + + // The recording owners feature, when the host has one. Called while holding _lock, which is + // the only allowed order: it never calls back into this service. + private readonly IRecordingOwners? _owners; private readonly SemaphoreSlim _lock = new(1, 1); // Copies this service deleted, so their removal isn't logged as happening outside Moonfin. @@ -81,7 +85,8 @@ public IncompleteRecordingService( IStateFile stateFile, Func utcNow, string storePath, - Func settings) + Func settings, + IRecordingOwners? owners = null) { _host = host; _logger = logger; @@ -89,6 +94,7 @@ public IncompleteRecordingService( _utcNow = utcNow; _storePath = storePath; _settings = settings; + _owners = owners; _processStart = Now; } @@ -225,6 +231,7 @@ public async Task RunAsync(CancellationToken cancellationToken) changed |= await RetryUntagsAsync(data, cancellationToken).ConfigureAwait(false); changed |= MarkStoppedRecordings(data); changed |= await JudgeClosedAsync(data, now, cancellationToken).ConfigureAwait(false); + changed |= GatherRecordingOwners(data); changed |= ApplySettings(data); // Without a current list of timers a search can't tell which showings already have @@ -510,12 +517,23 @@ public async Task DismissAsync(Guid itemId, Guid userId, CancellationToken } request.Explicit = true; + AddOwner(request, userId); if (_timersStale || _timersLoadedAt == null) { await ReloadTimersAsync(cancellationToken).ConfigureAwait(false); } await SearchAsync(data, now, false, cancellationToken).ConfigureAwait(false); + + // Joining a request whose showing is already booked makes the caller an owner of its + // timer too. Only the caller: the rest were added when the timer was scheduled or + // adopted, and any who left it since stay off. + if (request.State == CompleteShowingState.Scheduled && request.ScheduledProgramId != null) + { + ShareOwners(request, LiveTimerIdFor(request.ScheduledProgramId), new[] { userId }); + } + + PruneDeletedOwners(request); Save(data); ScheduleNextRun(data, Now); var response = request.Copy(); @@ -621,7 +639,9 @@ public async Task ScheduleSuggestedShowingAsync(string programId, Suggeste && LiveTimerFor(bookedId) != null && VisibleProgram(bookedId, userId) is { } booked) { request!.Explicit = true; + AddOwner(request, userId); SetScheduled(request, booked); + ShareOwners(request, LiveTimerIdFor(bookedId), new[] { userId }); Save(data); ScheduleNextRun(data, Now); _logger.Info("A user confirmed the showing of {Recording} already booked at {Start} on {Channel}", name, booked.StartDate, booked.ChannelName); @@ -659,18 +679,26 @@ public async Task ScheduleSuggestedShowingAsync(string programId, Suggeste var previousExplicit = request?.Explicit ?? false; if (source.Key != null) { - request ??= new CompleteShowingRequest { Episode = source.Key, OpenedAt = Now, RequestedByUserId = userId }; + request ??= new CompleteShowingRequest + { + Episode = source.Key, + OpenedAt = Now, + RequestedByUserId = userId, + OwnerUserIds = { userId }, + }; if (createdRequest) data.Requests.Add(request); request.Explicit = true; request.PendingProgramId = candidate.Id; Save(data); } - if (LiveTimerFor(candidate.Id) == null) + var timerId = LiveTimerIdFor(candidate.Id); + if (timerId == null) { var result = await _host.ScheduleProgramAsync(candidate.Id, cancellationToken).ConfigureAwait(false); _timersStale = true; - if (result == ScheduleResult.Failed) + timerId = result.TimerId ?? result.ApiId; + if (result.Outcome == ScheduleOutcome.Failed) { if (request != null) { @@ -692,13 +720,16 @@ public async Task ScheduleSuggestedShowingAsync(string programId, Suggeste if (request != null) { + AddOwner(request, userId); SetScheduled(request, candidate); + ShareOwners(request, timerId); Save(data); ScheduleNextRun(data, Now); _logger.Info("Recording the confirmed showing of {Recording} at {Start} on {Channel}", name, candidate.StartDate, candidate.ChannelName); } else { + ShareOwners(new[] { userId }, timerId); _logger.Info( "Recording the confirmed showing of {Recording} at {Start} on {Channel}, a possible future airing that isn't followed for recovery or deletion", name, candidate.StartDate, candidate.ChannelName); @@ -717,6 +748,152 @@ public async Task ScheduleSuggestedShowingAsync(string programId, Suggeste private GuideProgram? VisibleProgram(string programId, Guid userId) => _host.GetProgram(programId) is { } program && CanSeeProgram(program, userId) ? program : null; + private static bool AddOwner(CompleteShowingRequest request, Guid userId) + { + if (userId == Guid.Empty || request.OwnerUserIds.Contains(userId)) + { + return false; + } + + request.OwnerUserIds.Add(userId); + return true; + } + + private string? LiveTimerIdFor(string programId) => + LiveTimerFor(programId) is { } timer ? (string.IsNullOrEmpty(timer.ApiId) ? timer.TimerId : timer.ApiId) : null; + + // The timer a request newly scheduled or adopted belongs to everyone waiting for it, so the + // recording does too. A timer that already had them gets only the owners just added, so + // anyone who left it isn't put back. + private void ShareOwners(CompleteShowingRequest request, string? timerId, IReadOnlyCollection? added = null) + { + PruneDeletedOwners(request); + ShareOwners((added ?? request.OwnerUserIds).Where(id => request.OwnerUserIds.Contains(id)).ToList(), timerId); + } + + // Deleted users are dropped from a request's owners when it next hands them out. Only a user + // the server definitely doesn't have: a lookup that fails or can't tell keeps the owner. + private bool PruneDeletedOwners(CompleteShowingRequest request) => + request.OwnerUserIds.RemoveAll(UserIsGone) > 0; + + private bool UserIsGone(Guid userId) + { + try + { + return _host.UserExists(userId) == false; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not check whether user {UserId} still exists; keeping them as an owner", userId); + return false; + } + } + + private void ShareOwners(IReadOnlyCollection owners, string? timerId) + { + if (_owners == null || string.IsNullOrEmpty(timerId) || owners.Count == 0) + { + return; + } + + try + { + _owners.AddTimerOwners(timerId!, owners); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not add the owners waiting for a later showing to timer {TimerId}", timerId); + } + } + + private IReadOnlyList OwnersOfItems(IEnumerable itemIds) + { + if (_owners == null) + { + return Array.Empty(); + } + + try + { + return _owners.OwnersOfItems(itemIds); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not look up who owns an incomplete recording"); + return Array.Empty(); + } + } + + // Owners of an incomplete recording are often known only once its library items arrive, after + // the request it opened, so each pass gathers them into its open request and onto the timer + // already scheduled for it. + private bool GatherRecordingOwners(IncompleteRecordingStoreData data) + { + if (_owners == null) + { + return false; + } + + var changed = false; + foreach (var request in data.Requests.Where(r => CompleteShowingState.IsOpen(r.State))) + { + var itemIds = data.Records.Where(r => r.RequestId == request.Id).SelectMany(r => r.ItemIds).ToList(); + if (itemIds.Count == 0) + { + continue; + } + + var added = OwnersOfItems(itemIds).Where(owner => AddOwner(request, owner)).ToList(); + if (added.Count == 0) + { + continue; + } + + changed = true; + if (request.State == CompleteShowingState.Scheduled && request.ScheduledProgramId != null) + { + ShareOwners(request, LiveTimerIdFor(request.ScheduledProgramId), added); + } + } + + return changed; + } + + /// + /// The request's owners other than the given user, as the client shows them ("Jordan is also + /// waiting for this"). Disabled and deleted users are left out, and nobody is listed while the + /// recording owners feature is off. + /// + public IReadOnlyList OtherOwners(CompleteShowingRequest request, Guid userId, bool ownersEnabled) + { + var result = new List(); + if (!ownersEnabled) + { + return result; + } + + foreach (var owner in request.OwnerUserIds.Where(id => id != userId).Distinct()) + { + ServerUser? user; + try + { + user = _host.GetUser(owner); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not read user {UserId}, so they are left out of the other owners shown", owner); + continue; + } + + if (user is { IsDisabled: false }) + { + result.Add(new OwnerInfo(user.Id, user.Name, user.PrimaryImageTag)); + } + } + + return result; + } + private string CancellationVersion(IncompleteRecordingStoreData data, string programId) { var request = data.Requests.LastOrDefault(r => r.State == CompleteShowingState.CancelledByUser @@ -1257,7 +1434,7 @@ private async Task OnIncompleteRecordingAsync(IncompleteRecordingStoreData data, if (snapshot.Episode != null) { - record.RequestId = LinkRequest(data, snapshot, now)?.Id; + record.RequestId = LinkRequest(data, snapshot, record, now)?.Id; } else { @@ -1279,7 +1456,7 @@ private async Task OnIncompleteRecordingAsync(IncompleteRecordingStoreData data, } } - private CompleteShowingRequest? LinkRequest(IncompleteRecordingStoreData data, RecordingSnapshot snapshot, DateTime now) + private CompleteShowingRequest? LinkRequest(IncompleteRecordingStoreData data, RecordingSnapshot snapshot, IncompleteRecord record, DateTime now) { var episode = snapshot.Episode!; var scheduled = data.Requests.FirstOrDefault(r => r.State == CompleteShowingState.Scheduled @@ -1319,6 +1496,7 @@ private async Task OnIncompleteRecordingAsync(IncompleteRecordingStoreData data, } var request = new CompleteShowingRequest { Episode = episode, OpenedAt = now }; + request.OwnerUserIds.AddRange(OwnersOfItems(record.ItemIds)); data.Requests.Add(request); _searchNow.Add(request.Id); _logger.Info("Looking for a later showing of {Recording}", Describe(episode)); @@ -1440,6 +1618,7 @@ private bool TrackScheduledRequests(IncompleteRecordingStoreData data, DateTime if (moved != null) { SetScheduled(request, moved); + ShareOwners(request, LiveTimerIdFor(moved.Id)); _logger.Info( "Following {Recording} to {Start} on {Channel}: the series rule moved its recording there", Describe(request.Episode), moved.StartDate, moved.ChannelName); @@ -1533,6 +1712,7 @@ private async Task SearchAsync(IncompleteRecordingStoreData data, DateTime var changed = false; var askedServer = false; + var unresolvedOwners = new List(); foreach (var request in data.Requests.Where(r => r.State == CompleteShowingState.Waiting).ToList()) { if (!searchAll && !_searchNow.Contains(request.Id) && request.PendingProgramId == null) @@ -1601,14 +1781,16 @@ private async Task SearchAsync(IncompleteRecordingStoreData data, DateTime // A showing that already has a timer, whoever made it, is adopted and followed like // one the plugin scheduled, and uses an attempt the same way. - if (LiveTimerFor(showing.Id) == null) + var timerId = LiveTimerIdFor(showing.Id); + if (timerId == null) { request.PendingProgramId = showing.Id; Save(data); var result = await _host.ScheduleProgramAsync(showing.Id, cancellationToken).ConfigureAwait(false); askedServer = true; - if (result == ScheduleResult.Failed) + timerId = result.TimerId ?? result.ApiId; + if (result.Outcome == ScheduleOutcome.Failed) { changed = true; if (retrying != showing.Id) @@ -1625,6 +1807,15 @@ private async Task SearchAsync(IncompleteRecordingStoreData data, DateTime SetScheduled(request, showing); changed = true; + if (timerId != null) + { + ShareOwners(request, timerId); + } + else + { + // Already scheduled on the server but not in the cache yet: found after the reload below. + unresolvedOwners.Add(request); + } _logger.Info( "Following a later showing of {Recording} at {Start} on {Channel}", @@ -1640,6 +1831,11 @@ private async Task SearchAsync(IncompleteRecordingStoreData data, DateTime await ReloadTimersAsync(cancellationToken).ConfigureAwait(false); } + foreach (var request in unresolvedOwners.Where(r => r.ScheduledProgramId != null)) + { + ShareOwners(request, LiveTimerIdFor(request.ScheduledProgramId!)); + } + return changed; } @@ -1789,6 +1985,17 @@ private IncompleteRecordingStoreData Load() _data = _stateFile.Read(_storePath, json => JsonSerializer.Deserialize(json, JsonOptions)) ?? new IncompleteRecordingStoreData(); + + // Files written before requests had owners name only the user who asked. + foreach (var request in _data.Requests) + { + request.OwnerUserIds ??= new(); + if (request.OwnerUserIds.Count == 0 && request.RequestedByUserId is { } requestedBy) + { + request.OwnerUserIds.Add(requestedBy); + } + } + RefreshTracked(_data); return _data; } diff --git a/shared/LiveTv/RecordingOwnershipModels.cs b/shared/LiveTv/RecordingOwnershipModels.cs new file mode 100644 index 00000000..d8f7340f --- /dev/null +++ b/shared/LiveTv/RecordingOwnershipModels.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Moonfin.LiveTv; + +/// +/// A series recording rule as the server holds it. Id is the Live TV API id clients see +/// (SeriesTimerInfoDto.Id) and matches ScheduledTimer.SeriesTimerId. SeriesId is the guide's +/// series id on Emby and always null on Jellyfin, whose public DTO doesn't carry it, so callers +/// must not rely on it. +/// +public sealed record SeriesRule(string Id, string? SeriesId, string? Name); + +/// A server account, with only what the recording owner features need. +public sealed record ServerUser(Guid Id, string Name, string? PrimaryImageTag, bool IsDisabled); + +/// +/// Everything the recording owners feature persists, kept in one file. Timers are keyed by the API +/// id clients see (ScheduledTimer.ApiId), series rules by SeriesRule.Id and recordings by their +/// library item id. Each value is the owning users' ids, first owner first. +/// +public sealed class OwnershipStoreData +{ + /// + /// The file's format. A file with a higher version than this build writes is read but never + /// overwritten (see ). + /// + public int Version { get; set; } = 1; + + public Dictionary> Timers { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary> SeriesTimers { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary> Items { get; set; } = new(); + + /// The file each owned timer wrote, by timer API id, so the finished item can find its owners. + public Dictionary TimerPaths { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// Owners of recordings removed from the library, kept for a while in case they come back. + public Dictionary Removed { get; set; } = new(); + + /// + /// The service's own id of each owned timer, by API id, so a cancel event carrying the service + /// id still resolves after the timer has left the server's listing or the server restarted. + /// + public Dictionary TimerServiceIds { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// When each owned timer without a recorded file was first found missing from the server's listing. + public Dictionary TimersMissingSince { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// When each owned series rule was first found missing from the server's listing. + public Dictionary SeriesTimersMissingSince { get; set; } = new(StringComparer.OrdinalIgnoreCase); + + /// Members a newer plugin wrote that this one doesn't know, kept so a save doesn't drop them. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// The owners of a recording that left the library, and when it left. +public sealed class RemovedItem +{ + public List Owners { get; set; } = new(); + + public DateTime RemovedAt { get; set; } + + /// Members a newer plugin wrote that this one doesn't know, kept so a save doesn't drop them. + [JsonExtensionData] + public Dictionary? Extra { get; set; } +} + +/// An owner as clients show it: display name and profile image tag. +public sealed record OwnerInfo(Guid UserId, string Name, string? ImageTag); + +public enum OwnedKind +{ + Timer, + Series, + Item, +} + +/// What recording or joining did: the timer or rule id, its owners now, and whether it already existed. +public sealed record OwnershipOutcome(string Id, IReadOnlyList Owners, bool Joined); + +/// +/// A series rule the host created: its API id, or null when it couldn't be created or found, with +/// the server's reason when it refused. +/// +public readonly record struct SeriesRuleCreation(string? RuleId, string? Error = null) +{ + public static SeriesRuleCreation Failed(string? error) => new(null, string.IsNullOrWhiteSpace(error) ? null : error); +} + +/// +/// A record call's result: the outcome, or null with the server's reason for refusing when it +/// gave one, so the endpoint can pass it on (an Emby Premiere refusal, a tuner conflict). +/// +public sealed record OwnershipAttempt(OwnershipOutcome? Outcome, string? Error = null) +{ + /// The server's reason, or the fallback when it gave none. + public string ErrorOr(string fallback) => string.IsNullOrWhiteSpace(Error) ? fallback : Error!; +} + +/// +/// Owners per requested id. Ids with no owners the caller may see are left out. RecordingItemIds +/// are the requested items that are Live TV recordings the caller may see, owned or not, so a +/// client can offer to claim an unowned one; null when the server can't tell for some item. +/// +public sealed record OwnersLookup( + IReadOnlyDictionary> Timers, + IReadOnlyDictionary> SeriesTimers, + IReadOnlyDictionary> Items, + IReadOnlyList? RecordingItemIds = null); + +/// Everything a user owns. +public sealed record MineResult(IReadOnlyList TimerIds, IReadOnlyList SeriesTimerIds, IReadOnlyList ItemIds); + +/// +/// The owner calls the incomplete recordings feature makes. They take the owners lock synchronously, +/// so the owners service must never call back into that feature while holding it. +/// +public interface IRecordingOwners +{ + /// Everyone who owns any of the given recordings. + IReadOnlyList OwnersOfItems(IEnumerable itemIds); + + /// Adds owners to a timer, by either of its ids. + void AddTimerOwners(string timerId, IEnumerable owners); +} diff --git a/shared/LiveTv/RecordingOwnershipService.cs b/shared/LiveTv/RecordingOwnershipService.cs new file mode 100644 index 00000000..ba42904f --- /dev/null +++ b/shared/LiveTv/RecordingOwnershipService.cs @@ -0,0 +1,1899 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace Moonfin.LiveTv; + +/// +/// Tracks which users own each Live TV timer, series rule and finished recording. The server stores +/// no user on any of them, so ownership is recorded when a user schedules or claims something +/// through the plugin and follows the recording from timer to library item. +/// +/// All state lives in one JSON file and every read and write goes through one lock, the same +/// pattern as . Each finished recording also carries one +/// "Recorded by name" tag per owner, a readable backup the store can be rebuilt from when the file +/// and its backup are both lost. Owners are only ever added by a timer moving between series rules; +/// nothing is forgotten because it is missing at the moment, only on the server's cancel and removal +/// events or once it is gone and its recording has been attached. +/// +public sealed class RecordingOwnershipService : IRecordingOwners, IDisposable +{ + /// The state file's name inside the plugin's data folder. + public const string StoreFileName = "livetv-recording-owners.json"; + + /// + /// The store format this build writes. A file with a higher version came from a newer plugin + /// (this one is running after a downgrade): it is read, but never saved over, so the newer + /// plugin finds its data intact after an upgrade. Changes made meanwhile last until restart. + /// + public const int CurrentVersion = 1; + + /// The fixed, non-localized start of each owner tag, so a rebuild can parse it. + public const string TagPrefix = "Recorded by "; + + /// Whether a tag is one of the owner tags this feature stamps on recordings. + public static bool IsOwnerTag(string? tag) => + tag != null && tag.StartsWith(TagPrefix, StringComparison.OrdinalIgnoreCase); + + /// + /// An item's tags without the owner tags. Those say who recorded it, not what it is, so + /// similar-items scoring and smart search leave them out. + /// + public static IReadOnlyList WithoutOwnerTags(IEnumerable? tags) => + tags == null ? Array.Empty() : tags.Where(t => !IsOwnerTag(t)).ToList(); + + /// How long a removed recording's owners are kept in case the item comes back. + public static readonly TimeSpan RemovedRetention = TimeSpan.FromDays(7); + + /// + /// How much later than its removal a returning file may have been written and still count as + /// the same recording, for clock drift between the server and the storage holding the file. + /// + public static readonly TimeSpan FileClockTolerance = TimeSpan.FromMinutes(1); + + /// + /// How long after a finished timer's window its file may still be written (a post-processing + /// remux, say) and still be that timer's recording. A file written later at the same path is a + /// new recording, a rerun, that the finished timer must not claim. + /// + public static readonly TimeSpan PostRecordingAllowance = TimeSpan.FromHours(1); + + // At or before this a file time means none: .NET reports 1601-01-01 for a file it can't stat. + private static readonly DateTime UnknownFileTime = new(1601, 1, 2, 0, 0, 0, DateTimeKind.Utc); + + private const string StatusCancelled = "Cancelled"; + private const string StatusCompleted = "Completed"; + private const string StatusInProgress = "InProgress"; + + // Matches AtomicFile.BackupPath in both servers' IStateFile implementations. + private const string BackupSuffix = ".bak"; + + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = false }; + + private readonly ILiveTvRecordingHost _host; + private readonly IRecordingLog _logger; + private readonly IStateFile _stateFile; + private readonly Func _utcNow; + private readonly Func _storePathProvider; + private readonly Func _enabled; + private readonly SemaphoreSlim _lock = new(1, 1); + + // Everything below is guarded by _lock. + + // Any timer id, service or API kind, to the API id the store keys timers by. Events carry + // either kind, so each is resolved against both. Refreshed whenever the timers are listed. + private readonly Dictionary _apiIds = new(StringComparer.OrdinalIgnoreCase); + + // The timers as last listed, by API id. + private readonly Dictionary _timers = new(StringComparer.OrdinalIgnoreCase); + + // Each user's name as last seen, so a rename knows which tag to replace and a deleted user's + // tags can still be found. + private readonly Dictionary _userNames = new(); + + // Owned timers whose service id the last listing couldn't map. Listing again for a cancel + // only helps when an owned timer has become unmapped since. + private readonly HashSet _unmappedAtLastListing = new(StringComparer.OrdinalIgnoreCase); + + // The library item each owned timer's recording became, as seen by this process, so removing + // that item can forget the finished timer instead of leaving it to claim the path's next file. + private readonly Dictionary _timerItems = new(StringComparer.OrdinalIgnoreCase); + + private OwnershipStoreData? _data; + + // Set when the store was rebuilt from tags: the unusable file must be copied aside before the + // first save overwrites it. + private bool _preserveUnusable; + + // Set when the store came from a newer plugin, which must find it as it left it. + private bool _readOnly; + private volatile bool _recordingInProgress; + private long _nextTimerStartTicks; + + public RecordingOwnershipService( + ILiveTvRecordingHost host, + IRecordingLog log, + IStateFile stateFile, + Func now, + string storePath, + Func enabled) + : this(host, log, stateFile, now, () => storePath, enabled) + { + } + + /// + /// As the main constructor, but the store path is asked for each time it is needed, so a + /// host whose data folder isn't known yet can throw instead of the file landing somewhere + /// it must not. + /// + public RecordingOwnershipService( + ILiveTvRecordingHost host, + IRecordingLog log, + IStateFile stateFile, + Func now, + Func storePathProvider, + Func enabled) + { + _host = host; + _logger = log; + _stateFile = stateFile; + _utcNow = now; + _storePathProvider = storePathProvider; + _enabled = enabled; + } + + private string _storePath => _storePathProvider(); + + /// Whether any timer was recording at the last sync, so the watcher can sync often enough to catch its file. + public bool HasRecordingInProgress => _recordingInProgress && Enabled; + + /// + /// The earliest recording window start, at the last listing, that began no more than ten + /// minutes before that listing and isn't cancelled; null when there is none. The watcher syncs + /// often around it, since a recording's file is only captured while a sync sees it in progress. + /// + public DateTime? NextTimerStart + { + get + { + var ticks = Interlocked.Read(ref _nextTimerStartTicks); + return ticks == 0 ? null : new DateTime(ticks, DateTimeKind.Utc); + } + } + + private bool Enabled => _enabled(); + + public void Dispose() => _lock.Dispose(); + + /// + /// Records a program for a user: joins the timer that already records it, or schedules one. + /// Null when the feature is off or the server couldn't schedule it. + /// + public async Task RecordProgramAsync(string programId, Guid userId, CancellationToken ct) => + (await TryRecordProgramAsync(programId, userId, ct).ConfigureAwait(false)).Outcome; + + /// As , with the server's reason when it refused to schedule. + public async Task TryRecordProgramAsync(string programId, Guid userId, CancellationToken ct) + { + if (!Enabled || string.IsNullOrEmpty(programId)) + { + return new OwnershipAttempt(null); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + var existing = FindLiveTimerForProgram(await RefreshTimersAsync(ct).ConfigureAwait(false), programId); + if (existing != null) + { + var joinedId = ApiIdOf(existing); + AddOwners(data.Timers, joinedId, new[] { userId }); + Track(data, existing); + Save(data); + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + _logger.Info("User {UserId} joined the recording of program {ProgramId} (timer {TimerId})", userId, programId, joinedId); + return new OwnershipAttempt(new OwnershipOutcome(joinedId, ToOwnerInfos(data.Timers, joinedId), true)); + } + + var result = await _host.ScheduleProgramAsync(programId, ct).ConfigureAwait(false); + if (result.Outcome == ScheduleOutcome.Failed) + { + _logger.Warn(null, "Could not schedule program {ProgramId} for user {UserId}", programId, userId); + return new OwnershipAttempt(null, result.Error); + } + + // A timer someone else made between the listing and the schedule call, or one the + // server returned no ids for: either way the listing now has it. + var timers = await RefreshTimersAsync(ct).ConfigureAwait(false); + var timer = result.ApiId != null && _timers.TryGetValue(result.ApiId, out var byApi) + ? byApi + : result.TimerId != null && _apiIds.TryGetValue(result.TimerId, out var mapped) && _timers.TryGetValue(mapped, out var byService) + ? byService + : FindLiveTimerForProgram(timers, programId); + var timerId = result.ApiId ?? (timer != null ? ApiIdOf(timer) : null); + if (timerId == null) + { + _logger.Warn(null, "Scheduled program {ProgramId} for user {UserId} but could not find its timer, so it has no owner", programId, userId); + return new OwnershipAttempt(null); + } + + var joined = result.Outcome == ScheduleOutcome.AlreadyScheduled; + AddOwners(data.Timers, timerId, new[] { userId }); + if (timer != null) + { + Track(data, timer); + } + else if (!string.IsNullOrEmpty(result.TimerId)) + { + RememberServiceId(data, timerId, result.TimerId!); + } + + Save(data); + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + _logger.Info("User {UserId} {Action} program {ProgramId} (timer {TimerId})", userId, joined ? "joined the recording of" : "scheduled", programId, timerId); + return new OwnershipAttempt(new OwnershipOutcome(timerId, ToOwnerInfos(data.Timers, timerId), joined)); + } + finally + { + _lock.Release(); + } + } + + /// + /// Records a program's series for a user: joins the rule that already records the series, + /// ignoring the settings, or creates one with them. Null when the feature is off, the program + /// is unknown or the server couldn't create the rule. + /// + public async Task RecordSeriesAsync(string programId, Guid userId, IReadOnlyDictionary? settings, CancellationToken ct) => + (await TryRecordSeriesAsync(programId, userId, settings, ct).ConfigureAwait(false)).Outcome; + + /// As , with the server's reason when it refused to create the rule. + public async Task TryRecordSeriesAsync(string programId, Guid userId, IReadOnlyDictionary? settings, CancellationToken ct) + { + if (!Enabled || string.IsNullOrEmpty(programId)) + { + return new OwnershipAttempt(null); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + var program = _host.GetProgram(programId); + if (program == null) + { + _logger.Warn(null, "Could not record the series of program {ProgramId} for user {UserId}: the program isn't in the guide", programId, userId); + return new OwnershipAttempt(null); + } + + var timers = await RefreshTimersAsync(ct).ConfigureAwait(false); + var rules = await _host.GetSeriesTimersAsync(ct).ConfigureAwait(false); + var ruleId = FindRuleForSeries(program, timers, rules); + var joined = ruleId != null; + if (ruleId == null) + { + var creation = await _host.CreateSeriesTimerAsync(programId, settings, ct).ConfigureAwait(false); + ruleId = creation.RuleId; + if (ruleId == null) + { + _logger.Warn(null, "Could not create a series rule from program {ProgramId} for user {UserId}", programId, userId); + return new OwnershipAttempt(null, creation.Error); + } + + // The new rule's timers exist now; list them so its owners reach them right away. + timers = await RefreshTimersAsync(ct).ConfigureAwait(false); + } + + AddOwners(data.SeriesTimers, ruleId, new[] { userId }); + ApplySeriesOwners(data, timers); + Save(data); + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + _logger.Info("User {UserId} {Action} series rule {RuleId} from program {ProgramId}", userId, joined ? "joined" : "created", ruleId, programId); + return new OwnershipAttempt(new OwnershipOutcome(ruleId, ToOwnerInfos(data.SeriesTimers, ruleId), joined)); + } + finally + { + _lock.Release(); + } + } + + /// + /// Adds a user to the owners of an existing timer, series rule or recording, and for a + /// recording stamps the user's tag. Null when the feature is off or the object doesn't exist. + /// + public async Task?> ClaimAsync(OwnedKind kind, string id, Guid userId, CancellationToken ct) + { + if (!Enabled || string.IsNullOrEmpty(id)) + { + return null; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + switch (kind) + { + case OwnedKind.Timer: + { + var timer = await FindTimerAsync(id, ct).ConfigureAwait(false); + if (timer == null || timer.Status == StatusCancelled) + { + return null; + } + + var timerId = ApiIdOf(timer); + AddOwners(data.Timers, timerId, new[] { userId }); + Track(data, timer); + Save(data); + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + _logger.Info("User {UserId} claimed timer {TimerId}", userId, timerId); + return ToOwnerInfos(data.Timers, timerId); + } + + case OwnedKind.Series: + { + var rules = await _host.GetSeriesTimersAsync(ct).ConfigureAwait(false); + var rule = rules.FirstOrDefault(r => string.Equals(r.Id, id, StringComparison.OrdinalIgnoreCase)); + if (rule == null) + { + return null; + } + + AddOwners(data.SeriesTimers, rule.Id, new[] { userId }); + ApplySeriesOwners(data, await RefreshTimersAsync(ct).ConfigureAwait(false)); + Save(data); + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + _logger.Info("User {UserId} claimed series rule {RuleId}", userId, rule.Id); + return ToOwnerInfos(data.SeriesTimers, rule.Id); + } + + case OwnedKind.Item: + { + // Only a Live TV recording can be claimed; a server that can't tell allows it. + if (!Guid.TryParse(id, out var itemId) || _host.GetTags(itemId) == null || IsRecording(itemId) == false) + { + return null; + } + + AddOwners(data.Items, itemId, new[] { userId }); + Save(data); + await StampTagsAsync(itemId, new[] { userId }, ct).ConfigureAwait(false); + _logger.Info("User {UserId} claimed recording {ItemId}", userId, itemId); + return ToOwnerInfos(data.Items, itemId); + } + + default: + return null; + } + } + finally + { + _lock.Release(); + } + } + + /// + /// Owners of the given timers, rules and recordings, for the ones the caller may see. Disabled + /// users and ids without owners are left out. Also lists which of the given items are Live TV + /// recordings the caller may see, owned or not, or null when the server can't tell for one. + /// + public async Task LookupAsync( + IReadOnlyCollection timerIds, + IReadOnlyCollection seriesTimerIds, + IReadOnlyCollection itemIds, + Guid callerId, + CancellationToken ct) + { + var timerOwners = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var seriesOwners = new Dictionary>(StringComparer.OrdinalIgnoreCase); + var itemOwners = new Dictionary>(); + if (!Enabled) + { + return new OwnersLookup(timerOwners, seriesOwners, itemOwners); + } + + // Needs no owner state, so it is worked out before taking the lock. + var lookup = new OwnersLookup(timerOwners, seriesOwners, itemOwners, RecordingsVisibleTo(itemIds, callerId)); + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + + var ownedItems = itemIds.Distinct().Where(data.Items.ContainsKey).ToList(); + if (ownedItems.Count > 0) + { + foreach (var itemId in _host.VisibleTo(ownedItems, callerId)) + { + AddIfAny(itemOwners, itemId, ToOwnerInfos(data.Items, itemId)); + } + } + + var ownedTimers = timerIds.Distinct(StringComparer.OrdinalIgnoreCase) + .Where(id => data.Timers.ContainsKey(Resolve(id)) || !_apiIds.ContainsKey(id)) + .ToList(); + if (ownedTimers.Count > 0) + { + // A timer the last listing didn't have may be new; list once more before giving up on it. + if (ownedTimers.Any(id => !_apiIds.ContainsKey(id))) + { + await RefreshTimersAsync(ct).ConfigureAwait(false); + } + + foreach (var id in ownedTimers) + { + var key = Resolve(id); + if (data.Timers.ContainsKey(key) + && _timers.TryGetValue(key, out var timer) + && timer.ProgramId != null + && _host.GetProgram(timer.ProgramId) is { } program + && _host.IsVisibleTo(program.ItemId, callerId)) + { + AddIfAny(timerOwners, id, ToOwnerInfos(data.Timers, key)); + } + } + } + + // Anyone who can use Live TV can list every series rule, so a rule the server lists is + // answered for whoever asks. + var ownedRules = seriesTimerIds.Distinct(StringComparer.OrdinalIgnoreCase).Where(data.SeriesTimers.ContainsKey).ToList(); + if (ownedRules.Count > 0) + { + var listed = (await _host.GetSeriesTimersAsync(ct).ConfigureAwait(false)) + .Select(r => r.Id) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var id in ownedRules.Where(listed.Contains)) + { + AddIfAny(seriesOwners, id, ToOwnerInfos(data.SeriesTimers, id)); + } + } + + return lookup; + } + finally + { + _lock.Release(); + } + } + + /// Every timer, rule and recording that lists the user as an owner. + public async Task GetMineAsync(Guid userId, CancellationToken ct) + { + if (!Enabled) + { + return new MineResult(Array.Empty(), Array.Empty(), Array.Empty()); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + return new MineResult( + data.Timers.Where(e => e.Value.Contains(userId)).Select(e => e.Key).ToList(), + data.SeriesTimers.Where(e => e.Value.Contains(userId)).Select(e => e.Key).ToList(), + data.Items.Where(e => e.Value.Contains(userId)).Select(e => e.Key).ToList()); + } + finally + { + _lock.Release(); + } + } + + /// + /// Brings the store in line with the server: copies series owners onto their timers, notes the + /// file each owned timer is writing, forgets timers and rules the server is done with, and + /// purges old tombstones. + /// + public async Task SyncAsync(CancellationToken ct) + { + if (!Enabled) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + var changed = false; + var timers = await RefreshTimersAsync(ct).ConfigureAwait(false); + var rules = await _host.GetSeriesTimersAsync(ct).ConfigureAwait(false); + + var now = _utcNow(); + var cutoff = now - RemovedRetention; + + changed |= RekeyServiceIds(data); + changed |= ApplySeriesOwners(data, timers); + + foreach (var timer in timers) + { + changed |= Track(data, timer); + } + + // Jellyfin adds a recording's item when the recording starts, usually before the file + // is captured here, so the item's ItemAdded found no owners. Attach them now, before a + // finished timer is forgotten below. + changed |= await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + + // A timer is forgotten once the server is done with it and its recording has reached + // the library; until then the item may still arrive and need the owners. A done timer + // whose recording isn't in the library (deleted, or never scanned in) is forgotten + // after the retention, counted in TimersMissingSince from the first sync that found it + // so; kept, it would claim whatever is recorded to its path next. One without a + // recorded file is forgotten only after the server has left it out for the whole + // retention, since a listing can miss timers while a Live TV service is failing. + foreach (var key in data.Timers.Keys.ToList()) + { + var listed = _timers.TryGetValue(key, out var timer); + if (data.TimerPaths.TryGetValue(key, out var path)) + { + var done = !listed || timer!.Status == StatusCancelled || timer.Status == StatusCompleted; + if (!done) + { + changed |= data.TimersMissingSince.Remove(key); + } + else if (_host.FindItemByPath(path) != null) + { + data.Timers.Remove(key); + changed = true; + } + else if (!data.TimersMissingSince.TryGetValue(key, out var doneSince)) + { + data.TimersMissingSince[key] = now; + changed = true; + } + else if (doneSince <= cutoff) + { + data.Timers.Remove(key); + _logger.Info("Forgot finished timer {TimerId}, whose recording hasn't been in the library since {Since}", key, doneSince); + changed = true; + } + } + else if (listed) + { + changed |= data.TimersMissingSince.Remove(key); + } + else if (!data.TimersMissingSince.TryGetValue(key, out var missingSince)) + { + data.TimersMissingSince[key] = now; + changed = true; + } + else if (missingSince <= cutoff) + { + data.Timers.Remove(key); + _logger.Info("Forgot the owners of timer {TimerId}, which the server hasn't listed since {Since}", key, missingSince); + changed = true; + } + } + + var listedRules = rules.Select(r => r.Id).ToHashSet(StringComparer.OrdinalIgnoreCase); + foreach (var key in data.SeriesTimers.Keys.ToList()) + { + if (listedRules.Contains(key)) + { + changed |= data.SeriesTimersMissingSince.Remove(key); + } + else if (!data.SeriesTimersMissingSince.TryGetValue(key, out var missingSince)) + { + data.SeriesTimersMissingSince[key] = now; + changed = true; + } + else if (missingSince <= cutoff) + { + data.SeriesTimers.Remove(key); + _logger.Info("Forgot the owners of series rule {RuleId}, which the server hasn't listed since {Since}", key, missingSince); + changed = true; + } + } + + changed |= PruneSideTables(data); + foreach (var key in _timerItems.Keys.Where(k => !data.Timers.ContainsKey(k)).ToList()) + { + _timerItems.Remove(key); + } + + foreach (var entry in data.Removed.Where(e => e.Value.RemovedAt < cutoff).ToList()) + { + data.Removed.Remove(entry.Key); + changed = true; + } + + foreach (var user in _host.GetUsers()) + { + // Only users not seen yet: a rename's old name is kept until its event arrives. + if (!_userNames.ContainsKey(user.Id)) + { + _userNames[user.Id] = user.Name; + } + } + + if (changed) + { + Save(data); + } + } + finally + { + _lock.Release(); + } + } + + /// + /// A timer was cancelled, which is for everyone, so its owners are forgotten. A recording that + /// was stopped partway still reaches the library, so a timer whose file is known keeps its + /// owners until that item arrives. The server raises the cancel while the recording is still + /// running, so the watcher reads the file then and passes it as ; + /// an item already in the library for it takes the owners at once. + /// + public async Task OnTimerCancelledAsync(string timerId, string? activePath, CancellationToken ct) + { + if (!Enabled || string.IsNullOrEmpty(timerId)) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + if (!_apiIds.ContainsKey(timerId) && NeedsListingToResolve(data, timerId)) + { + await RefreshTimersAsync(ct).ConfigureAwait(false); + } + + var key = Resolve(timerId); + if (!data.Timers.ContainsKey(key)) + { + return; + } + + if (!string.IsNullOrEmpty(activePath) + && !(data.TimerPaths.TryGetValue(key, out var known) && string.Equals(known, activePath, StringComparison.OrdinalIgnoreCase))) + { + data.TimerPaths[key] = activePath!; + Save(data); + _logger.Info("Cancelled timer {TimerId} was recording {Path}; keeping its owners for that recording", key, activePath); + } + + if (data.TimerPaths.ContainsKey(key)) + { + await AttachToStartedRecordingsAsync(data, ct).ConfigureAwait(false); + return; + } + + data.Timers.Remove(key); + PruneSideTables(data); + Save(data); + _logger.Info("Forgot the owners of cancelled timer {TimerId}", key); + } + finally + { + _lock.Release(); + } + } + + /// As with no file known. + public Task OnTimerCancelledAsync(string timerId, CancellationToken ct) => OnTimerCancelledAsync(timerId, null, ct); + + /// + /// A library item arrived. A recording written by an owned timer takes that timer's owners; + /// otherwise a recording that left the library within the retention gets its owners back, + /// unless its file was written after it left (a new recording on the same path). Each owner's + /// tag is stamped on it. + /// + public async Task OnItemAddedAsync(LibraryItem item, CancellationToken ct) + { + if (!Enabled) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + var hasTombstone = data.Removed.TryGetValue(item.Id, out var removed); + var timerId = FindTimerForPath(data, item.Path); + var writtenAt = hasTombstone || (timerId != null && !IsLive(timerId)) ? FileWrittenAt(item.Id) : null; + + // The server derives an item's id from its path, so a rerun recorded to the file of a + // deleted recording comes back as that recording. Jellyfin adds the item as the + // recording starts, usually before a sync has seen its file, so the timers are listed + // again before the old owners, or a finished timer's, are taken back. A file known to + // be older than the removal is the old recording coming back, which no listing can + // change, so a storage outage's many returning items list nothing. + var returned = hasTombstone && writtenAt is { } written && written <= removed!.RemovedAt + FileClockTolerance; + if (hasTombstone && !returned && !string.IsNullOrEmpty(item.Path) && (timerId == null || !IsLive(timerId))) + { + try + { + foreach (var timer in await RefreshTimersAsync(ct).ConfigureAwait(false)) + { + Track(data, timer); + } + } + catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) + { + // Live TV may not be ready yet (a startup scan); decide from the last listing. + _logger.Warn(ex, "Could not list the timers while recording {ItemId} came back; deciding its owners from the last listing", item.Id); + } + + timerId = FindTimerForPath(data, item.Path); + } + + // A finished timer whose window ended well before this file was written didn't record it. + if (timerId != null && IsStaleMatch(data, timerId, writtenAt, removed)) + { + _logger.Info("Recording {ItemId} was written at {WrittenAt}, after finished timer {TimerId} that recorded its path; that timer's owners don't apply", item.Id, writtenAt, timerId); + timerId = null; + } + + List owners; + if (timerId != null) + { + _timerItems[timerId] = item.Id; + owners = data.Timers[timerId].ToList(); + _logger.Info("Recording {ItemId} from timer {TimerId} took its {Count} owner(s)", item.Id, timerId, owners.Count); + if (hasTombstone) + { + // A new recording on the old one's file: the old owners must not come back with it. + data.Removed.Remove(item.Id); + _logger.Info("Discarded the owners kept for removed recording {ItemId}, since timer {TimerId} recorded it again", item.Id, timerId); + } + } + else if (hasTombstone && writtenAt is { } newer && newer > removed!.RemovedAt + FileClockTolerance) + { + // A file written after its recording left the library is a new recording on the + // old one's path (a rerun by a timer nobody owns, or one not yet seen recording), + // not the old file coming back, so the old owners stay gone. + data.Removed.Remove(item.Id); + Save(data); + _logger.Info( + "Recording {ItemId} came back with a file written at {WrittenAt}, after it left the library at {RemovedAt}; it is a new recording, so the owners kept for the old one were discarded", + item.Id, + newer, + removed!.RemovedAt); + return; + } + else if (hasTombstone && removed!.RemovedAt >= _utcNow() - RemovedRetention) + { + owners = removed.Owners; + data.Removed.Remove(item.Id); + _logger.Info("Recording {ItemId} came back to the library; restored its {Count} owner(s)", item.Id, owners.Count); + } + else if (hasTombstone) + { + data.Removed.Remove(item.Id); + Save(data); + _logger.Info("Recording {ItemId} came back to the library after its owners were kept for {Days} days; it has no owners", item.Id, RemovedRetention.TotalDays); + return; + } + else + { + return; + } + + if (owners.Count == 0) + { + Save(data); + return; + } + + AddOwners(data.Items, item.Id, owners); + Save(data); + await StampTagsAsync(item.Id, owners, ct).ConfigureAwait(false); + } + finally + { + _lock.Release(); + } + } + + /// A recording left the library. Its owners are kept as a tombstone in case it comes back. + public async Task OnItemRemovedAsync(Guid itemId, CancellationToken ct) + { + if (!Enabled) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + if (!data.Items.TryGetValue(itemId, out var owners)) + { + return; + } + + data.Items.Remove(itemId); + data.Removed[itemId] = new RemovedItem { Owners = owners, RemovedAt = _utcNow() }; + + // A finished timer whose recording this was is done with: its owners now live in the + // tombstone, and kept, it would claim whatever is recorded to its path next. + foreach (var entry in _timerItems.Where(e => e.Value == itemId).ToList()) + { + _timerItems.Remove(entry.Key); + if (data.Timers.ContainsKey(entry.Key) + && !IsLive(entry.Key) + && (!data.TimerPaths.TryGetValue(entry.Key, out var path) || _host.FindItemByPath(path) == null)) + { + data.Timers.Remove(entry.Key); + _logger.Info("Forgot finished timer {TimerId} along with its removed recording {ItemId}", entry.Key, itemId); + } + } + + PruneSideTables(data); + Save(data); + _logger.Info("Recording {ItemId} left the library; keeping its owners for {Days} days in case it comes back", itemId, RemovedRetention.TotalDays); + } + finally + { + _lock.Release(); + } + } + + /// A user changed. A rename swaps the user's tag on every recording they own that still has it. + public async Task OnUserUpdatedAsync(ServerUser user, CancellationToken ct) + { + if (!Enabled) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + var known = _userNames.TryGetValue(user.Id, out var oldName); + _userNames[user.Id] = user.Name; + if (!known || string.Equals(oldName, user.Name, StringComparison.Ordinal)) + { + return; + } + + var oldTag = TagPrefix + oldName; + var newTag = TagPrefix + user.Name; + var renamed = 0; + foreach (var itemId in data.Items.Where(e => e.Value.Contains(user.Id)).Select(e => e.Key).ToList()) + { + // A tag removed outside Moonfin stays gone. + if (_host.GetTags(itemId)?.Contains(oldTag, StringComparer.OrdinalIgnoreCase) != true) + { + continue; + } + + if (!SharesName(data.Items[itemId], user.Id, oldName!)) + { + await SetTagAsync(itemId, oldTag, false, ct).ConfigureAwait(false); + } + + if (await SetTagAsync(itemId, newTag, true, ct).ConfigureAwait(false)) + { + renamed++; + } + } + + _logger.Info("User {UserId} was renamed from {OldName} to {NewName}; updated the tag on {Count} recording(s)", user.Id, oldName, user.Name, renamed); + } + finally + { + _lock.Release(); + } + } + + /// A user was deleted: they leave every owner set and their tags are removed. + public async Task OnUserDeletedAsync(Guid userId, CancellationToken ct) + { + if (!Enabled) + { + return; + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + var data = Load(); + _userNames.TryGetValue(userId, out var name); + var ownedItems = data.Items.Where(e => e.Value.Contains(userId)).Select(e => e.Key).ToList(); + + var changed = RemoveOwner(data.Timers, userId); + changed |= RemoveOwner(data.SeriesTimers, userId); + changed |= RemoveOwner(data.Items, userId); + foreach (var entry in data.Removed.ToList()) + { + if (entry.Value.Owners.Remove(userId)) + { + changed = true; + if (entry.Value.Owners.Count == 0) + { + data.Removed.Remove(entry.Key); + } + } + } + + if (changed) + { + Save(data); + } + + if (name != null) + { + var tag = TagPrefix + name; + foreach (var itemId in ownedItems) + { + var remaining = data.Items.TryGetValue(itemId, out var owners) ? owners : null; + if (remaining == null || !SharesName(remaining, userId, name)) + { + await SetTagAsync(itemId, tag, false, ct).ConfigureAwait(false); + } + } + } + else if (ownedItems.Count > 0) + { + _logger.Warn(null, "Deleted user {UserId} owned {Count} recording(s) but their name is unknown, so their tags were left", userId, ownedItems.Count); + } + + _userNames.Remove(userId); + if (changed) + { + _logger.Info("Removed deleted user {UserId} from every recording owner list", userId); + } + } + finally + { + _lock.Release(); + } + } + + /// + public IReadOnlyList OwnersOfItems(IEnumerable itemIds) + { + if (!Enabled) + { + return Array.Empty(); + } + + _lock.Wait(); + try + { + var data = Load(); + var result = new List(); + foreach (var itemId in itemIds) + { + if (data.Items.TryGetValue(itemId, out var owners)) + { + result.AddRange(owners.Where(o => !result.Contains(o))); + } + } + + return result; + } + finally + { + _lock.Release(); + } + } + + /// + public void AddTimerOwners(string timerId, IEnumerable owners) + { + if (!Enabled || string.IsNullOrEmpty(timerId)) + { + return; + } + + _lock.Wait(); + try + { + // An id the last listing didn't have is kept as given; the next sync's listing maps + // service ids, and Jellyfin's schedule call hands back the API id. + // A deleted user lingering in a request's owners is never put back on a timer; one + // whose lookup failed is kept, since a failed read doesn't mean the user is gone. + var data = Load(); + if (AddOwners(data.Timers, Resolve(timerId), owners.Where(o => !UserIsGone(o)).ToList())) + { + Save(data); + } + } + finally + { + _lock.Release(); + } + } + + private static string ApiIdOf(ScheduledTimer timer) => + string.IsNullOrEmpty(timer.ApiId) ? timer.TimerId : timer.ApiId!; + + private static ScheduledTimer? FindLiveTimerForProgram(IReadOnlyList timers, string programId) => + timers.FirstOrDefault(t => t.Status != StatusCancelled && string.Equals(t.ProgramId, programId, StringComparison.OrdinalIgnoreCase)); + + private static bool AddOwners(Dictionary> map, TKey key, IEnumerable owners) + where TKey : notnull + { + var added = false; + foreach (var owner in owners) + { + if (owner == Guid.Empty) + { + continue; + } + + if (!map.TryGetValue(key, out var list)) + { + list = new List(); + map[key] = list; + } + + if (!list.Contains(owner)) + { + list.Add(owner); + added = true; + } + } + + return added; + } + + private static bool RemoveOwner(Dictionary> map, Guid owner) + where TKey : notnull + { + var changed = false; + foreach (var entry in map.ToList()) + { + if (entry.Value.Remove(owner)) + { + changed = true; + if (entry.Value.Count == 0) + { + map.Remove(entry.Key); + } + } + } + + return changed; + } + + private static void AddIfAny(Dictionary> map, TKey key, IReadOnlyList owners) + where TKey : notnull + { + if (owners.Count > 0) + { + map[key] = owners; + } + } + + // The API id for any timer id: from the listings seen, else from the service ids stored with + // owned timers (which outlive the listing and a restart), else the id itself. + private string Resolve(string timerId) + { + if (_apiIds.TryGetValue(timerId, out var apiId)) + { + return apiId; + } + + if (_data != null) + { + foreach (var entry in _data.TimerServiceIds) + { + if (string.Equals(entry.Value, timerId, StringComparison.OrdinalIgnoreCase)) + { + return entry.Key; + } + } + } + + return timerId; + } + + // Lists the timers. The id map is merged rather than replaced, so a timer that leaves the + // listing (Jellyfin drops a cancelled one-off) still resolves from its service id; a mapping + // is pruned only once its timer is neither listed nor owned. + private async Task> RefreshTimersAsync(CancellationToken ct) + { + var timers = await _host.GetTimersAsync(ct).ConfigureAwait(false); + _timers.Clear(); + foreach (var timer in timers) + { + var apiId = ApiIdOf(timer); + if (string.IsNullOrEmpty(apiId)) + { + continue; + } + + _timers[apiId] = timer; + _apiIds[apiId] = apiId; + if (!string.IsNullOrEmpty(timer.TimerId)) + { + _apiIds[timer.TimerId] = apiId; + } + } + + foreach (var entry in _apiIds.ToList()) + { + if (!_timers.ContainsKey(entry.Value) && _data?.Timers.ContainsKey(entry.Value) != true) + { + _apiIds.Remove(entry.Key); + } + } + + _unmappedAtLastListing.Clear(); + if (_data != null) + { + _unmappedAtLastListing.UnionWith(_data.Timers.Keys.Where(k => !IsMapped(_data, k))); + } + + _recordingInProgress = timers.Any(t => t.Status == StatusInProgress); + var recentCutoff = _utcNow().AddMinutes(-10); + var starts = timers + .Where(t => t.Status != StatusCancelled && t.WindowStart.ToUniversalTime() >= recentCutoff) + .Select(t => t.WindowStart.ToUniversalTime()) + .ToList(); + Interlocked.Exchange(ref _nextTimerStartTicks, starts.Count == 0 ? 0 : starts.Min().Ticks); + return timers; + } + + // Whether a cancel event's id, unknown to the id map, could belong to an owned timer that only + // a fresh listing would reveal. Deleting a series rule raises one cancel per timer, nearly + // always for timers nobody owns, so this avoids a listing per event: there is nothing to find + // when nothing is owned, an owned id or a stored service id resolves without a listing, and a + // listing can only map an owned timer that has become unmapped since the last one. + private bool NeedsListingToResolve(OwnershipStoreData data, string timerId) + { + if (data.Timers.Count == 0 + || data.Timers.ContainsKey(timerId) + || data.TimerServiceIds.Values.Contains(timerId, StringComparer.OrdinalIgnoreCase)) + { + return false; + } + + return data.Timers.Keys.Any(k => !IsMapped(data, k) && !_unmappedAtLastListing.Contains(k)); + } + + // Whether both of an owned timer's ids are known: its service id is stored, or a listing or + // schedule call has mapped it (on Emby the two ids are one). + private bool IsMapped(OwnershipStoreData data, string key) => + data.TimerServiceIds.ContainsKey(key) + || _apiIds.Values.Contains(key, StringComparer.OrdinalIgnoreCase); + + private async Task FindTimerAsync(string id, CancellationToken ct) + { + if (!_apiIds.ContainsKey(id) || !_timers.ContainsKey(Resolve(id))) + { + await RefreshTimersAsync(ct).ConfigureAwait(false); + } + + return _timers.TryGetValue(Resolve(id), out var timer) ? timer : null; + } + + // Notes what an owned timer's later events and its recording need: its service id and the + // file it is writing. + private bool Track(OwnershipStoreData data, ScheduledTimer timer) + { + var key = ApiIdOf(timer); + if (!data.Timers.ContainsKey(key)) + { + return false; + } + + var changed = !string.IsNullOrEmpty(timer.TimerId) && RememberServiceId(data, key, timer.TimerId); + return CaptureActivePath(data, timer) | changed; + } + + private bool RememberServiceId(OwnershipStoreData data, string apiId, string serviceId) + { + _apiIds[serviceId] = apiId; + _apiIds[apiId] = apiId; + if (string.Equals(apiId, serviceId, StringComparison.OrdinalIgnoreCase) + || (data.TimerServiceIds.TryGetValue(apiId, out var known) && string.Equals(known, serviceId, StringComparison.OrdinalIgnoreCase))) + { + return false; + } + + data.TimerServiceIds[apiId] = serviceId; + return true; + } + + // Owners stored under a timer's service id (AddTimerOwners before a listing had the timer) + // move to its API id, joining any owners already there, along with its recorded file. + private bool RekeyServiceIds(OwnershipStoreData data) + { + var changed = false; + foreach (var key in data.Timers.Keys.ToList()) + { + var apiId = Resolve(key); + if (string.Equals(apiId, key, StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + AddOwners(data.Timers, apiId, data.Timers[key]); + data.Timers.Remove(key); + if (data.TimerPaths.TryGetValue(key, out var path)) + { + data.TimerPaths.Remove(key); + if (!data.TimerPaths.ContainsKey(apiId)) + { + data.TimerPaths[apiId] = path; + } + } + + data.TimersMissingSince.Remove(key); + data.TimerServiceIds.Remove(key); + RememberServiceId(data, apiId, key); + changed = true; + } + + return changed; + } + + // Drops what is kept beside a timer or rule whose owners are gone. + private static bool PruneSideTables(OwnershipStoreData data) + { + var changed = false; + foreach (var key in data.TimerPaths.Keys.Where(k => !data.Timers.ContainsKey(k)).ToList()) + { + changed |= data.TimerPaths.Remove(key); + } + + foreach (var key in data.TimerServiceIds.Keys.Where(k => !data.Timers.ContainsKey(k)).ToList()) + { + changed |= data.TimerServiceIds.Remove(key); + } + + foreach (var key in data.TimersMissingSince.Keys.Where(k => !data.Timers.ContainsKey(k)).ToList()) + { + changed |= data.TimersMissingSince.Remove(key); + } + + foreach (var key in data.SeriesTimersMissingSince.Keys.Where(k => !data.SeriesTimers.ContainsKey(k)).ToList()) + { + changed |= data.SeriesTimersMissingSince.Remove(key); + } + + return changed; + } + + // Records the file an owned timer is writing, so the finished item can find its owners. + private bool CaptureActivePath(OwnershipStoreData data, ScheduledTimer timer) + { + if (timer.Status != StatusInProgress || string.IsNullOrEmpty(timer.TimerId)) + { + return false; + } + + var key = ApiIdOf(timer); + if (!data.Timers.ContainsKey(key)) + { + return false; + } + + var path = _host.GetActiveRecordingPath(timer.TimerId); + if (string.IsNullOrEmpty(path) + || (data.TimerPaths.TryGetValue(key, out var known) && string.Equals(known, path, StringComparison.OrdinalIgnoreCase))) + { + return false; + } + + data.TimerPaths[key] = path!; + return true; + } + + // The owned timer, with owners, that recorded the file at this path; null when there is none. + // A finished timer can outlive its recording when the item is deleted before a sync forgets + // the timer, so a timer still recording that path is preferred over it. + private string? FindTimerForPath(OwnershipStoreData data, string? path) + { + if (string.IsNullOrEmpty(path)) + { + return null; + } + + string? finished = null; + foreach (var entry in data.TimerPaths) + { + if (string.Equals(entry.Value, path, StringComparison.OrdinalIgnoreCase) + && data.Timers.ContainsKey(entry.Key)) + { + if (IsLive(entry.Key)) + { + return entry.Key; + } + + finished ??= entry.Key; + } + } + + return finished; + } + + // When an item's file was last written, in UTC; null when that can't be read. The last-write + // time is used, not the creation time: Linux file systems often have no creation time (.NET + // then reports the older of the change and write times), and Windows can hand a file + // re-created at a deleted file's path the old one's creation time. A rerun keeps writing its + // file after the old recording's removal and its timer's end; a file that went away with its + // storage and came back was last written before both. Limits: a restore or post-processing + // that rewrites the file makes it look new (its owners are then dropped, which fails safe), + // and storage whose clock runs behind the server's by more than the gap between a deletion + // and the rerun makes a rerun look old. + private DateTime? FileWrittenAt(Guid itemId) + { + DateTime? writtenAt; + try + { + writtenAt = _host.GetFileWrittenAt(itemId); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not read when the file of recording {ItemId} was written", itemId); + return null; + } + + return writtenAt is { } written && written > UnknownFileTime ? ToUtc(written) : null; + } + + private static DateTime ToUtc(DateTime time) => time.Kind == DateTimeKind.Local ? time.ToUniversalTime() : time; + + // Whether a path match with a finished timer is only a coincidence: the file was written after + // the timer's window (plus post-processing) ended; or, when the listing no longer has the + // timer, after the recording at that path was removed, or else after a sync first found the + // timer done without its recording (plus post-processing). Unknown times never count as stale. + private bool IsStaleMatch(OwnershipStoreData data, string timerId, DateTime? writtenAt, RemovedItem? removed) + { + if (writtenAt is not { } written || IsLive(timerId)) + { + return false; + } + + if (_timers.TryGetValue(timerId, out var timer)) + { + return written > ToUtc(timer.WindowEnd) + PostRecordingAllowance + FileClockTolerance; + } + + if (removed != null) + { + return written > removed.RemovedAt + FileClockTolerance; + } + + return data.TimersMissingSince.TryGetValue(timerId, out var doneSince) + && written > doneSince + PostRecordingAllowance + FileClockTolerance; + } + + // Whether the last listing has the timer and the server isn't done with it. + private bool IsLive(string timerId) => + _timers.TryGetValue(timerId, out var timer) && timer.Status != StatusCancelled && timer.Status != StatusCompleted; + + // Whether a timer other than this one is still recording the same file, so this one's + // recording at that path was replaced. + private bool PathTakenOver(OwnershipStoreData data, string timerId, string path) => + !IsLive(timerId) + && data.TimerPaths.Any(e => !string.Equals(e.Key, timerId, StringComparison.OrdinalIgnoreCase) + && string.Equals(e.Value, path, StringComparison.OrdinalIgnoreCase) + && data.Timers.ContainsKey(e.Key) + && IsLive(e.Key)); + + // Gives each recording already in the library the owners of the owned timer writing it, + // stamping a tag for each owner it gains. The item can exist before its file is captured + // (Jellyfin adds it when the recording starts), and owners can join a recording in progress, + // so this runs whenever files may have been captured or owners added. Saves before stamping + // each item's tags, so a tag write that fails or raises events can't lose the owners. True + // when an item gained an owner. + private async Task AttachToStartedRecordingsAsync(OwnershipStoreData data, CancellationToken ct) + { + var changed = false; + foreach (var entry in data.TimerPaths.ToList()) + { + if (!data.Timers.TryGetValue(entry.Key, out var timerOwners) + || timerOwners.Count == 0 + || PathTakenOver(data, entry.Key, entry.Value)) + { + continue; + } + + var item = _host.FindItemByPath(entry.Value); + if (item == null) + { + continue; + } + + var gained = data.Items.TryGetValue(item.Id, out var itemOwners) + ? timerOwners.Where(o => !itemOwners.Contains(o)).ToList() + : timerOwners.ToList(); + if (gained.Count == 0) + { + _timerItems[entry.Key] = item.Id; + continue; + } + + // A finished timer's path now holding a file written long after it ended is a rerun + // someone else recorded there. + if (!IsLive(entry.Key) + && IsStaleMatch(data, entry.Key, FileWrittenAt(item.Id), data.Removed.TryGetValue(item.Id, out var tombstone) ? tombstone : null)) + { + continue; + } + + _timerItems[entry.Key] = item.Id; + + AddOwners(data.Items, item.Id, gained); + changed = true; + _logger.Info("Recording {ItemId} from timer {TimerId} took {Count} owner(s)", item.Id, entry.Key, gained.Count); + if (data.Removed.Remove(item.Id)) + { + // A new recording on a removed one's file; a later re-add must not bring the old owners back. + _logger.Info("Discarded the owners kept for removed recording {ItemId}, since timer {TimerId} recorded it again", item.Id, entry.Key); + } + + Save(data); + await StampTagsAsync(item.Id, gained, ct).ConfigureAwait(false); + } + + return changed; + } + + // A timer under a rule gets the rule's owners. Owners are never taken away when the server + // moves a timer to another rule, so a newer duplicate rule can't strip anyone's showings. + private bool ApplySeriesOwners(OwnershipStoreData data, IReadOnlyList timers) + { + var changed = false; + foreach (var timer in timers) + { + if (timer.Status != StatusCancelled + && !string.IsNullOrEmpty(timer.SeriesTimerId) + && data.SeriesTimers.TryGetValue(timer.SeriesTimerId!, out var owners) + && AddOwners(data.Timers, ApiIdOf(timer), owners)) + { + Track(data, timer); + changed = true; + } + } + + return changed; + } + + // The rule that already records a program's series: the one with a timer for this very + // program, else the one holding most of the series' timers (the rule the server evaluated + // last), else one with the series' id (Emby only), else one named after the series. + private string? FindRuleForSeries(GuideProgram program, IReadOnlyList timers, IReadOnlyList rules) + { + var ruleIds = rules.Select(r => r.Id).ToHashSet(StringComparer.OrdinalIgnoreCase); + var ruled = timers + .Where(t => t.Status != StatusCancelled && !string.IsNullOrEmpty(t.SeriesTimerId) && ruleIds.Contains(t.SeriesTimerId!)) + .ToList(); + + var direct = ruled.FirstOrDefault(t => string.Equals(t.ProgramId, program.Id, StringComparison.OrdinalIgnoreCase)); + if (direct != null) + { + return direct.SeriesTimerId; + } + + var programs = new Dictionary(StringComparer.OrdinalIgnoreCase); + var sameSeries = ruled.Where(t => + { + if (string.IsNullOrEmpty(t.ProgramId)) + { + return false; + } + + if (!programs.TryGetValue(t.ProgramId!, out var other)) + { + other = _host.GetProgram(t.ProgramId!); + programs[t.ProgramId!] = other; + } + + return other != null + && ((!string.IsNullOrEmpty(program.SeriesId) && string.Equals(other.SeriesId, program.SeriesId, StringComparison.OrdinalIgnoreCase)) + || (!string.IsNullOrEmpty(program.SeriesName) && string.Equals(other.SeriesName, program.SeriesName, StringComparison.OrdinalIgnoreCase))); + }); + var busiest = sameSeries + .GroupBy(t => t.SeriesTimerId!, StringComparer.OrdinalIgnoreCase) + .OrderByDescending(g => g.Count()) + .FirstOrDefault(); + if (busiest != null) + { + return busiest.Key; + } + + if (!string.IsNullOrEmpty(program.SeriesId) + && rules.FirstOrDefault(r => string.Equals(r.SeriesId, program.SeriesId, StringComparison.OrdinalIgnoreCase)) is { } bySeriesId) + { + return bySeriesId.Id; + } + + return string.IsNullOrEmpty(program.SeriesName) + ? null + : rules.FirstOrDefault(r => string.Equals(r.Name, program.SeriesName, StringComparison.OrdinalIgnoreCase))?.Id; + } + + // Owners as clients show them. Deleted and disabled users are left out. + private IReadOnlyList ToOwnerInfos(Dictionary> map, TKey key) + where TKey : notnull + { + if (!map.TryGetValue(key, out var owners)) + { + return Array.Empty(); + } + + var result = new List(owners.Count); + foreach (var owner in owners) + { + if (TryGetUser(owner) is { IsDisabled: false } user) + { + result.Add(new OwnerInfo(user.Id, user.Name, user.PrimaryImageTag)); + } + } + + return result; + } + + // A host that throws can't tell, which is never taken as "not a recording". + private bool? IsRecording(Guid itemId) + { + try + { + return _host.IsLiveTvRecording(itemId); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not check whether item {ItemId} is a Live TV recording", itemId); + return null; + } + } + + // The given items that are Live TV recordings the caller may see, or null when any of them + // can't be told apart, so a client never reads "unknown" as "not a recording". + private IReadOnlyList? RecordingsVisibleTo(IReadOnlyCollection itemIds, Guid callerId) + { + var recordings = new List(); + foreach (var itemId in itemIds.Distinct()) + { + switch (IsRecording(itemId)) + { + case null: + return null; + case true: + recordings.Add(itemId); + break; + } + } + + if (recordings.Count == 0) + { + return recordings; + } + + try + { + var visible = _host.VisibleTo(recordings, callerId); + return recordings.Where(visible.Contains).ToList(); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not check which recordings user {UserId} may see", callerId); + return null; + } + } + + // A user, or null when there is none or the server failed to read it. + private ServerUser? TryGetUser(Guid userId) + { + try + { + return _host.GetUser(userId); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not read user {UserId}", userId); + return null; + } + } + + // Only a user the server definitely doesn't have; a lookup that fails or can't tell keeps them. + private bool UserIsGone(Guid userId) + { + try + { + return _host.UserExists(userId) == false; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not check whether user {UserId} still exists; keeping them as an owner", userId); + return false; + } + } + + // Whether another owner in the set goes by the same name, so a shared tag must stay. + private bool SharesName(List owners, Guid userId, string name) => + owners.Any(o => o != userId && _userNames.TryGetValue(o, out var other) && string.Equals(other, name, StringComparison.OrdinalIgnoreCase)); + + private async Task StampTagsAsync(Guid itemId, IEnumerable owners, CancellationToken ct) + { + foreach (var owner in owners) + { + var name = TryGetUser(owner)?.Name ?? (_userNames.TryGetValue(owner, out var known) ? known : null); + if (!string.IsNullOrEmpty(name)) + { + await SetTagAsync(itemId, TagPrefix + name, true, ct).ConfigureAwait(false); + } + } + } + + // Tags are a readable backup, not the source of truth, so failing to write one is logged only. + private async Task SetTagAsync(Guid itemId, string tag, bool present, CancellationToken ct) + { + // While a newer store is in use, owners live only in memory; tags would outlive them. + if (_readOnly) + { + return false; + } + + try + { + return await _host.SetTagAsync(itemId, tag, present, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) + { + _logger.Warn(ex, "Could not {Action} tag {Tag} on recording {ItemId}", present ? "add" : "remove", tag, itemId); + return false; + } + } + + private OwnershipStoreData Load() + { + if (_data != null) + { + return _data; + } + + // A user list that can't be read only costs the names a rename or delete would look up; + // it must not keep the store from loading, or every owner call would fail. + try + { + foreach (var user in _host.GetUsers()) + { + _userNames[user.Id] = user.Name; + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Warn(ex, "Could not list the server's users while loading recording owners"); + } + + // A newer file is accepted even when this version can't parse it, so the state file never + // falls back to promoting the .bak over it and nothing here rebuilds over it. + var unreadable = false; + var read = _stateFile.Read(_storePath, json => ParseStore(json, () => unreadable = true)); + if (read != null) + { + _data = Normalize(read); + if (read.Version > CurrentVersion) + { + _readOnly = true; + _logger.Warn( + null, + unreadable + ? "The recording owners file {Path} is version {Version}, which this plugin (version {Current}) can't read; recording owners are unavailable until the plugin is upgraded, and the file is left untouched" + : "The recording owners file {Path} is version {Version}, newer than this plugin's {Current}; it is used but not saved over, and no owner tags are written, so changes to recording owners last until restart", + _storePath, + read.Version, + CurrentVersion); + } + + return _data; + } + + _data = new OwnershipStoreData(); + + // Should the read have failed for another reason, a newer file is still never rebuilt over. + var newest = Math.Max(PeekFileVersion(_storePath) ?? 0, PeekFileVersion(_storePath + BackupSuffix) ?? 0); + if (newest > CurrentVersion) + { + _data.Version = newest; + _readOnly = true; + _logger.Warn(null, "The recording owners file {Path} could not be read but is version {Version}, newer than this plugin's {Current}; recording owners are unavailable until the plugin is upgraded, and the file is left untouched", _storePath, newest, CurrentVersion); + return _data; + } + + // Read returns null both when there is no file yet and when the file and its backup are + // both unusable. Only the second loses data, so only then are the recordings' owners + // rebuilt from their tags. + if (File.Exists(_storePath) || File.Exists(_storePath + BackupSuffix)) + { + // The unusable copies are set aside before anything overwrites them, so a read that + // failed only for the moment can't lose the owners for good. + _preserveUnusable = true; + Rebuild(_data); + Save(_data); + } + + return _data; + } + + // Parses the store. A file newer than this build that it can't parse becomes an empty + // placeholder carrying the file's version, so it reads as newer rather than as corrupt. + private static OwnershipStoreData? ParseStore(string json, Action markUnreadable) + { + if (PeekVersion(json) is { } version && version > CurrentVersion) + { + try + { + if (JsonSerializer.Deserialize(json, JsonOptions) is { } parsed) + { + return parsed; + } + } + catch (Exception ex) when (ex is JsonException or NotSupportedException or InvalidOperationException) + { + // Its shape changed; the placeholder below keeps it untouched. + } + + markUnreadable(); + return new OwnershipStoreData { Version = version }; + } + + return JsonSerializer.Deserialize(json, JsonOptions); + } + + // The store's top-level Version, or null when the text isn't a JSON object with one. + private static int? PeekVersion(string json) + { + try + { + using var document = JsonDocument.Parse(json); + return document.RootElement.ValueKind == JsonValueKind.Object + && document.RootElement.TryGetProperty(nameof(OwnershipStoreData.Version), out var element) + && element.ValueKind == JsonValueKind.Number + && element.TryGetInt32(out var version) + ? version + : null; + } + catch (JsonException) + { + return null; + } + } + + private static int? PeekFileVersion(string path) + { + try + { + return File.Exists(path) ? PeekVersion(File.ReadAllText(path)) : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + // Copies the store file and its backup to ".corrupt-". True once done, or when + // there was nothing to copy. + private bool PreserveUnusableFiles() + { + var stamp = _utcNow().ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture); + try + { + foreach (var path in new[] { _storePath, _storePath + BackupSuffix }) + { + if (File.Exists(path)) + { + var aside = path + ".corrupt-" + stamp; + File.Copy(path, aside, overwrite: true); + _logger.Warn(null, "Kept the unusable recording owners file {Path} as {Copy}", path, aside); + } + } + + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.Error(ex, "Could not keep a copy of the unusable recording owners file {Path}; not overwriting it until a copy succeeds", _storePath); + return false; + } + } + + // Deserializing replaces the dictionaries with ones that compare ids case-sensitively and + // leaves explicit nulls, so both are put right here. + private static OwnershipStoreData Normalize(OwnershipStoreData read) => new() + { + Version = Math.Max(read.Version, CurrentVersion), + Timers = Copy(read.Timers, StringComparer.OrdinalIgnoreCase), + SeriesTimers = Copy(read.SeriesTimers, StringComparer.OrdinalIgnoreCase), + Items = Copy(read.Items, EqualityComparer.Default), + TimerPaths = CopyStrings(read.TimerPaths), + Removed = (read.Removed ?? new Dictionary()) + .Where(e => e.Value?.Owners is { Count: > 0 }) + .ToDictionary(e => e.Key, e => e.Value), + TimerServiceIds = CopyStrings(read.TimerServiceIds), + TimersMissingSince = new Dictionary(read.TimersMissingSince ?? new Dictionary(), StringComparer.OrdinalIgnoreCase), + SeriesTimersMissingSince = new Dictionary(read.SeriesTimersMissingSince ?? new Dictionary(), StringComparer.OrdinalIgnoreCase), + Extra = read.Extra, + }; + + private static Dictionary CopyStrings(Dictionary? source) => + new( + (source ?? new Dictionary()).Where(e => !string.IsNullOrEmpty(e.Value)).ToDictionary(e => e.Key, e => e.Value), + StringComparer.OrdinalIgnoreCase); + + private static Dictionary> Copy(Dictionary>? source, IEqualityComparer comparer) + where TKey : notnull + { + var copy = new Dictionary>(comparer); + if (source != null) + { + foreach (var entry in source) + { + if (entry.Value is { Count: > 0 }) + { + AddOwners(copy, entry.Key, entry.Value); + } + } + } + + return copy; + } + + // Rebuilds the recordings' owners from their "Recorded by name" tags. Timer and rule owners + // have no backup and are lost. + private void Rebuild(OwnershipStoreData data) + { + var users = _host.GetUsers(); + var unmatched = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var item in _host.FindItemsWithTagPrefix(TagPrefix)) + { + foreach (var tag in item.Tags.Where(t => t.StartsWith(TagPrefix, StringComparison.OrdinalIgnoreCase))) + { + var name = tag.Substring(TagPrefix.Length).Trim(); + var matches = users.Where(u => string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase)).ToList(); + var user = matches.Count == 1 ? matches[0] : matches.FirstOrDefault(u => string.Equals(u.Name, name, StringComparison.Ordinal)); + if (user == null) + { + unmatched.Add(name); + continue; + } + + AddOwners(data.Items, item.Id, new[] { user.Id }); + } + } + + foreach (var name in unmatched) + { + _logger.Warn(null, "Rebuilding recording owners: no single user is named {Name}, so recordings tagged for them stay without that owner", name); + } + + _logger.Warn(null, "The recording owners file {Path} and its backup were unusable; rebuilt the owners of {Count} recording(s) from their tags. Timer and series rule owners are lost", _storePath, data.Items.Count); + } + + private void Save(OwnershipStoreData data) + { + if (_readOnly) + { + return; + } + + if (_preserveUnusable) + { + if (!PreserveUnusableFiles()) + { + return; + } + + _preserveUnusable = false; + } + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(_storePath)!); + _stateFile.Write(_storePath, JsonSerializer.Serialize(data, JsonOptions)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.Error(ex, "Could not save recording owners to {Path}; changes since the last save are lost on restart", _storePath); + } + } +} diff --git a/shared/LiveTv/RecordingOwnershipWatcher.cs b/shared/LiveTv/RecordingOwnershipWatcher.cs new file mode 100644 index 00000000..e540eb61 --- /dev/null +++ b/shared/LiveTv/RecordingOwnershipWatcher.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Concurrent; +using System.Threading; +using System.Threading.Tasks; + +namespace Moonfin.LiveTv; + +/// +/// Keeps in step with the server: a sync once a minute while +/// a recording is in progress or a timer is about to start or has just started, otherwise every ten +/// minutes or when a schedule event wakes it, plus once more shortly after a timer is created. Every +/// handler returns at once, because the service raises some of these events itself while holding its +/// lock; the cancel handler only asks the host for the timer's file first, since the recording stops +/// right after the event. Each server starts +/// once and stops it on shutdown. +/// +public sealed class RecordingOwnershipWatcher : IDisposable +{ + private static readonly TimeSpan ActiveInterval = TimeSpan.FromSeconds(60); + private static readonly TimeSpan IdleInterval = TimeSpan.FromMinutes(10); + private static readonly TimeSpan NearWindow = TimeSpan.FromMinutes(10); + + // A timer made for a program already airing starts recording seconds later; one extra sync + // then captures its file while the recording is still young. + private static readonly TimeSpan CreatedFollowUp = TimeSpan.FromSeconds(10); + + private readonly ILiveTvRecordingHost _host; + private readonly RecordingOwnershipService _service; + private readonly IRecordingLog _logger; + private readonly TimeSpan _createdFollowUp; + private readonly Func _delay; + private readonly SemaphoreSlim _wake = new(0, 1); + + // Every listed timer id, API or service kind, to its service id, from the host's last listing + // while something was recording. Read on the raising thread of a cancel, so it is never behind + // the service's lock. Each listing builds a new map and swaps it in whole, so a cancel never + // sees it half filled. + private volatile IReadOnlyDictionary _serviceIds = EmptyServiceIds; + private int _serviceIdListings; + private CancellationToken _stopping; + + public RecordingOwnershipWatcher(ILiveTvRecordingHost host, RecordingOwnershipService service, IRecordingLog log) + : this(host, service, log, CreatedFollowUp) + { + } + + // Tests shorten the follow-up sync after TimerCreated. + internal RecordingOwnershipWatcher(ILiveTvRecordingHost host, RecordingOwnershipService service, IRecordingLog log, TimeSpan createdFollowUp) + : this(host, service, log, createdFollowUp, Task.Delay) + { + } + + // Tests complete the follow-up wait themselves, so no wall-clock time is involved. + internal RecordingOwnershipWatcher(ILiveTvRecordingHost host, RecordingOwnershipService service, IRecordingLog log, Func followUpDelay) + : this(host, service, log, CreatedFollowUp, followUpDelay) + { + } + + private RecordingOwnershipWatcher(ILiveTvRecordingHost host, RecordingOwnershipService service, IRecordingLog log, TimeSpan createdFollowUp, Func delay) + { + _host = host; + _service = service; + _logger = log; + _createdFollowUp = createdFollowUp; + _delay = delay; + } + + private static IReadOnlyDictionary EmptyServiceIds { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public void Dispose() => _wake.Dispose(); + + // Tests wait on this instead of sleeping until the id map is filled. + internal bool KnowsServiceId(string id) => _serviceIds.ContainsKey(id); + + // How many id listings have finished and been swapped in, for tests. + internal int ServiceIdListings => Volatile.Read(ref _serviceIdListings); + + public async Task RunAsync(CancellationToken stoppingToken) + { + _stopping = stoppingToken; + _host.ScheduleChanged += OnScheduleChanged; + _host.TimerCreated += OnTimerCreated; + _host.TimerCancelled += OnTimerCancelled; + _host.GuideRefreshed += OnGuideRefreshed; + _host.ItemAdded += OnItemAdded; + _host.ItemRemoved += OnItemRemoved; + _host.UserUpdated += OnUserUpdated; + _host.UserDeleted += OnUserDeleted; + + try + { + while (!stoppingToken.IsCancellationRequested) + { + // Anything that escapes here would end the loop, and with it every sync until a restart. + try + { + await _service.SyncAsync(stoppingToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException || !stoppingToken.IsCancellationRequested) + { + _logger.Error(ex, "Recording owners sync failed"); + } + + await RefreshServiceIdsAsync(stoppingToken).ConfigureAwait(false); + + await _wake.WaitAsync(NextDelay(), stoppingToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + // Server shutting down. + } + finally + { + _host.ScheduleChanged -= OnScheduleChanged; + _host.TimerCreated -= OnTimerCreated; + _host.TimerCancelled -= OnTimerCancelled; + _host.GuideRefreshed -= OnGuideRefreshed; + _host.ItemAdded -= OnItemAdded; + _host.ItemRemoved -= OnItemRemoved; + _host.UserUpdated -= OnUserUpdated; + _host.UserDeleted -= OnUserDeleted; + } + } + + private TimeSpan NextDelay() + { + if (_service.HasRecordingInProgress) + { + return ActiveInterval; + } + + // A recording's file is only captured while a sync sees its timer in progress, so sync + // often from shortly before a timer starts until shortly after. + var next = _service.NextTimerStart; + if (next.HasValue && next.Value - DateTime.UtcNow <= NearWindow) + { + return ActiveInterval; + } + + return IdleInterval; + } + + // Only a recording in progress has a file a cancel needs to find, so the ids are listed only then. + private async Task RefreshServiceIdsAsync(CancellationToken ct) + { + if (!_service.HasRecordingInProgress) + { + _serviceIds = EmptyServiceIds; + return; + } + + try + { + var timers = await _host.GetTimersAsync(ct).ConfigureAwait(false); + var serviceIds = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var timer in timers) + { + if (string.IsNullOrEmpty(timer.TimerId)) + { + continue; + } + + serviceIds[timer.TimerId] = timer.TimerId; + if (!string.IsNullOrEmpty(timer.ApiId)) + { + serviceIds[timer.ApiId!] = timer.TimerId; + } + } + + _serviceIds = serviceIds; + Interlocked.Increment(ref _serviceIdListings); + } + catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) + { + _logger.Warn(ex, "Could not list the timers for the recording owners"); + } + } + + // The file a cancelled timer is writing. The server raises the cancel before it stops the + // recording, so this runs on the raising thread, through the host only: the service's lock may + // be held by whoever cancelled. + private string? ActivePathOf(string timerId) + { + if (string.IsNullOrEmpty(timerId)) + { + return null; + } + + try + { + var path = _host.GetActiveRecordingPath(timerId); + if (string.IsNullOrEmpty(path) + && _serviceIds.TryGetValue(timerId, out var serviceId) + && !string.Equals(serviceId, timerId, StringComparison.OrdinalIgnoreCase)) + { + path = _host.GetActiveRecordingPath(serviceId); + } + + return string.IsNullOrEmpty(path) ? null : path; + } + catch (Exception ex) + { + _logger.Warn(ex, "Could not look up the recording of cancelled timer {TimerId}", timerId); + return null; + } + } + + private void WakeLater(TimeSpan delay) + { + _ = _delay(delay, _stopping).ContinueWith( + _ => Wake(), + CancellationToken.None, + TaskContinuationOptions.OnlyOnRanToCompletion, + TaskScheduler.Default); + } + + private void Wake() + { + try + { + _wake.Release(); + } + catch (SemaphoreFullException) + { + // Already due to wake. + } + catch (ObjectDisposedException) + { + // Shut down. + } + } + + private void OnScheduleChanged(object? sender, EventArgs e) => Wake(); + + private void OnTimerCreated(object? sender, ScheduledTimer timer) + { + Wake(); + WakeLater(_createdFollowUp); + } + + private void OnGuideRefreshed(object? sender, EventArgs e) => Wake(); + + private void OnTimerCancelled(object? sender, string timerId) + { + var path = ActivePathOf(timerId); + Handle(() => _service.OnTimerCancelledAsync(timerId, path, _stopping)); + } + + private void OnItemAdded(object? sender, LibraryItem item) => Handle(() => _service.OnItemAddedAsync(item, _stopping)); + + private void OnItemRemoved(object? sender, Guid itemId) => Handle(() => _service.OnItemRemovedAsync(itemId, _stopping)); + + private void OnUserUpdated(object? sender, ServerUser user) => Handle(() => _service.OnUserUpdatedAsync(user, _stopping)); + + private void OnUserDeleted(object? sender, Guid userId) => Handle(() => _service.OnUserDeletedAsync(userId, _stopping)); + + // The service raises some of these events while holding its lock, so none is handled on the + // raising thread. + private void Handle(Func work) + { + _ = Task.Run(async () => + { + try + { + await work().ConfigureAwait(false); + } + catch (OperationCanceledException) when (_stopping.IsCancellationRequested) + { + // Server shutting down. + } + catch (Exception ex) + { + _logger.Warn(ex, "Recording owners event failed"); + } + }); + } +} From 6a507733454479672a807964db8b42136c2a3fb7 Mon Sep 17 00:00:00 2001 From: WizardOfYendor1 Date: Sun, 15 Nov 2026 18:08:53 -0500 Subject: [PATCH 02/13] added recording owner endpoints, an admin switch and a ping flag Moonfin/LiveTv/Owners/{Record,RecordSeries,Claim,Lookup,Mine} on Jellyfin and Emby let clients schedule with an owner, join a recording someone else scheduled, and read owners (only for items and users the caller can see). Lookup also lists which asked items are live tv recordings. Complete-showing requests carry their owners onto the recording. The LiveTvRecordingOwners switch (on by default) and Ping's recordingOwnersSupported flag let clients fall back to plain Live TV calls when the feature is off, and both servers answer "feature off" and refusals with the same JSON error bodies. --- .../Api/LiveTvRecordingsRequests.cs | 59 +++ .../Api/LiveTvRecordingsService.cs | 155 ++++++++ .../Api/SettingsService.cs | 8 + .../Pages/configPage.html | 9 + Emby/Emby.Plugins.Moonfin/Pages/moonfin.js | 2 + .../PluginConfiguration.cs | 3 + Emby/Emby.Plugins.Moonfin/ServerEntryPoint.cs | 29 +- .../backend/Api/LiveTvRecordingsController.cs | 5 + Jellyfin/backend/Api/MoonfinController.cs | 4 + .../backend/Api/RecordingOwnersController.cs | 365 ++++++++++++++++++ Jellyfin/backend/Pages/configPage.html | 11 + Jellyfin/backend/PluginConfiguration.cs | 3 + Jellyfin/backend/PluginServiceRegistrator.cs | 21 +- .../Services/IncompleteRecordingHosting.cs | 28 ++ 14 files changed, 699 insertions(+), 3 deletions(-) create mode 100644 Jellyfin/backend/Api/RecordingOwnersController.cs diff --git a/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsRequests.cs b/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsRequests.cs index c21561ad..cd746867 100644 --- a/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsRequests.cs +++ b/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsRequests.cs @@ -63,4 +63,63 @@ public class SuggestedShowingBody public SuggestedShowing? Showing { get; set; } } + + [Route("/Moonfin/LiveTv/Owners/Record", "POST")] + [Authenticated] + public class RecordOwnerRequest : IReturn, IRequiresRequestStream + { + public System.IO.Stream RequestStream { get; set; } = null!; + } + + [Route("/Moonfin/LiveTv/Owners/RecordSeries", "POST")] + [Authenticated] + public class RecordSeriesOwnerRequest : IReturn, IRequiresRequestStream + { + public System.IO.Stream RequestStream { get; set; } = null!; + } + + [Route("/Moonfin/LiveTv/Owners/Claim", "POST")] + [Authenticated] + public class ClaimOwnerRequest : IReturn, IRequiresRequestStream + { + public System.IO.Stream RequestStream { get; set; } = null!; + } + + [Route("/Moonfin/LiveTv/Owners/Lookup", "POST")] + [Authenticated] + public class LookupOwnersRequest : IReturn, IRequiresRequestStream + { + public System.IO.Stream RequestStream { get; set; } = null!; + } + + [Route("/Moonfin/LiveTv/Owners/Mine", "GET")] + [Authenticated] + public class GetMyOwnedRequest : IReturn { } + + /// Body for recording a program, or its series, as its owner. + public class RecordOwnerBody + { + public string? ProgramId { get; set; } + + public System.Collections.Generic.Dictionary? Settings { get; set; } + } + + /// Body for claiming an existing timer, series rule or recording. + public class ClaimOwnerBody + { + /// timer, series or item. + public string? Kind { get; set; } + + public string? Id { get; set; } + } + + /// Body for looking owners up. + public class LookupOwnersBody + { + public System.Collections.Generic.List? TimerIds { get; set; } + + public System.Collections.Generic.List? SeriesTimerIds { get; set; } + + public System.Collections.Generic.List? ItemIds { get; set; } + } } diff --git a/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsService.cs b/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsService.cs index da2218ce..47e34d3a 100644 --- a/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsService.cs +++ b/Emby/Emby.Plugins.Moonfin/Api/LiveTvRecordingsService.cs @@ -117,6 +117,7 @@ public async Task Post(RequestCompleteShowingRequest request) state = IncompleteRecordingRules.DisplayState(showing), scheduledStart = showing.ScheduledStart, channelName = showing.ScheduledChannelName, + otherOwners = OwnerList(service.OtherOwners(showing, user.Id, OwnersEnabled())), }); } @@ -181,6 +182,160 @@ public async Task Post(SaveIncompleteRecordingSettingsRequest request) return Json(IncompleteRecordingConfig.Read()); } + // ---- Recording owners (My Recordings) ---- + + private static bool OwnersEnabled() => Plugin.Instance?.Configuration?.LiveTvRecordingOwners ?? true; + + private object OwnersNotFound() => Json(404, new { error = "Recording owners are not available" }); + + private static object[] OwnerList(System.Collections.Generic.IEnumerable owners) => + owners.Select(o => (object)new { userId = o.UserId.ToString("N"), name = o.Name, imageTag = o.ImageTag }).ToArray(); + + private static bool ProgramVisible(string programId, Guid userId) + { + var host = PluginServices.RecordingHost; + var program = host?.GetProgram(programId); + return program != null && host!.IsVisibleTo(program.ItemId, userId); + } + + private object OwnershipResult(OwnershipOutcome outcome) => + Json(new { id = outcome.Id, owners = OwnerList(outcome.Owners), joined = outcome.Joined }); + + /// Records a program as the caller, or joins the timer that already records it. + public async Task Post(RecordOwnerRequest request) + { + var service = PluginServices.RecordingOwners; + if (service == null) return NotReady(); + var user = AuthHelpers.GetCurrentUser(Request, _authContext); + if (user == null) return NoUser(); + if (user.Policy?.EnableLiveTvManagement != true) return NotAllowed(); + if (!OwnersEnabled()) return OwnersNotFound(); + + var body = await MoonfinJson.ReadBodyAsync(request.RequestStream).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(body?.ProgramId)) return Json(400, new { error = "programId is required." }); + if (!ProgramVisible(body!.ProgramId!, user.Id)) return Json(404, new { error = "No guide program with that id" }); + + var attempt = await service.TryRecordProgramAsync(body.ProgramId!, user.Id, CancellationToken.None).ConfigureAwait(false); + return attempt.Outcome == null + ? Json(409, new { error = attempt.ErrorOr("The server could not schedule the recording.") }) + : OwnershipResult(attempt.Outcome); + } + + /// Records a program's series as the caller, or joins the rule that already records it. + public async Task Post(RecordSeriesOwnerRequest request) + { + var service = PluginServices.RecordingOwners; + if (service == null) return NotReady(); + var user = AuthHelpers.GetCurrentUser(Request, _authContext); + if (user == null) return NoUser(); + if (user.Policy?.EnableLiveTvManagement != true) return NotAllowed(); + if (!OwnersEnabled()) return OwnersNotFound(); + + var body = await MoonfinJson.ReadBodyAsync(request.RequestStream).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(body?.ProgramId)) return Json(400, new { error = "programId is required." }); + if (!ProgramVisible(body!.ProgramId!, user.Id)) return Json(404, new { error = "No guide program with that id" }); + + var attempt = await service.TryRecordSeriesAsync(body.ProgramId!, user.Id, body.Settings, CancellationToken.None).ConfigureAwait(false); + return attempt.Outcome == null + ? Json(409, new { error = attempt.ErrorOr("The server could not create the series recording.") }) + : OwnershipResult(attempt.Outcome); + } + + /// Adds the caller to the owners of an existing timer, series rule or recording. + public async Task Post(ClaimOwnerRequest request) + { + var service = PluginServices.RecordingOwners; + if (service == null) return NotReady(); + var user = AuthHelpers.GetCurrentUser(Request, _authContext); + if (user == null) return NoUser(); + if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed(); + if (!OwnersEnabled()) return OwnersNotFound(); + + var body = await MoonfinJson.ReadBodyAsync(request.RequestStream).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(body?.Id)) return Json(400, new { error = "id is required." }); + + OwnedKind kind; + switch (body!.Kind?.ToLowerInvariant()) + { + case "timer": kind = OwnedKind.Timer; break; + case "series": kind = OwnedKind.Series; break; + case "item": kind = OwnedKind.Item; break; + default: return Json(400, new { error = "kind must be timer, series or item." }); + } + + var id = body.Id!; + if (kind == OwnedKind.Item) + { + var itemId = ResolveItem(id); + if (itemId == null || PluginServices.RecordingHost?.IsVisibleTo(itemId.Value, user.Id) != true) + { + return Json(404, new { error = "No recording with that id" }); + } + + id = itemId.Value.ToString("N"); + } + + var owners = await service.ClaimAsync(kind, id, user.Id, CancellationToken.None).ConfigureAwait(false); + return owners == null + ? Json(404, new { error = "Nothing to claim with that id" }) + : Json(new { owners = OwnerList(owners) }); + } + + /// The owners of the given timers, series rules and recordings, in one call. + public async Task Post(LookupOwnersRequest request) + { + var service = PluginServices.RecordingOwners; + if (service == null) return NotReady(); + var user = AuthHelpers.GetCurrentUser(Request, _authContext); + if (user == null) return NoUser(); + if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed(); + if (!OwnersEnabled()) return OwnersNotFound(); + + var body = await MoonfinJson.ReadBodyAsync(request.RequestStream).ConfigureAwait(false); + var itemIds = (body?.ItemIds ?? new System.Collections.Generic.List()) + .Select(s => ResolveItem(s?.Trim())) + .Where(id => id != null) + .Select(id => id!.Value) + .Distinct() + .ToList(); + + var lookup = await service.LookupAsync( + body?.TimerIds ?? new System.Collections.Generic.List(), + body?.SeriesTimerIds ?? new System.Collections.Generic.List(), + itemIds, + user.Id, + CancellationToken.None).ConfigureAwait(false); + + var timers = lookup.Timers.ToDictionary(p => p.Key, p => OwnerList(p.Value)); + var seriesTimers = lookup.SeriesTimers.ToDictionary(p => p.Key, p => OwnerList(p.Value)); + var items = lookup.Items.ToDictionary(p => ClientId(p.Key.ToString("N")), p => OwnerList(p.Value)); + + // recordingItemIds is left out, not sent as null, when the server can't tell: clients + // read a missing field as "unknown". + return lookup.RecordingItemIds == null + ? Json(new { timers, seriesTimers, items }) + : Json(new { timers, seriesTimers, items, recordingItemIds = lookup.RecordingItemIds.Select(i => ClientId(i.ToString("N"))).ToArray() }); + } + + /// Everything the caller owns. Timer ids may be stale; clients intersect them with the live timer list. + public async Task Get(GetMyOwnedRequest request) + { + var service = PluginServices.RecordingOwners; + if (service == null) return NotReady(); + var user = AuthHelpers.GetCurrentUser(Request, _authContext); + if (user == null) return NoUser(); + if (user.Policy?.EnableLiveTvAccess != true) return NotAllowed(); + if (!OwnersEnabled()) return OwnersNotFound(); + + var mine = await service.GetMineAsync(user.Id, CancellationToken.None).ConfigureAwait(false); + return Json(new + { + timerIds = mine.TimerIds, + seriesTimerIds = mine.SeriesTimerIds, + itemIds = mine.ItemIds.Select(i => ClientId(i.ToString("N"))).ToArray(), + }); + } + // Emby clients send numeric item ids, and the feature keys items by their Guid. private static Guid? ResolveItem(string? id) { diff --git a/Emby/Emby.Plugins.Moonfin/Api/SettingsService.cs b/Emby/Emby.Plugins.Moonfin/Api/SettingsService.cs index 6025c15b..67b91d96 100644 --- a/Emby/Emby.Plugins.Moonfin/Api/SettingsService.cs +++ b/Emby/Emby.Plugins.Moonfin/Api/SettingsService.cs @@ -63,6 +63,13 @@ private bool TryAuthorizedSync([NotNullWhen(true)] out Guid? userId, [NotNullWhe return true; } + /// + /// Ping's recordingOwnersSupported: the setting, but only once the owners service runs, so a + /// client that pings during startup isn't sent to endpoints that would answer 503. + /// + internal static bool RecordingOwnersSupported(PluginConfiguration? config, bool serviceReady) => + serviceReady && (config?.LiveTvRecordingOwners ?? true); + public object Get(GetPingRequest request) { var config = Plugin.Instance?.Configuration; @@ -101,6 +108,7 @@ public object Get(GetPingRequest request) smartSearchEnabled = config?.SmartSearchEnabled ?? false, recommendationsSupported = config?.RecommendationsProviderEnabled ?? true, incompleteRecordingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, + recordingOwnersSupported = RecordingOwnersSupported(config, PluginServices.RecordingOwners != null), extendedCompleteShowingsSupported = config?.LiveTvDetectIncompleteRecordings ?? true, clientLogSupported = config?.EnableClientLogUpload ?? false, calendarAvailable = seerrEnabled diff --git a/Emby/Emby.Plugins.Moonfin/Pages/configPage.html b/Emby/Emby.Plugins.Moonfin/Pages/configPage.html index c65a31a4..f5642d10 100644 --- a/Emby/Emby.Plugins.Moonfin/Pages/configPage.html +++ b/Emby/Emby.Plugins.Moonfin/Pages/configPage.html @@ -5280,6 +5280,15 @@

Uploaded Themes

Live TV Recordings

+
+ +
+ Remembers which users scheduled each recording, so Moonfin can show a My Recordings list and who else records a show. +
+