using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Data.Events;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.Tasks;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.WebSocketListeners
{
///
/// Class ScheduledTasksWebSocketListener.
///
public class ScheduledTasksWebSocketListener : BasePeriodicWebSocketListener, WebSocketListenerState>
{
///
/// Gets or sets the task manager.
///
/// The task manager.
private readonly ITaskManager _taskManager;
///
/// Initializes a new instance of the class.
///
/// Instance of the interface.
/// Instance of the interface.
public ScheduledTasksWebSocketListener(ILogger logger, ITaskManager taskManager)
: base(logger)
{
_taskManager = taskManager;
_taskManager.TaskExecuting += OnTaskExecuting;
_taskManager.TaskCompleted += OnTaskCompleted;
}
///
protected override SessionMessageType Type => SessionMessageType.ScheduledTasksInfo;
///
protected override SessionMessageType StartType => SessionMessageType.ScheduledTasksInfoStart;
///
protected override SessionMessageType StopType => SessionMessageType.ScheduledTasksInfoStop;
///
/// Gets the data to send.
///
/// Task{IEnumerable{TaskInfo}}.
protected override Task> GetDataToSend()
{
return Task.FromResult(_taskManager.ScheduledTasks
.OrderBy(i => i.Name)
.Select(ScheduledTaskHelpers.GetTaskInfo)
.Where(i => !i.IsHidden));
}
///
protected override void Dispose(bool dispose)
{
_taskManager.TaskExecuting -= OnTaskExecuting;
_taskManager.TaskCompleted -= OnTaskCompleted;
base.Dispose(dispose);
}
private async void OnTaskCompleted(object? sender, TaskCompletionEventArgs e)
{
e.Task.TaskProgress -= OnTaskProgress;
await SendData(true).ConfigureAwait(false);
}
private async void OnTaskExecuting(object? sender, GenericEventArgs e)
{
await SendData(true).ConfigureAwait(false);
e.Argument.TaskProgress += OnTaskProgress;
}
private async void OnTaskProgress(object? sender, GenericEventArgs e)
{
await SendData(false).ConfigureAwait(false);
}
}
}