using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ConfusedPolarBear.Plugin.IntroSkipper.Data;
using ConfusedPolarBear.Plugin.IntroSkipper.Manager;
using ConfusedPolarBear.Plugin.IntroSkipper.Services;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper.ScheduledTasks;
///
/// Analyze all television episodes for introduction sequences.
///
///
/// Initializes a new instance of the class.
///
/// Logger factory.
/// Library manager.
/// Logger.
/// MediaSegment Update Manager.
public class DetectIntrosCreditsTask(
ILogger logger,
ILoggerFactory loggerFactory,
ILibraryManager libraryManager,
MediaSegmentUpdateManager mediaSegmentUpdateManager) : IScheduledTask
{
private readonly ILogger _logger = logger;
private readonly ILoggerFactory _loggerFactory = loggerFactory;
private readonly ILibraryManager _libraryManager = libraryManager;
private readonly MediaSegmentUpdateManager _mediaSegmentUpdateManager = mediaSegmentUpdateManager;
///
/// Gets the task name.
///
public string Name => "Detect Intros and Credits";
///
/// Gets the task category.
///
public string Category => "Intro Skipper";
///
/// Gets the task description.
///
public string Description => "Analyzes media to determine the timestamp and length of intros and credits.";
///
/// Gets the task key.
///
public string Key => "CPBIntroSkipperDetectIntrosCredits";
///
/// Analyze all episodes in the queue. Only one instance of this task should be run at a time.
///
/// Task progress.
/// Cancellation token.
/// Task.
public async Task ExecuteAsync(IProgress progress, CancellationToken cancellationToken)
{
if (_libraryManager is null)
{
throw new InvalidOperationException("Library manager was null");
}
// abort automatic analyzer if running
if (Entrypoint.AutomaticTaskState == TaskState.Running || Entrypoint.AutomaticTaskState == TaskState.Cancelling)
{
_logger.LogInformation("Automatic Task is {0} and will be canceled.", Entrypoint.AutomaticTaskState);
await Entrypoint.CancelAutomaticTaskAsync(cancellationToken).ConfigureAwait(false);
}
using (await ScheduledTaskSemaphore.AcquireAsync(cancellationToken).ConfigureAwait(false))
{
_logger.LogInformation("Scheduled Task is starting");
var modes = new List { AnalysisMode.Introduction, AnalysisMode.Credits };
var baseIntroAnalyzer = new BaseItemAnalyzerTask(
modes,
_loggerFactory.CreateLogger(),
_loggerFactory,
_libraryManager,
_mediaSegmentUpdateManager);
await baseIntroAnalyzer.AnalyzeItems(progress, cancellationToken).ConfigureAwait(false);
}
}
///
/// Get task triggers.
///
/// Task triggers.
public IEnumerable GetDefaultTriggers()
{
return
[
new TaskTriggerInfo
{
Type = TaskTriggerInfo.TriggerDaily,
TimeOfDayTicks = TimeSpan.FromHours(0).Ticks
}
];
}
}