// Copyright (C) 2024 Intro-Skipper contributors // SPDX-License-Identifier: GPL-3.0-only. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using IntroSkipper.Data; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller; using MediaBrowser.Model; using Microsoft.Extensions.Logging; namespace IntroSkipper.Manager { /// /// Initializes a new instance of the class. /// /// MediaSegmentManager. /// logger. /// segmentProvider. public class MediaSegmentUpdateManager(IMediaSegmentManager mediaSegmentManager, ILogger logger, IMediaSegmentProvider segmentProvider) { private readonly IMediaSegmentManager _mediaSegmentManager = mediaSegmentManager; private readonly ILogger _logger = logger; private readonly IMediaSegmentProvider _segmentProvider = segmentProvider; private readonly string _id = Plugin.Instance!.Name.ToLowerInvariant() .GetMD5() .ToString("N", CultureInfo.InvariantCulture); /// /// Updates all media items in a List. /// /// Queued media items. /// CancellationToken. /// A representing the asynchronous operation. public async Task UpdateMediaSegmentsAsync(IReadOnlyList episodes, CancellationToken cancellationToken) { foreach (var episode in episodes) { cancellationToken.ThrowIfCancellationRequested(); try { var existingSegments = await _mediaSegmentManager.GetSegmentsAsync(episode.EpisodeId, null, false).ConfigureAwait(false); await Task.WhenAll(existingSegments.Select(s => _mediaSegmentManager.DeleteSegmentAsync(s.Id))).ConfigureAwait(false); var newSegments = await _segmentProvider.GetMediaSegments(new MediaSegmentGenerationRequest { ItemId = episode.EpisodeId }, cancellationToken).ConfigureAwait(false); if (newSegments.Count == 0) { _logger.LogDebug("No segments found for episode {EpisodeId}", episode.EpisodeId); continue; } await Task.WhenAll(newSegments.Select(s => _mediaSegmentManager.CreateSegmentAsync(s, _id))).ConfigureAwait(false); _logger.LogDebug("Updated {SegmentCount} segments for episode {EpisodeId}", newSegments.Count, episode.EpisodeId); } catch (Exception ex) { _logger.LogError(ex, "Error processing episode {EpisodeId}", episode.EpisodeId); } } } } }