using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Net.Mime;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Jellyfin.Api.Attributes;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Api.Models.LiveTvDtos;
using Jellyfin.Data.Enums;
using Jellyfin.Database.Implementations.Enums;
using Jellyfin.Extensions;
using MediaBrowser.Common.Api;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Controller.MediaEncoding;
using MediaBrowser.Controller.Streaming;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Jellyfin.Api.Controllers;
/// 
/// Live tv controller.
/// 
public class LiveTvController : BaseJellyfinApiController
{
    private readonly ILiveTvManager _liveTvManager;
    private readonly IGuideManager _guideManager;
    private readonly ITunerHostManager _tunerHostManager;
    private readonly IListingsManager _listingsManager;
    private readonly IRecordingsManager _recordingsManager;
    private readonly IUserManager _userManager;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILibraryManager _libraryManager;
    private readonly IDtoService _dtoService;
    private readonly IMediaSourceManager _mediaSourceManager;
    private readonly IConfigurationManager _configurationManager;
    private readonly ITranscodeManager _transcodeManager;
    /// 
    /// Initializes a new instance of the  class.
    /// 
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    /// Instance of the  interface.
    public LiveTvController(
        ILiveTvManager liveTvManager,
        IGuideManager guideManager,
        ITunerHostManager tunerHostManager,
        IListingsManager listingsManager,
        IRecordingsManager recordingsManager,
        IUserManager userManager,
        IHttpClientFactory httpClientFactory,
        ILibraryManager libraryManager,
        IDtoService dtoService,
        IMediaSourceManager mediaSourceManager,
        IConfigurationManager configurationManager,
        ITranscodeManager transcodeManager)
    {
        _liveTvManager = liveTvManager;
        _guideManager = guideManager;
        _tunerHostManager = tunerHostManager;
        _listingsManager = listingsManager;
        _recordingsManager = recordingsManager;
        _userManager = userManager;
        _httpClientFactory = httpClientFactory;
        _libraryManager = libraryManager;
        _dtoService = dtoService;
        _mediaSourceManager = mediaSourceManager;
        _configurationManager = configurationManager;
        _transcodeManager = transcodeManager;
    }
    /// 
    /// Gets available live tv services.
    /// 
    /// Available live tv services returned.
    /// 
    /// An  containing the available live tv services.
    /// 
    [HttpGet("Info")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public ActionResult GetLiveTvInfo()
    {
        return _liveTvManager.GetLiveTvInfo(CancellationToken.None);
    }
    /// 
    /// Gets available live tv channels.
    /// 
    /// Optional. Filter by channel type.
    /// Optional. Filter by user and attach user data.
    /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
    /// Optional. Filter for movies.
    /// Optional. Filter for series.
    /// Optional. Filter for news.
    /// Optional. Filter for kids.
    /// Optional. Filter for sports.
    /// Optional. The maximum number of records to return.
    /// Optional. Filter by channels that are favorites, or not.
    /// Optional. Filter by channels that are liked, or not.
    /// Optional. Filter by channels that are disliked, or not.
    /// Optional. Include image information in output.
    /// Optional. The max number of images to return, per image type.
    /// "Optional. The image types to include in the output.
    /// Optional. Specify additional fields of information to return in the output.
    /// Optional. Include user data.
    /// Optional. Key to sort by.
    /// Optional. Sort order.
    /// Optional. Incorporate favorite and like status into channel sorting.
    /// Optional. Adds current program info to each channel.
    /// Available live tv channels returned.
    /// 
    /// An  containing the resulting available live tv channels.
    /// 
    [HttpGet("Channels")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public ActionResult> GetLiveTvChannels(
        [FromQuery] ChannelType? type,
        [FromQuery] Guid? userId,
        [FromQuery] int? startIndex,
        [FromQuery] bool? isMovie,
        [FromQuery] bool? isSeries,
        [FromQuery] bool? isNews,
        [FromQuery] bool? isKids,
        [FromQuery] bool? isSports,
        [FromQuery] int? limit,
        [FromQuery] bool? isFavorite,
        [FromQuery] bool? isLiked,
        [FromQuery] bool? isDisliked,
        [FromQuery] bool? enableImages,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery] bool? enableUserData,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemSortBy[] sortBy,
        [FromQuery] SortOrder? sortOrder,
        [FromQuery] bool enableFavoriteSorting = false,
        [FromQuery] bool addCurrentProgram = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        var channelResult = _liveTvManager.GetInternalChannels(
            new LiveTvChannelQuery
            {
                ChannelType = type,
                UserId = userId.Value,
                StartIndex = startIndex,
                Limit = limit,
                IsFavorite = isFavorite,
                IsLiked = isLiked,
                IsDisliked = isDisliked,
                EnableFavoriteSorting = enableFavoriteSorting,
                IsMovie = isMovie,
                IsSeries = isSeries,
                IsNews = isNews,
                IsKids = isKids,
                IsSports = isSports,
                SortBy = sortBy,
                SortOrder = sortOrder ?? SortOrder.Ascending,
                AddCurrentProgram = addCurrentProgram
            },
            dtoOptions,
            CancellationToken.None);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var fieldsList = dtoOptions.Fields.ToList();
        fieldsList.Remove(ItemFields.CanDelete);
        fieldsList.Remove(ItemFields.CanDownload);
        fieldsList.Remove(ItemFields.DisplayPreferencesId);
        fieldsList.Remove(ItemFields.Etag);
        dtoOptions.Fields = fieldsList.ToArray();
        dtoOptions.AddCurrentProgram = addCurrentProgram;
        var returnArray = _dtoService.GetBaseItemDtos(channelResult.Items, dtoOptions, user);
        return new QueryResult(
            startIndex,
            channelResult.TotalRecordCount,
            returnArray);
    }
    /// 
    /// Gets a live tv channel.
    /// 
    /// Channel id.
    /// Optional. Attach user data.
    /// Live tv channel returned.
    /// Item not found.
    /// An  containing the live tv channel.
    [HttpGet("Channels/{channelId}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public ActionResult GetChannel([FromRoute, Required] Guid channelId, [FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var item = channelId.IsEmpty()
            ? _libraryManager.GetUserRootFolder()
            : _libraryManager.GetItemById(channelId, user);
        if (item is null)
        {
            return NotFound();
        }
        var dtoOptions = new DtoOptions()
            .AddClientFields(User);
        return _dtoService.GetBaseItemDto(item, dtoOptions, user);
    }
    /// 
    /// Gets live tv recordings.
    /// 
    /// Optional. Filter by channel id.
    /// Optional. Filter by user and attach user data.
    /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
    /// Optional. The maximum number of records to return.
    /// Optional. Filter by recording status.
    /// Optional. Filter by recordings that are in progress, or not.
    /// Optional. Filter by recordings belonging to a series timer.
    /// Optional. Include image information in output.
    /// Optional. The max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// Optional. Specify additional fields of information to return in the output.
    /// Optional. Include user data.
    /// Optional. Filter for movies.
    /// Optional. Filter for series.
    /// Optional. Filter for kids.
    /// Optional. Filter for sports.
    /// Optional. Filter for news.
    /// Optional. Filter for is library item.
    /// Optional. Return total record count.
    /// Live tv recordings returned.
    /// An  containing the live tv recordings.
    [HttpGet("Recordings")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task>> GetRecordings(
        [FromQuery] string? channelId,
        [FromQuery] Guid? userId,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery] RecordingStatus? status,
        [FromQuery] bool? isInProgress,
        [FromQuery] string? seriesTimerId,
        [FromQuery] bool? enableImages,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery] bool? enableUserData,
        [FromQuery] bool? isMovie,
        [FromQuery] bool? isSeries,
        [FromQuery] bool? isKids,
        [FromQuery] bool? isSports,
        [FromQuery] bool? isNews,
        [FromQuery] bool? isLibraryItem,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        return await _liveTvManager.GetRecordingsAsync(
            new RecordingQuery
            {
                ChannelId = channelId,
                UserId = userId.Value,
                StartIndex = startIndex,
                Limit = limit,
                Status = status,
                SeriesTimerId = seriesTimerId,
                IsInProgress = isInProgress,
                EnableTotalRecordCount = enableTotalRecordCount,
                IsMovie = isMovie,
                IsNews = isNews,
                IsSeries = isSeries,
                IsKids = isKids,
                IsSports = isSports,
                IsLibraryItem = isLibraryItem,
                Fields = fields,
                ImageTypeLimit = imageTypeLimit,
                EnableImages = enableImages
            },
            dtoOptions).ConfigureAwait(false);
    }
    /// 
    /// Gets live tv recording series.
    /// 
    /// Optional. Filter by channel id.
    /// Optional. Filter by user and attach user data.
    /// Optional. Filter by recording group.
    /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
    /// Optional. The maximum number of records to return.
    /// Optional. Filter by recording status.
    /// Optional. Filter by recordings that are in progress, or not.
    /// Optional. Filter by recordings belonging to a series timer.
    /// Optional. Include image information in output.
    /// Optional. The max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// Optional. Specify additional fields of information to return in the output.
    /// Optional. Include user data.
    /// Optional. Return total record count.
    /// Live tv recordings returned.
    /// An  containing the live tv recordings.
    [HttpGet("Recordings/Series")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [Obsolete("This endpoint is obsolete.")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "channelId", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "groupId", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "startIndex", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "limit", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "status", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isInProgress", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "seriesTimerId", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImages", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "imageTypeLimit", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableImageTypes", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "fields", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableUserData", Justification = "Imported from ServiceStack")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "enableTotalRecordCount", Justification = "Imported from ServiceStack")]
    public ActionResult> GetRecordingsSeries(
        [FromQuery] string? channelId,
        [FromQuery] Guid? userId,
        [FromQuery] string? groupId,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery] RecordingStatus? status,
        [FromQuery] bool? isInProgress,
        [FromQuery] string? seriesTimerId,
        [FromQuery] bool? enableImages,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery] bool? enableUserData,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        return new QueryResult();
    }
    /// 
    /// Gets live tv recording groups.
    /// 
    /// Optional. Filter by user and attach user data.
    /// Recording groups returned.
    /// An  containing the recording groups.
    [HttpGet("Recordings/Groups")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [Obsolete("This endpoint is obsolete.")]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Imported from ServiceStack")]
    public ActionResult> GetRecordingGroups([FromQuery] Guid? userId)
    {
        return new QueryResult();
    }
    /// 
    /// Gets recording folders.
    /// 
    /// Optional. Filter by user and attach user data.
    /// Recording folders returned.
    /// An  containing the recording folders.
    [HttpGet("Recordings/Folders")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task>> GetRecordingFolders([FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var folders = await _liveTvManager.GetRecordingFoldersAsync(user).ConfigureAwait(false);
        var returnArray = _dtoService.GetBaseItemDtos(folders, new DtoOptions(), user);
        return new QueryResult(returnArray);
    }
    /// 
    /// Gets a live tv recording.
    /// 
    /// Recording id.
    /// Optional. Attach user data.
    /// Recording returned.
    /// Item not found.
    /// An  containing the live tv recording.
    [HttpGet("Recordings/{recordingId}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public ActionResult GetRecording([FromRoute, Required] Guid recordingId, [FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var item = recordingId.IsEmpty()
            ? _libraryManager.GetUserRootFolder()
            : _libraryManager.GetItemById(recordingId, user);
        if (item is null)
        {
            return NotFound();
        }
        var dtoOptions = new DtoOptions()
            .AddClientFields(User);
        return _dtoService.GetBaseItemDto(item, dtoOptions, user);
    }
    /// 
    /// Resets a tv tuner.
    /// 
    /// Tuner id.
    /// Tuner reset.
    /// A .
    [HttpPost("Tuners/{tunerId}/Reset")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [Authorize(Policy = Policies.LiveTvManagement)]
    public async Task ResetTuner([FromRoute, Required] string tunerId)
    {
        await _liveTvManager.ResetTuner(tunerId, CancellationToken.None).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Gets a timer.
    /// 
    /// Timer id.
    /// Timer returned.
    /// 
    /// A  containing an  which contains the timer.
    /// 
    [HttpGet("Timers/{timerId}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task> GetTimer([FromRoute, Required] string timerId)
    {
        return await _liveTvManager.GetTimer(timerId, CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets the default values for a new timer.
    /// 
    /// Optional. To attach default values based on a program.
    /// Default values returned.
    /// 
    /// A  containing an  which contains the default values for a timer.
    /// 
    [HttpGet("Timers/Defaults")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task> GetDefaultTimer([FromQuery] string? programId)
    {
        return string.IsNullOrEmpty(programId)
            ? await _liveTvManager.GetNewTimerDefaults(CancellationToken.None).ConfigureAwait(false)
            : await _liveTvManager.GetNewTimerDefaults(programId, CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets the live tv timers.
    /// 
    /// Optional. Filter by channel id.
    /// Optional. Filter by timers belonging to a series timer.
    /// Optional. Filter by timers that are active.
    /// Optional. Filter by timers that are scheduled.
    /// 
    /// A  containing an  which contains the live tv timers.
    /// 
    [HttpGet("Timers")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task>> GetTimers(
        [FromQuery] string? channelId,
        [FromQuery] string? seriesTimerId,
        [FromQuery] bool? isActive,
        [FromQuery] bool? isScheduled)
    {
        return await _liveTvManager.GetTimers(
            new TimerQuery
            {
                ChannelId = channelId,
                SeriesTimerId = seriesTimerId,
                IsActive = isActive,
                IsScheduled = isScheduled
            },
            CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets available live tv epgs.
    /// 
    /// The channels to return guide information for.
    /// Optional. Filter by user id.
    /// Optional. The minimum premiere start date.
    /// Optional. Filter by programs that have completed airing, or not.
    /// Optional. Filter by programs that are currently airing, or not.
    /// Optional. The maximum premiere start date.
    /// Optional. The minimum premiere end date.
    /// Optional. The maximum premiere end date.
    /// Optional. Filter for movies.
    /// Optional. Filter for series.
    /// Optional. Filter for news.
    /// Optional. Filter for kids.
    /// Optional. Filter for sports.
    /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
    /// Optional. The maximum number of records to return.
    /// Optional. Specify one or more sort orders, comma delimited. Options: Name, StartDate.
    /// Sort Order - Ascending,Descending.
    /// The genres to return guide information for.
    /// The genre ids to return guide information for.
    /// Optional. Include image information in output.
    /// Optional. The max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// Optional. Include user data.
    /// Optional. Filter by series timer id.
    /// Optional. Filter by library series id.
    /// Optional. Specify additional fields of information to return in the output.
    /// Retrieve total record count.
    /// Live tv epgs returned.
    /// 
    /// A  containing a  which contains the live tv epgs.
    /// 
    [HttpGet("Programs")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task>> GetLiveTvPrograms(
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] channelIds,
        [FromQuery] Guid? userId,
        [FromQuery] DateTime? minStartDate,
        [FromQuery] bool? hasAired,
        [FromQuery] bool? isAiring,
        [FromQuery] DateTime? maxStartDate,
        [FromQuery] DateTime? minEndDate,
        [FromQuery] DateTime? maxEndDate,
        [FromQuery] bool? isMovie,
        [FromQuery] bool? isSeries,
        [FromQuery] bool? isNews,
        [FromQuery] bool? isKids,
        [FromQuery] bool? isSports,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemSortBy[] sortBy,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] SortOrder[] sortOrder,
        [FromQuery, ModelBinder(typeof(PipeDelimitedCollectionModelBinder))] string[] genres,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] genreIds,
        [FromQuery] bool? enableImages,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery] bool? enableUserData,
        [FromQuery] string? seriesTimerId,
        [FromQuery] Guid? librarySeriesId,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var query = new InternalItemsQuery(user)
        {
            ChannelIds = channelIds,
            HasAired = hasAired,
            IsAiring = isAiring,
            EnableTotalRecordCount = enableTotalRecordCount,
            MinStartDate = minStartDate,
            MinEndDate = minEndDate,
            MaxStartDate = maxStartDate,
            MaxEndDate = maxEndDate,
            StartIndex = startIndex,
            Limit = limit,
            OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
            IsNews = isNews,
            IsMovie = isMovie,
            IsSeries = isSeries,
            IsKids = isKids,
            IsSports = isSports,
            SeriesTimerId = seriesTimerId,
            Genres = genres,
            GenreIds = genreIds
        };
        if (!librarySeriesId.IsNullOrEmpty())
        {
            query.IsSeries = true;
            var series = _libraryManager.GetItemById(librarySeriesId.Value);
            if (series is not null)
            {
                query.Name = series.Name;
            }
        }
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets available live tv epgs.
    /// 
    /// Request body.
    /// Live tv epgs returned.
    /// 
    /// A  containing a  which contains the live tv epgs.
    /// 
    [HttpPost("Programs")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [Authorize(Policy = Policies.LiveTvAccess)]
    public async Task>> GetPrograms([FromBody] GetProgramsDto body)
    {
        var user = body.UserId.IsNullOrEmpty() ? null : _userManager.GetUserById(body.UserId.Value);
        var query = new InternalItemsQuery(user)
        {
            ChannelIds = body.ChannelIds ?? [],
            HasAired = body.HasAired,
            IsAiring = body.IsAiring,
            EnableTotalRecordCount = body.EnableTotalRecordCount,
            MinStartDate = body.MinStartDate,
            MinEndDate = body.MinEndDate,
            MaxStartDate = body.MaxStartDate,
            MaxEndDate = body.MaxEndDate,
            StartIndex = body.StartIndex,
            Limit = body.Limit,
            OrderBy = RequestHelpers.GetOrderBy(body.SortBy ?? [], body.SortOrder ?? []),
            IsNews = body.IsNews,
            IsMovie = body.IsMovie,
            IsSeries = body.IsSeries,
            IsKids = body.IsKids,
            IsSports = body.IsSports,
            SeriesTimerId = body.SeriesTimerId,
            Genres = body.Genres ?? [],
            GenreIds = body.GenreIds ?? []
        };
        if (!body.LibrarySeriesId.IsNullOrEmpty())
        {
            query.IsSeries = true;
            var series = _libraryManager.GetItemById(body.LibrarySeriesId.Value);
            if (series is not null)
            {
                query.Name = series.Name;
            }
        }
        var dtoOptions = new DtoOptions { Fields = body.Fields ?? [] }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(body.EnableImages, body.EnableUserData, body.ImageTypeLimit, body.EnableImageTypes ?? []);
        return await _liveTvManager.GetPrograms(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets recommended live tv epgs.
    /// 
    /// Optional. filter by user id.
    /// Optional. The record index to start at. All items with a lower index will be dropped from the results.
    /// Optional. The maximum number of records to return.
    /// Optional. Filter by programs that are currently airing, or not.
    /// Optional. Filter by programs that have completed airing, or not.
    /// Optional. Filter for series.
    /// Optional. Filter for movies.
    /// Optional. Filter for news.
    /// Optional. Filter for kids.
    /// Optional. Filter for sports.
    /// Optional. Include image information in output.
    /// Optional. The max number of images to return, per image type.
    /// Optional. The image types to include in the output.
    /// The genres to return guide information for.
    /// Optional. Specify additional fields of information to return in the output.
    /// Optional. include user data.
    /// Retrieve total record count.
    /// Recommended epgs returned.
    /// A  containing the queryresult of recommended epgs.
    [HttpGet("Programs/Recommended")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task>> GetRecommendedPrograms(
        [FromQuery] Guid? userId,
        [FromQuery] int? startIndex,
        [FromQuery] int? limit,
        [FromQuery] bool? isAiring,
        [FromQuery] bool? hasAired,
        [FromQuery] bool? isSeries,
        [FromQuery] bool? isMovie,
        [FromQuery] bool? isNews,
        [FromQuery] bool? isKids,
        [FromQuery] bool? isSports,
        [FromQuery] bool? enableImages,
        [FromQuery] int? imageTypeLimit,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ImageType[] enableImageTypes,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] Guid[] genreIds,
        [FromQuery, ModelBinder(typeof(CommaDelimitedCollectionModelBinder))] ItemFields[] fields,
        [FromQuery] bool? enableUserData,
        [FromQuery] bool enableTotalRecordCount = true)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        var query = new InternalItemsQuery(user)
        {
            IsAiring = isAiring,
            StartIndex = startIndex,
            Limit = limit,
            HasAired = hasAired,
            IsSeries = isSeries,
            IsMovie = isMovie,
            IsKids = isKids,
            IsNews = isNews,
            IsSports = isSports,
            EnableTotalRecordCount = enableTotalRecordCount,
            GenreIds = genreIds
        };
        var dtoOptions = new DtoOptions { Fields = fields }
            .AddClientFields(User)
            .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
        return await _liveTvManager.GetRecommendedProgramsAsync(query, dtoOptions, CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Gets a live tv program.
    /// 
    /// Program id.
    /// Optional. Attach user data.
    /// Program returned.
    /// An  containing the livetv program.
    [HttpGet("Programs/{programId}")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task> GetProgram(
        [FromRoute, Required] string programId,
        [FromQuery] Guid? userId)
    {
        userId = RequestHelpers.GetUserId(User, userId);
        var user = userId.IsNullOrEmpty()
            ? null
            : _userManager.GetUserById(userId.Value);
        return await _liveTvManager.GetProgram(programId, CancellationToken.None, user).ConfigureAwait(false);
    }
    /// 
    /// Deletes a live tv recording.
    /// 
    /// Recording id.
    /// Recording deleted.
    /// Item not found.
    /// A  on success, or a  if item not found.
    [HttpDelete("Recordings/{recordingId}")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult DeleteRecording([FromRoute, Required] Guid recordingId)
    {
        var item = _libraryManager.GetItemById(recordingId, User.GetUserId());
        if (item is null)
        {
            return NotFound();
        }
        _libraryManager.DeleteItem(item, new DeleteOptions
        {
            DeleteFileLocation = false
        });
        return NoContent();
    }
    /// 
    /// Cancels a live tv timer.
    /// 
    /// Timer id.
    /// Timer deleted.
    /// A .
    [HttpDelete("Timers/{timerId}")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task CancelTimer([FromRoute, Required] string timerId)
    {
        await _liveTvManager.CancelTimer(timerId).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Updates a live tv timer.
    /// 
    /// Timer id.
    /// New timer info.
    /// Timer updated.
    /// A .
    [HttpPost("Timers/{timerId}")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "timerId", Justification = "Imported from ServiceStack")]
    public async Task UpdateTimer([FromRoute, Required] string timerId, [FromBody] TimerInfoDto timerInfo)
    {
        await _liveTvManager.UpdateTimer(timerInfo, CancellationToken.None).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Creates a live tv timer.
    /// 
    /// New timer info.
    /// Timer created.
    /// A .
    [HttpPost("Timers")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task CreateTimer([FromBody] TimerInfoDto timerInfo)
    {
        await _liveTvManager.CreateTimer(timerInfo, CancellationToken.None).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Gets a live tv series timer.
    /// 
    /// Timer id.
    /// Series timer returned.
    /// Series timer not found.
    /// A  on success, or a  if timer not found.
    [HttpGet("SeriesTimers/{timerId}")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task> GetSeriesTimer([FromRoute, Required] string timerId)
    {
        var timer = await _liveTvManager.GetSeriesTimer(timerId, CancellationToken.None).ConfigureAwait(false);
        if (timer is null)
        {
            return NotFound();
        }
        return timer;
    }
    /// 
    /// Gets live tv series timers.
    /// 
    /// Optional. Sort by SortName or Priority.
    /// Optional. Sort in Ascending or Descending order.
    /// Timers returned.
    /// An  of live tv series timers.
    [HttpGet("SeriesTimers")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task>> GetSeriesTimers([FromQuery] string? sortBy, [FromQuery] SortOrder? sortOrder)
    {
        return await _liveTvManager.GetSeriesTimers(
            new SeriesTimerQuery
            {
                SortOrder = sortOrder ?? SortOrder.Ascending,
                SortBy = sortBy
            },
            CancellationToken.None).ConfigureAwait(false);
    }
    /// 
    /// Cancels a live tv series timer.
    /// 
    /// Timer id.
    /// Timer cancelled.
    /// A .
    [HttpDelete("SeriesTimers/{timerId}")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task CancelSeriesTimer([FromRoute, Required] string timerId)
    {
        await _liveTvManager.CancelSeriesTimer(timerId).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Updates a live tv series timer.
    /// 
    /// Timer id.
    /// New series timer info.
    /// Series timer updated.
    /// A .
    [HttpPost("SeriesTimers/{timerId}")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "timerId", Justification = "Imported from ServiceStack")]
    public async Task UpdateSeriesTimer([FromRoute, Required] string timerId, [FromBody] SeriesTimerInfoDto seriesTimerInfo)
    {
        await _liveTvManager.UpdateSeriesTimer(seriesTimerInfo, CancellationToken.None).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Creates a live tv series timer.
    /// 
    /// New series timer info.
    /// Series timer info created.
    /// A .
    [HttpPost("SeriesTimers")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task CreateSeriesTimer([FromBody] SeriesTimerInfoDto seriesTimerInfo)
    {
        await _liveTvManager.CreateSeriesTimer(seriesTimerInfo, CancellationToken.None).ConfigureAwait(false);
        return NoContent();
    }
    /// 
    /// Get recording group.
    /// 
    /// Group id.
    /// A .
    [HttpGet("Recordings/Groups/{groupId}")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [Obsolete("This endpoint is obsolete.")]
    public ActionResult GetRecordingGroup([FromRoute, Required] Guid groupId)
    {
        return NotFound();
    }
    /// 
    /// Get guide info.
    /// 
    /// Guide info returned.
    /// An  containing the guide info.
    [HttpGet("GuideInfo")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult GetGuideInfo()
        => _guideManager.GetGuideInfo();
    /// 
    /// Adds a tuner host.
    /// 
    /// New tuner host.
    /// Created tuner host returned.
    /// A  containing the created tuner host.
    [HttpPost("TunerHosts")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task> AddTunerHost([FromBody] TunerHostInfo tunerHostInfo)
        => await _tunerHostManager.SaveTunerHost(tunerHostInfo).ConfigureAwait(false);
    /// 
    /// Deletes a tuner host.
    /// 
    /// Tuner host id.
    /// Tuner host deleted.
    /// A .
    [HttpDelete("TunerHosts")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public ActionResult DeleteTunerHost([FromQuery] string? id)
    {
        var config = _configurationManager.GetConfiguration("livetv");
        config.TunerHosts = config.TunerHosts.Where(i => !string.Equals(id, i.Id, StringComparison.OrdinalIgnoreCase)).ToArray();
        _configurationManager.SaveConfiguration("livetv", config);
        return NoContent();
    }
    /// 
    /// Gets default listings provider info.
    /// 
    /// Default listings provider info returned.
    /// An  containing the default listings provider info.
    [HttpGet("ListingProviders/Default")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public ActionResult GetDefaultListingProvider()
    {
        return new ListingsProviderInfo();
    }
    /// 
    /// Adds a listings provider.
    /// 
    /// Password.
    /// New listings info.
    /// Validate listings.
    /// Validate login.
    /// Created listings provider returned.
    /// A  containing the created listings provider.
    [HttpPost("ListingProviders")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [SuppressMessage("Microsoft.Performance", "CA5350:RemoveSha1", MessageId = "AddListingProvider", Justification = "Imported from ServiceStack")]
    public async Task> AddListingProvider(
        [FromQuery] string? pw,
        [FromBody] ListingsProviderInfo listingsProviderInfo,
        [FromQuery] bool validateListings = false,
        [FromQuery] bool validateLogin = false)
    {
        if (!string.IsNullOrEmpty(pw))
        {
            // TODO: remove ToLower when Convert.ToHexString supports lowercase
            // Schedules Direct requires the hex to be lowercase
            listingsProviderInfo.Password = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(pw))).ToLowerInvariant();
        }
        return await _listingsManager.SaveListingProvider(listingsProviderInfo, validateLogin, validateListings).ConfigureAwait(false);
    }
    /// 
    /// Delete listing provider.
    /// 
    /// Listing provider id.
    /// Listing provider deleted.
    /// A .
    [HttpDelete("ListingProviders")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public ActionResult DeleteListingProvider([FromQuery] string? id)
    {
        _listingsManager.DeleteListingsProvider(id);
        return NoContent();
    }
    /// 
    /// Gets available lineups.
    /// 
    /// Provider id.
    /// Provider type.
    /// Location.
    /// Country.
    /// Available lineups returned.
    /// A  containing the available lineups.
    [HttpGet("ListingProviders/Lineups")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task>> GetLineups(
        [FromQuery] string? id,
        [FromQuery] string? type,
        [FromQuery] string? location,
        [FromQuery] string? country)
        => await _listingsManager.GetLineups(type, id, country, location).ConfigureAwait(false);
    /// 
    /// Gets available countries.
    /// 
    /// Available countries returned.
    /// A  containing the available countries.
    [HttpGet("ListingProviders/SchedulesDirect/Countries")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesFile(MediaTypeNames.Application.Json)]
    public async Task GetSchedulesDirectCountries()
    {
        var client = _httpClientFactory.CreateClient(NamedClient.Default);
        // https://json.schedulesdirect.org/20141201/available/countries
        // Can't dispose the response as it's required up the call chain.
        var response = await client.GetAsync(new Uri("https://json.schedulesdirect.org/20141201/available/countries"))
            .ConfigureAwait(false);
        return File(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), MediaTypeNames.Application.Json);
    }
    /// 
    /// Get channel mapping options.
    /// 
    /// Provider id.
    /// Channel mapping options returned.
    /// An  containing the channel mapping options.
    [HttpGet("ChannelMappingOptions")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public Task GetChannelMappingOptions([FromQuery] string? providerId)
        => _listingsManager.GetChannelMappingOptions(providerId);
    /// 
    /// Set channel mappings.
    /// 
    /// The set channel mapping dto.
    /// Created channel mapping returned.
    /// An  containing the created channel mapping.
    [HttpPost("ChannelMappings")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public Task SetChannelMapping([FromBody, Required] SetChannelMappingDto dto)
        => _listingsManager.SetChannelMapping(dto.ProviderId, dto.TunerChannelId, dto.ProviderChannelId);
    /// 
    /// Get tuner host types.
    /// 
    /// Tuner host types returned.
    /// An  containing the tuner host types.
    [HttpGet("TunerHosts/Types")]
    [Authorize(Policy = Policies.LiveTvAccess)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IEnumerable GetTunerHostTypes()
        => _tunerHostManager.GetTunerHostTypes();
    /// 
    /// Discover tuners.
    /// 
    /// Only discover new tuners.
    /// Tuners returned.
    /// An  containing the tuners.
    [HttpGet("Tuners/Discvover", Name = "DiscvoverTuners")]
    [HttpGet("Tuners/Discover")]
    [Authorize(Policy = Policies.LiveTvManagement)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public IAsyncEnumerable DiscoverTuners([FromQuery] bool newDevicesOnly = false)
        => _tunerHostManager.DiscoverTuners(newDevicesOnly);
    /// 
    /// Gets a live tv recording stream.
    /// 
    /// Recording id.
    /// Recording stream returned.
    /// Recording not found.
    /// 
    /// An  containing the recording stream on success,
    /// or a  if recording not found.
    /// 
    [HttpGet("LiveRecordings/{recordingId}/stream")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesVideoFile]
    public ActionResult GetLiveRecordingFile([FromRoute, Required] string recordingId)
    {
        var path = _recordingsManager.GetActiveRecordingPath(recordingId);
        if (string.IsNullOrWhiteSpace(path))
        {
            return NotFound();
        }
        var stream = new ProgressiveFileStream(path, null, _transcodeManager);
        return new FileStreamResult(stream, MimeTypes.GetMimeType(path));
    }
    /// 
    /// Gets a live tv channel stream.
    /// 
    /// Stream id.
    /// Container type.
    /// Stream returned.
    /// Stream not found.
    /// 
    /// An  containing the channel stream on success,
    /// or a  if stream not found.
    /// 
    [HttpGet("LiveStreamFiles/{streamId}/stream.{container}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesVideoFile]
    public ActionResult GetLiveStreamFile(
        [FromRoute, Required] string streamId,
        [FromRoute, Required] [RegularExpression(EncodingHelper.ContainerValidationRegex)] string container)
    {
        var liveStreamInfo = _mediaSourceManager.GetLiveStreamInfoByUniqueId(streamId);
        if (liveStreamInfo is null)
        {
            return NotFound();
        }
        var liveStream = new ProgressiveFileStream(liveStreamInfo.GetStream());
        return new FileStreamResult(liveStream, MimeTypes.GetMimeType("file." + container));
    }
}