using System;
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Plugins;
using Microsoft.Extensions.Logging;
namespace ConfusedPolarBear.Plugin.IntroSkipper;
///
/// Server entrypoint.
///
public class Entrypoint : IServerEntryPoint
{
private readonly IUserManager _userManager;
private readonly IUserViewManager _userViewManager;
private readonly ILibraryManager _libraryManager;
private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
///
/// Initializes a new instance of the class.
///
/// User manager.
/// User view manager.
/// Library manager.
/// Logger.
/// Logger factory.
public Entrypoint(
IUserManager userManager,
IUserViewManager userViewManager,
ILibraryManager libraryManager,
ILogger logger,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_userViewManager = userViewManager;
_libraryManager = libraryManager;
_logger = logger;
_loggerFactory = loggerFactory;
}
///
/// Registers event handler.
///
/// Task.
public Task RunAsync()
{
Chromaprint.Logger = _logger;
#if DEBUG
LogVersion();
#endif
// TODO: when a new item is added to the server, immediately analyze the season it belongs to
// instead of waiting for the next task interval. The task start should be debounced by a few seconds.
try
{
// Enqueue all episodes at startup so the fingerprint visualizer works before the task is started.
_logger.LogInformation("Running startup enqueue");
var queueManager = new QueueManager(_loggerFactory.CreateLogger(), _libraryManager);
queueManager.EnqueueAllEpisodes();
}
catch (Exception ex)
{
_logger.LogError("Unable to run startup enqueue: {Exception}", ex);
}
_logger.LogDebug(
"Total enqueued seasons: {Count} ({Episodes} episodes)",
Plugin.Instance!.AnalysisQueue.Count,
Plugin.Instance!.TotalQueued);
return Task.CompletedTask;
}
#if DEBUG
///
/// Logs the exact commit that created this version of the plugin. Only used in unstable builds.
///
private void LogVersion()
{
var assembly = GetType().Assembly;
var path = GetType().Namespace + ".Configuration.version.txt";
using (var stream = assembly.GetManifestResourceStream(path))
{
if (stream is null)
{
_logger.LogWarning("Unable to read embedded version information");
return;
}
var version = string.Empty;
using (var reader = new StreamReader(stream))
{
version = reader.ReadToEnd().TrimEnd();
}
if (version == "unknown")
{
_logger.LogTrace("Embedded version information was not valid, ignoring");
return;
}
_logger.LogInformation("Unstable version built from commit {Version}", version);
}
}
#endif
///
/// Dispose.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
///
/// Protected dispose.
///
/// Dispose.
protected virtual void Dispose(bool dispose)
{
if (!dispose)
{
return;
}
}
}