jellyfin/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs

821 lines
32 KiB
C#
Raw Normal View History

#nullable disable
#pragma warning disable CS1591
2015-07-21 04:22:46 +00:00
using System;
2015-07-23 05:25:55 +00:00
using System.Collections.Concurrent;
2015-07-21 04:22:46 +00:00
using System.Collections.Generic;
2015-07-23 05:25:55 +00:00
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Mime;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
2015-07-21 04:22:46 +00:00
using System.Threading;
using System.Threading.Tasks;
2021-08-28 22:32:50 +00:00
using Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos;
2021-09-03 18:35:52 +00:00
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
2018-09-12 17:26:21 +00:00
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using Microsoft.Extensions.Logging;
2015-07-21 04:22:46 +00:00
2016-11-03 23:35:19 +00:00
namespace Emby.Server.Implementations.LiveTv.Listings
2015-07-21 04:22:46 +00:00
{
2022-02-15 17:59:46 +00:00
public class SchedulesDirect : IListingsProvider, IDisposable
2015-07-21 04:22:46 +00:00
{
2020-08-31 20:20:19 +00:00
private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
2020-06-06 00:15:56 +00:00
private readonly ILogger<SchedulesDirect> _logger;
private readonly IHttpClientFactory _httpClientFactory;
2015-07-23 05:25:55 +00:00
private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
2020-11-26 20:54:14 +00:00
private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
2021-03-09 04:57:38 +00:00
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
2021-02-12 23:39:18 +00:00
private DateTime _lastErrorResponse;
2022-02-15 17:59:46 +00:00
private bool _disposed = false;
2020-11-26 20:54:14 +00:00
public SchedulesDirect(
ILogger<SchedulesDirect> logger,
2021-11-16 11:24:17 +00:00
IHttpClientFactory httpClientFactory)
2015-07-23 05:25:55 +00:00
{
_logger = logger;
_httpClientFactory = httpClientFactory;
2015-07-29 20:31:15 +00:00
}
2019-09-20 10:42:08 +00:00
/// <inheritdoc />
public string Name => "Schedules Direct";
/// <inheritdoc />
public string Type => nameof(SchedulesDirect);
private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
2015-07-29 17:16:00 +00:00
{
2019-01-13 20:37:13 +00:00
var dates = new List<string>();
2015-07-29 17:16:00 +00:00
2022-02-15 17:59:46 +00:00
var start = new[] { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
var end = new[] { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
2015-07-29 17:16:00 +00:00
2015-11-12 02:25:12 +00:00
while (start <= end)
2015-07-29 17:16:00 +00:00
{
2020-08-31 20:20:19 +00:00
dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
2015-07-29 17:16:00 +00:00
start = start.AddDays(1);
}
return dates;
}
2017-02-04 23:32:16 +00:00
public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
2015-07-23 05:25:55 +00:00
{
ArgumentException.ThrowIfNullOrEmpty(channelId);
2017-02-04 23:32:16 +00:00
// Normalize incoming input
channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
2015-09-01 19:18:25 +00:00
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2015-07-23 05:25:55 +00:00
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(token))
2015-07-23 05:25:55 +00:00
{
_logger.LogWarning("SchedulesDirect token is empty, returning empty program list");
return Enumerable.Empty<ProgramInfo>();
2015-07-23 05:25:55 +00:00
}
2015-07-29 17:16:00 +00:00
var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
2015-07-23 05:25:55 +00:00
_logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
2021-08-28 22:32:50 +00:00
var requestList = new List<RequestScheduleForChannelDto>()
{
2021-08-28 22:32:50 +00:00
new RequestScheduleForChannelDto()
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
StationId = channelId,
Date = dates
}
};
2015-07-23 05:25:55 +00:00
_logger.LogDebug("Request string for schedules is: {@RequestString}", requestList);
2016-03-17 19:29:53 +00:00
using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules");
options.Content = JsonContent.Create(requestList, options: _jsonOptions);
options.Headers.TryAddWithoutValidation("token", token);
using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
2020-11-17 18:43:00 +00:00
await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-09-03 18:35:52 +00:00
var dailySchedules = await JsonSerializer.DeserializeAsync<IReadOnlyList<DayDto>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2022-12-05 14:00:20 +00:00
if (dailySchedules is null)
2021-09-03 19:36:07 +00:00
{
return Array.Empty<ProgramInfo>();
}
_logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId);
2016-03-17 19:29:53 +00:00
using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs");
programRequestOptions.Headers.TryAddWithoutValidation("token", token);
2015-07-23 05:25:55 +00:00
2021-09-03 16:59:40 +00:00
var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct();
programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions);
2015-07-23 05:25:55 +00:00
using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
2020-11-17 18:43:00 +00:00
await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-09-03 18:35:52 +00:00
var programDetails = await JsonSerializer.DeserializeAsync<IReadOnlyList<ProgramDetailsDto>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2022-12-05 14:00:20 +00:00
if (programDetails is null)
2021-09-03 19:36:07 +00:00
{
return Array.Empty<ProgramInfo>();
}
var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y);
2017-06-11 20:40:25 +00:00
2021-02-15 13:19:08 +00:00
var programIdsWithImages = programDetails
2021-08-28 22:32:50 +00:00
.Where(p => p.HasImageArtwork).Select(p => p.ProgramId)
2021-02-15 13:19:08 +00:00
.ToList();
2015-07-23 05:25:55 +00:00
var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
2017-02-09 03:58:04 +00:00
var programsInfo = new List<ProgramInfo>();
2021-08-28 22:32:50 +00:00
foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs))
{
// _logger.LogDebug("Proccesing Schedule for statio ID " + stationID +
// " which corresponds to channel " + channelNumber + " and program id " +
2021-08-28 22:32:50 +00:00
// schedule.ProgramId + " which says it has images? " +
// programDict[schedule.ProgramId].hasImageArtwork);
2015-07-23 05:25:55 +00:00
2021-09-03 18:35:52 +00:00
if (string.IsNullOrEmpty(schedule.ProgramId))
{
continue;
}
2022-12-05 14:01:13 +00:00
if (images is not null)
{
2021-08-28 22:32:50 +00:00
var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
if (imageIndex > -1)
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
var programEntry = programDict[schedule.ProgramId];
2017-06-11 20:40:25 +00:00
2021-09-03 18:35:52 +00:00
var allImages = images[imageIndex].Data;
2021-12-15 17:25:36 +00:00
var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
2017-06-11 20:40:25 +00:00
const double DesiredAspect = 2.0 / 3;
programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ??
GetProgramImage(ApiUrl, allImages, DesiredAspect, token);
2017-06-11 20:40:25 +00:00
const double WideAspect = 16.0 / 9;
2016-09-11 07:33:53 +00:00
programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token);
2017-06-11 21:58:49 +00:00
// Don't supply the same image twice
2021-08-28 22:32:50 +00:00
if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal))
{
2021-08-28 22:32:50 +00:00
programEntry.ThumbImage = null;
2015-07-23 05:25:55 +00:00
}
programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token);
2019-09-20 10:42:08 +00:00
// programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
// GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
// GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
// GetProgramImage(ApiUrl, data, "Banner-LOT", false);
}
2015-07-23 05:25:55 +00:00
}
2021-08-28 22:32:50 +00:00
programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId]));
2015-07-23 05:25:55 +00:00
}
return programsInfo;
2015-07-23 05:25:55 +00:00
}
2021-08-28 22:32:50 +00:00
private static int GetSizeOrder(ImageDataDto image)
2016-09-11 07:33:53 +00:00
{
2021-08-28 22:32:50 +00:00
if (int.TryParse(image.Height, out int value))
2016-09-11 07:33:53 +00:00
{
2019-09-20 10:42:08 +00:00
return value;
2016-09-11 07:33:53 +00:00
}
return 0;
}
2021-08-28 22:32:50 +00:00
private static string GetChannelNumber(MapDto map)
2015-10-11 00:39:30 +00:00
{
2021-08-28 22:32:50 +00:00
var channelNumber = map.LogicalChannelNumber;
2016-09-09 06:59:23 +00:00
2017-02-04 23:32:16 +00:00
if (string.IsNullOrWhiteSpace(channelNumber))
2015-10-11 00:39:30 +00:00
{
2021-08-28 22:32:50 +00:00
channelNumber = map.Channel;
2015-10-11 00:39:30 +00:00
}
2020-06-15 21:43:52 +00:00
2017-02-04 23:32:16 +00:00
if (string.IsNullOrWhiteSpace(channelNumber))
2016-03-17 19:29:53 +00:00
{
2021-08-28 22:32:50 +00:00
channelNumber = map.AtscMajor + "." + map.AtscMinor;
2016-03-17 19:29:53 +00:00
}
2015-10-11 00:39:30 +00:00
return channelNumber.TrimStart('0');
2015-10-11 00:39:30 +00:00
}
2021-08-28 22:32:50 +00:00
private static bool IsMovie(ProgramDetailsDto programInfo)
2017-06-11 20:40:25 +00:00
{
2021-08-28 22:32:50 +00:00
return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase);
2017-06-11 20:40:25 +00:00
}
2021-08-28 22:32:50 +00:00
private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details)
2015-07-23 05:25:55 +00:00
{
2022-12-05 14:00:20 +00:00
if (programInfo.AirDateTime is null)
2021-09-03 18:35:52 +00:00
{
return null;
}
var startAt = programInfo.AirDateTime.Value;
2021-08-28 22:32:50 +00:00
var endAt = startAt.AddSeconds(programInfo.Duration);
2019-01-13 20:37:13 +00:00
var audioType = ProgramAudio.Stereo;
2015-08-19 06:12:58 +00:00
2021-08-28 22:32:50 +00:00
var programId = programInfo.ProgramId ?? string.Empty;
2017-08-23 16:49:42 +00:00
string newID = programId + "T" + startAt.Ticks + "C" + channelId;
2015-07-23 05:25:55 +00:00
2021-09-03 16:59:40 +00:00
if (programInfo.AudioProperties.Count != 0)
2015-07-23 05:25:55 +00:00
{
2021-12-20 12:31:07 +00:00
if (programInfo.AudioProperties.Contains("atmos", StringComparison.OrdinalIgnoreCase))
2016-09-08 20:32:30 +00:00
{
audioType = ProgramAudio.Atmos;
}
2021-12-20 12:31:07 +00:00
else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparison.OrdinalIgnoreCase))
2015-07-29 17:16:00 +00:00
{
audioType = ProgramAudio.DolbyDigital;
}
2021-12-20 12:31:07 +00:00
else if (programInfo.AudioProperties.Contains("dd", StringComparison.OrdinalIgnoreCase))
2015-07-29 17:16:00 +00:00
{
audioType = ProgramAudio.DolbyDigital;
}
2021-12-20 12:31:07 +00:00
else if (programInfo.AudioProperties.Contains("stereo", StringComparison.OrdinalIgnoreCase))
2015-07-23 05:25:55 +00:00
{
audioType = ProgramAudio.Stereo;
}
else
{
audioType = ProgramAudio.Mono;
}
}
2015-08-04 14:26:36 +00:00
string episodeTitle = null;
2022-12-05 14:01:13 +00:00
if (details.EpisodeTitle150 is not null)
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
episodeTitle = details.EpisodeTitle150;
2015-07-23 05:25:55 +00:00
}
2015-08-04 14:26:36 +00:00
2015-07-23 05:25:55 +00:00
var info = new ProgramInfo
{
2017-02-04 23:32:16 +00:00
ChannelId = channelId,
2015-07-23 05:25:55 +00:00
Id = newID,
StartDate = startAt,
EndDate = endAt,
2021-08-28 22:32:50 +00:00
Name = details.Titles[0].Title120 ?? "Unknown",
2015-08-16 18:37:53 +00:00
OfficialRating = null,
2015-07-23 05:25:55 +00:00
CommunityRating = null,
2015-08-04 14:26:36 +00:00
EpisodeTitle = episodeTitle,
2015-07-23 05:25:55 +00:00
Audio = audioType,
2020-06-14 09:11:11 +00:00
// IsNew = programInfo.@new ?? false,
2022-12-05 14:00:20 +00:00
IsRepeat = programInfo.New is null,
2021-08-28 22:32:50 +00:00
IsSeries = string.Equals(details.EntityType, "episode", StringComparison.OrdinalIgnoreCase),
ImageUrl = details.PrimaryImage,
ThumbImageUrl = details.ThumbImage,
IsKids = string.Equals(details.Audience, "children", StringComparison.OrdinalIgnoreCase),
IsSports = string.Equals(details.EntityType, "sports", StringComparison.OrdinalIgnoreCase),
2017-06-11 20:40:25 +00:00
IsMovie = IsMovie(details),
2021-08-28 22:32:50 +00:00
Etag = programInfo.Md5,
IsLive = string.Equals(programInfo.LiveTapeDelay, "live", StringComparison.OrdinalIgnoreCase),
IsPremiere = programInfo.Premiere || (programInfo.IsPremiereOrFinale ?? string.Empty).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
2015-07-23 05:25:55 +00:00
};
2015-08-04 14:26:36 +00:00
2017-08-23 16:49:42 +00:00
var showId = programId;
2016-12-22 15:58:09 +00:00
2017-03-01 20:30:05 +00:00
if (!info.IsSeries)
{
// It's also a series if it starts with SH
info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
}
2016-12-22 15:58:09 +00:00
// According to SchedulesDirect, these are generic, unidentified episodes
// SH005316560000
var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
!showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
if (!hasUniqueShowId)
{
showId = newID;
}
info.ShowId = showId;
2022-12-05 14:01:13 +00:00
if (programInfo.VideoProperties is not null)
2015-08-19 06:12:58 +00:00
{
2021-12-20 12:31:07 +00:00
info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase);
info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase);
2015-08-19 06:12:58 +00:00
}
2022-12-05 14:01:13 +00:00
if (details.ContentRating is not null && details.ContentRating.Count > 0)
2015-08-19 06:12:58 +00:00
{
2021-08-28 22:32:50 +00:00
info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal)
2020-11-26 20:54:14 +00:00
.Replace("--", "-", StringComparison.Ordinal);
2015-08-21 15:34:42 +00:00
2015-08-26 18:17:38 +00:00
var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
2021-12-20 12:31:07 +00:00
if (invalid.Contains(info.OfficialRating, StringComparison.OrdinalIgnoreCase))
2015-08-21 15:34:42 +00:00
{
info.OfficialRating = null;
}
2015-08-19 06:12:58 +00:00
}
2022-12-05 14:01:13 +00:00
if (details.Descriptions is not null)
2015-08-19 06:12:58 +00:00
{
2022-12-05 14:01:13 +00:00
if (details.Descriptions.Description1000 is not null && details.Descriptions.Description1000.Count > 0)
2015-08-19 06:12:58 +00:00
{
2021-08-28 22:32:50 +00:00
info.Overview = details.Descriptions.Description1000[0].Description;
2015-08-19 06:12:58 +00:00
}
2022-12-05 14:01:13 +00:00
else if (details.Descriptions.Description100 is not null && details.Descriptions.Description100.Count > 0)
2015-08-19 06:12:58 +00:00
{
2021-08-28 22:32:50 +00:00
info.Overview = details.Descriptions.Description100[0].Description;
2015-08-19 06:12:58 +00:00
}
}
2015-08-16 18:37:53 +00:00
if (info.IsSeries)
{
2017-08-23 16:49:42 +00:00
info.SeriesId = programId.Substring(0, 10);
2015-08-19 06:12:58 +00:00
2020-06-06 19:17:49 +00:00
info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId;
2018-09-12 17:26:21 +00:00
2022-12-05 14:01:13 +00:00
if (details.Metadata is not null)
2015-08-19 06:12:58 +00:00
{
2021-08-28 22:32:50 +00:00
foreach (var metadataProgram in details.Metadata)
2017-03-01 20:30:05 +00:00
{
2017-08-24 19:52:48 +00:00
var gracenote = metadataProgram.Gracenote;
2022-12-05 14:01:13 +00:00
if (gracenote is not null)
2017-08-23 16:49:42 +00:00
{
2021-08-28 22:32:50 +00:00
info.SeasonNumber = gracenote.Season;
2017-08-24 19:52:48 +00:00
2021-08-28 22:32:50 +00:00
if (gracenote.Episode > 0)
2017-08-24 19:52:48 +00:00
{
2021-08-28 22:32:50 +00:00
info.EpisodeNumber = gracenote.Episode;
2017-08-24 19:52:48 +00:00
}
break;
2017-08-23 16:49:42 +00:00
}
2017-03-01 20:30:05 +00:00
}
2015-08-19 06:12:58 +00:00
}
2015-08-16 18:37:53 +00:00
}
2022-12-05 14:01:13 +00:00
if (details.OriginalAirDate is not null)
2015-07-23 05:25:55 +00:00
{
2021-09-03 18:35:52 +00:00
info.OriginalAirDate = details.OriginalAirDate;
2016-10-22 14:50:21 +00:00
info.ProductionYear = info.OriginalAirDate.Value.Year;
2015-07-23 05:25:55 +00:00
}
2022-12-05 14:01:13 +00:00
if (details.Movie is not null)
2018-09-12 17:26:21 +00:00
{
2021-08-28 22:32:50 +00:00
if (!string.IsNullOrEmpty(details.Movie.Year)
&& int.TryParse(details.Movie.Year, out int year))
2018-09-12 17:26:21 +00:00
{
info.ProductionYear = year;
}
}
2022-12-05 14:01:13 +00:00
if (details.Genres is not null)
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
2021-12-20 12:31:07 +00:00
info.IsNews = details.Genres.Contains("news", StringComparison.OrdinalIgnoreCase);
2015-08-19 17:58:41 +00:00
2021-12-20 12:31:07 +00:00
if (info.Genres.Contains("children", StringComparison.OrdinalIgnoreCase))
2015-08-19 17:58:41 +00:00
{
info.IsKids = true;
}
2015-07-23 05:25:55 +00:00
}
2015-08-19 06:12:58 +00:00
2015-07-23 05:25:55 +00:00
return info;
}
private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, string token)
2015-07-23 05:25:55 +00:00
{
var match = images
.OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
2021-08-28 22:32:50 +00:00
.ThenByDescending(i => GetSizeOrder(i))
.FirstOrDefault();
2016-09-20 15:21:44 +00:00
2022-12-05 14:00:20 +00:00
if (match is null)
2016-09-15 23:19:27 +00:00
{
return null;
}
2021-08-28 22:32:50 +00:00
var uri = match.Uri;
2016-09-11 07:33:53 +00:00
if (string.IsNullOrWhiteSpace(uri))
2016-09-11 07:33:53 +00:00
{
return null;
}
else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
{
return uri;
}
else
{
return apiUrl + "/image/" + uri + "?token=" + token;
2015-07-23 05:25:55 +00:00
}
}
2021-08-28 22:32:50 +00:00
private static double GetAspectRatio(ImageDataDto i)
2017-06-11 20:40:25 +00:00
{
int width = 0;
int height = 0;
2021-08-28 22:32:50 +00:00
if (!string.IsNullOrWhiteSpace(i.Width))
2017-06-11 20:40:25 +00:00
{
2021-08-28 22:32:50 +00:00
_ = int.TryParse(i.Width, out width);
2017-06-11 20:40:25 +00:00
}
2021-08-28 22:32:50 +00:00
if (!string.IsNullOrWhiteSpace(i.Height))
2017-06-11 20:40:25 +00:00
{
2021-08-28 22:32:50 +00:00
_ = int.TryParse(i.Height, out height);
2017-06-11 20:40:25 +00:00
}
if (height == 0 || width == 0)
{
return 0;
}
double result = width;
result /= height;
return result;
}
2021-09-03 18:35:52 +00:00
private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
2016-06-08 21:04:52 +00:00
ListingsProviderInfo info,
2020-11-26 20:54:14 +00:00
IReadOnlyList<string> programIds,
CancellationToken cancellationToken)
2015-07-23 05:25:55 +00:00
{
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2017-02-09 03:58:04 +00:00
if (programIds.Count == 0)
{
2021-09-03 18:35:52 +00:00
return Array.Empty<ShowImagesDto>();
2017-02-09 03:58:04 +00:00
}
2020-11-26 20:54:14 +00:00
StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
foreach (ReadOnlySpan<char> i in programIds)
2015-07-23 05:25:55 +00:00
{
2020-11-26 20:54:14 +00:00
str.Append('"')
.Append(i.Slice(0, 10))
.Append("\",");
2016-11-03 23:35:19 +00:00
}
2020-11-26 20:54:14 +00:00
// Remove last ,
str.Length--;
str.Append(']');
2015-08-22 02:59:10 +00:00
2020-09-07 11:20:39 +00:00
using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
{
2020-11-26 20:54:14 +00:00
Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
2020-09-07 11:20:39 +00:00
};
message.Headers.TryAddWithoutValidation("token", token);
2017-02-09 03:58:04 +00:00
try
2015-07-23 05:25:55 +00:00
{
using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
2020-11-17 18:43:00 +00:00
await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-09-03 18:35:52 +00:00
return await JsonSerializer.DeserializeAsync<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
2015-07-23 05:25:55 +00:00
}
2017-02-09 03:58:04 +00:00
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error getting image info from schedules direct");
2015-07-23 05:25:55 +00:00
2021-09-03 18:35:52 +00:00
return Array.Empty<ShowImagesDto>();
2017-02-09 03:58:04 +00:00
}
2015-07-23 05:25:55 +00:00
}
2015-07-23 17:58:20 +00:00
public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
2015-07-23 05:25:55 +00:00
{
2019-10-25 10:47:20 +00:00
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2015-07-23 05:25:55 +00:00
var lineups = new List<NameIdPair>();
if (string.IsNullOrWhiteSpace(token))
{
return lineups;
}
using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location);
options.Headers.TryAddWithoutValidation("token", token);
2015-07-23 05:25:55 +00:00
try
{
using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
2020-11-17 18:43:00 +00:00
await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-09-03 18:35:52 +00:00
var root = await JsonSerializer.DeserializeAsync<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
2017-10-20 16:16:56 +00:00
2022-12-05 14:01:13 +00:00
if (root is not null)
{
2021-08-28 22:32:50 +00:00
foreach (HeadendsDto headend in root)
2018-12-20 12:11:26 +00:00
{
2021-08-28 22:32:50 +00:00
foreach (LineupDto lineup in headend.Lineups)
2015-07-23 05:25:55 +00:00
{
lineups.Add(new NameIdPair
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name,
2021-09-03 16:59:40 +00:00
Id = lineup.Uri?[18..]
});
2015-07-23 05:25:55 +00:00
}
2018-12-20 12:11:26 +00:00
}
}
else
{
_logger.LogInformation("No lineups available");
2015-07-23 05:25:55 +00:00
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error getting headends");
2015-07-23 05:25:55 +00:00
}
return lineups;
}
private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
{
2015-07-23 13:23:22 +00:00
var username = info.Username;
2015-07-23 05:25:55 +00:00
2015-07-23 13:23:22 +00:00
// Reset the token if there's no username
if (string.IsNullOrWhiteSpace(username))
{
return null;
}
2015-07-23 05:25:55 +00:00
2015-07-23 13:23:22 +00:00
var password = info.Password;
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(password))
2015-07-23 13:23:22 +00:00
{
return null;
}
2015-07-23 05:25:55 +00:00
2015-09-01 19:18:25 +00:00
// Avoid hammering SD
if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
{
return null;
}
2020-11-26 20:54:14 +00:00
if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
2015-07-23 13:23:22 +00:00
{
savedToken = new NameValuePair();
_tokens.TryAdd(username, savedToken);
}
2015-07-23 05:25:55 +00:00
if (!string.IsNullOrEmpty(savedToken.Name)
&& long.TryParse(savedToken.Value, CultureInfo.InvariantCulture, out long ticks))
2015-07-23 13:23:22 +00:00
{
// If it's under 24 hours old we can still use it
if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
2015-07-23 05:25:55 +00:00
{
return savedToken.Name;
2015-07-23 05:25:55 +00:00
}
2015-07-23 13:23:22 +00:00
}
2015-07-23 05:25:55 +00:00
2015-07-23 13:23:22 +00:00
await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
2015-07-23 05:25:55 +00:00
var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
savedToken.Name = result;
savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
return result;
}
2020-11-14 21:30:34 +00:00
catch (HttpRequestException ex)
2015-09-01 19:18:25 +00:00
{
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
2015-09-01 19:18:25 +00:00
{
_tokens.Clear();
_lastErrorResponse = DateTime.UtcNow;
2015-09-01 19:18:25 +00:00
}
2020-06-15 21:43:52 +00:00
2015-09-01 19:18:25 +00:00
throw;
}
2015-07-23 05:25:55 +00:00
finally
{
_tokenSemaphore.Release();
}
}
private async Task<HttpResponseMessage> Send(
HttpRequestMessage options,
2016-06-08 21:04:52 +00:00
bool enableRetry,
ListingsProviderInfo providerInfo,
CancellationToken cancellationToken,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
2015-11-21 03:13:03 +00:00
{
2020-12-10 15:25:05 +00:00
var response = await _httpClientFactory.CreateClient(NamedClient.Default)
.SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
2015-11-21 03:13:03 +00:00
{
2020-12-08 15:28:19 +00:00
return response;
2016-06-08 21:04:52 +00:00
}
2020-12-10 15:25:05 +00:00
// Response is automatically disposed in the calling function,
// so dispose manually if not returning.
response.Dispose();
if (!enableRetry || (int)response.StatusCode >= 500)
{
throw new HttpRequestException(
string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase),
null,
response.StatusCode);
2016-06-08 21:04:52 +00:00
}
2020-12-10 15:25:05 +00:00
_tokens.Clear();
options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
2015-11-21 03:13:03 +00:00
}
private async Task<string> GetTokenInternal(
string username,
string password,
2015-07-23 05:25:55 +00:00
CancellationToken cancellationToken)
2015-07-21 04:22:46 +00:00
{
using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
2021-12-24 21:18:24 +00:00
#pragma warning disable CA5350 // SchedulesDirect is always SHA1.
var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password));
2021-12-24 21:18:24 +00:00
#pragma warning restore CA5350
// TODO: remove ToLower when Convert.ToHexString supports lowercase
// Schedules Direct requires the hex to be lowercase
string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant();
options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + "\"}", Encoding.UTF8, MediaTypeNames.Application.Json);
2015-07-23 05:25:55 +00:00
using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
2020-12-08 15:28:19 +00:00
response.EnsureSuccessStatusCode();
2020-11-17 18:43:00 +00:00
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-08-28 22:32:50 +00:00
var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2021-09-03 18:35:52 +00:00
if (string.Equals(root?.Message, "OK", StringComparison.Ordinal))
2015-07-23 05:25:55 +00:00
{
2021-08-28 22:32:50 +00:00
_logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token);
return root.Token;
2015-07-23 05:25:55 +00:00
}
throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message);
2015-07-23 05:25:55 +00:00
}
2015-07-23 17:04:54 +00:00
private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
{
2019-10-25 10:47:20 +00:00
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2015-07-23 17:04:54 +00:00
ArgumentException.ThrowIfNullOrEmpty(token);
ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
2015-07-24 21:44:25 +00:00
_logger.LogInformation("Adding new LineUp ");
2015-07-23 17:04:54 +00:00
using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
options.Headers.TryAddWithoutValidation("token", token);
2020-09-03 13:30:34 +00:00
using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
2015-07-23 17:04:54 +00:00
}
2015-07-23 23:40:54 +00:00
private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
2015-07-24 21:44:25 +00:00
2019-10-25 10:47:20 +00:00
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2015-07-23 23:40:54 +00:00
ArgumentException.ThrowIfNullOrEmpty(token);
2015-07-26 21:02:23 +00:00
_logger.LogInformation("Headends on account ");
2015-07-23 23:40:54 +00:00
using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
options.Headers.TryAddWithoutValidation("token", token);
2015-07-23 23:40:54 +00:00
2015-08-21 05:00:56 +00:00
try
{
using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
2020-12-08 15:28:19 +00:00
httpResponse.EnsureSuccessStatusCode();
2020-11-17 18:43:00 +00:00
await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var response = httpResponse.Content;
2021-08-28 22:32:50 +00:00
var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2015-08-21 05:00:56 +00:00
2021-09-03 18:35:52 +00:00
return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false;
2015-08-21 05:00:56 +00:00
}
2020-11-14 21:30:34 +00:00
catch (HttpRequestException ex)
2015-07-23 23:40:54 +00:00
{
2020-12-08 15:28:19 +00:00
// SchedulesDirect returns 400 if no lineups are configured.
2021-09-03 18:35:52 +00:00
if (ex.StatusCode is HttpStatusCode.BadRequest)
2015-08-21 05:00:56 +00:00
{
return false;
}
2015-07-23 23:40:54 +00:00
2015-08-21 05:00:56 +00:00
throw;
2015-07-23 23:40:54 +00:00
}
}
2015-07-25 17:21:10 +00:00
public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
2015-07-23 23:40:54 +00:00
{
2015-07-25 17:21:10 +00:00
if (validateLogin)
2015-07-24 21:44:25 +00:00
{
ArgumentException.ThrowIfNullOrEmpty(info.Username);
ArgumentException.ThrowIfNullOrEmpty(info.Password);
2015-07-24 21:44:25 +00:00
}
2020-06-15 21:43:52 +00:00
2015-07-25 17:21:10 +00:00
if (validateListings)
{
ArgumentException.ThrowIfNullOrEmpty(info.ListingsId);
2015-07-24 21:44:25 +00:00
2015-07-25 17:21:10 +00:00
var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
2015-07-23 23:40:54 +00:00
2015-07-25 17:21:10 +00:00
if (!hasLineup)
{
await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
}
2015-07-23 23:40:54 +00:00
}
}
public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
{
return GetHeadends(info, country, location, CancellationToken.None);
}
2016-06-08 05:24:25 +00:00
public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
{
2016-06-08 21:04:52 +00:00
var listingsId = info.ListingsId;
ArgumentException.ThrowIfNullOrEmpty(listingsId);
2016-06-08 21:04:52 +00:00
2019-10-25 10:47:20 +00:00
var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
2016-06-08 21:04:52 +00:00
ArgumentException.ThrowIfNullOrEmpty(token);
2016-06-08 21:04:52 +00:00
using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
options.Headers.TryAddWithoutValidation("token", token);
2016-06-08 21:04:52 +00:00
using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
2020-11-17 18:43:00 +00:00
await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
2021-08-28 22:32:50 +00:00
var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2022-12-05 14:00:20 +00:00
if (root is null)
2021-09-03 19:36:07 +00:00
{
return new List<ChannelInfo>();
}
_logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count);
_logger.LogInformation("Mapping Stations to Channel");
2017-02-04 23:32:16 +00:00
2021-09-03 18:35:52 +00:00
var allStations = root.Stations;
2017-02-04 23:32:16 +00:00
2021-08-28 22:32:50 +00:00
var map = root.Map;
var list = new List<ChannelInfo>(map.Count);
foreach (var channel in map)
{
var channelNumber = GetChannelNumber(channel);
2017-10-20 16:16:56 +00:00
2021-09-06 17:08:40 +00:00
var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase));
var station = stationIndex == -1
? new StationDto { StationId = channel.StationId }
: allStations[stationIndex];
2017-02-04 23:32:16 +00:00
2020-09-01 13:58:05 +00:00
var channelInfo = new ChannelInfo
{
2021-08-28 22:32:50 +00:00
Id = station.StationId,
CallSign = station.Callsign,
2020-09-01 13:58:05 +00:00
Number = channelNumber,
2021-08-28 22:32:50 +00:00
Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name
2020-09-01 13:58:05 +00:00
};
2022-12-05 14:01:13 +00:00
if (station.Logo is not null)
{
2021-08-28 22:32:50 +00:00
channelInfo.ImageUrl = station.Logo.Url;
2016-06-08 21:04:52 +00:00
}
list.Add(channelInfo);
2017-02-04 23:32:16 +00:00
}
return list;
2017-02-04 23:32:16 +00:00
}
2022-02-15 17:59:46 +00:00
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and optionally managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_tokenSemaphore?.Dispose();
}
_disposed = true;
}
2015-07-21 04:22:46 +00:00
}
2018-12-30 17:30:29 +00:00
}