| | | 1 | | #nullable disable |
| | | 2 | | |
| | | 3 | | #pragma warning disable CS1591 |
| | | 4 | | |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Concurrent; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Globalization; |
| | | 9 | | using System.IO; |
| | | 10 | | using System.Linq; |
| | | 11 | | using System.Net; |
| | | 12 | | using System.Net.Http; |
| | | 13 | | using System.Net.Http.Json; |
| | | 14 | | using System.Net.Mime; |
| | | 15 | | using System.Security.Cryptography; |
| | | 16 | | using System.Text; |
| | | 17 | | using System.Text.Json; |
| | | 18 | | using System.Threading; |
| | | 19 | | using System.Threading.Tasks; |
| | | 20 | | using AsyncKeyedLock; |
| | | 21 | | using Jellyfin.Extensions; |
| | | 22 | | using Jellyfin.Extensions.Json; |
| | | 23 | | using Jellyfin.LiveTv.Guide; |
| | | 24 | | using Jellyfin.LiveTv.Listings.SchedulesDirectDtos; |
| | | 25 | | using MediaBrowser.Common.Configuration; |
| | | 26 | | using MediaBrowser.Common.Net; |
| | | 27 | | using MediaBrowser.Controller.Authentication; |
| | | 28 | | using MediaBrowser.Controller.LiveTv; |
| | | 29 | | using MediaBrowser.Model.Dto; |
| | | 30 | | using MediaBrowser.Model.Entities; |
| | | 31 | | using MediaBrowser.Model.LiveTv; |
| | | 32 | | using Microsoft.Extensions.Logging; |
| | | 33 | | |
| | | 34 | | namespace Jellyfin.LiveTv.Listings |
| | | 35 | | { |
| | | 36 | | public class SchedulesDirect : IListingsProvider, ISchedulesDirectService, IDisposable |
| | | 37 | | { |
| | | 38 | | private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; |
| | | 39 | | private const int CountryCacheDays = 7; |
| | | 40 | | |
| | | 41 | | private readonly ILogger<SchedulesDirect> _logger; |
| | | 42 | | private readonly IHttpClientFactory _httpClientFactory; |
| | | 43 | | private readonly IApplicationPaths _appPaths; |
| | 21 | 44 | | private readonly AsyncNonKeyedLocker _tokenLock = new(1); |
| | | 45 | | |
| | 21 | 46 | | private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new(); |
| | 21 | 47 | | private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; |
| | | 48 | | private long _lastErrorResponseTicks; |
| | | 49 | | private volatile bool _accountError; |
| | | 50 | | private bool _disposed = false; |
| | | 51 | | |
| | | 52 | | private byte[] _countriesCache; |
| | | 53 | | private DateOnly? _imageLimitHitDate; |
| | | 54 | | private DateOnly? _metadataLimitHitDate; |
| | | 55 | | |
| | | 56 | | public SchedulesDirect( |
| | | 57 | | ILogger<SchedulesDirect> logger, |
| | | 58 | | IHttpClientFactory httpClientFactory, |
| | | 59 | | IApplicationPaths appPaths) |
| | | 60 | | { |
| | 21 | 61 | | _logger = logger; |
| | 21 | 62 | | _httpClientFactory = httpClientFactory; |
| | 21 | 63 | | _appPaths = appPaths; |
| | 21 | 64 | | _imageLimitHitDate = LoadDailyLimitDate(ImageLimitFilePath); |
| | 21 | 65 | | _metadataLimitHitDate = LoadDailyLimitDate(MetadataLimitFilePath); |
| | 21 | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <inheritdoc /> |
| | 0 | 69 | | public string Name => "Schedules Direct"; |
| | | 70 | | |
| | 21 | 71 | | private string ImageLimitFilePath => Path.Combine(_appPaths.CachePath, "sd-image-limit.txt"); |
| | | 72 | | |
| | 21 | 73 | | private string MetadataLimitFilePath => Path.Combine(_appPaths.CachePath, "sd-metadata-limit.txt"); |
| | | 74 | | |
| | | 75 | | /// <inheritdoc /> |
| | 0 | 76 | | public string Type => nameof(SchedulesDirect); |
| | | 77 | | |
| | | 78 | | private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc) |
| | | 79 | | { |
| | 0 | 80 | | var dates = new List<string>(); |
| | | 81 | | |
| | 0 | 82 | | var start = new[] { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date; |
| | 0 | 83 | | var end = new[] { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date; |
| | | 84 | | |
| | 0 | 85 | | while (start <= end) |
| | | 86 | | { |
| | 0 | 87 | | dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); |
| | 0 | 88 | | start = start.AddDays(1); |
| | | 89 | | } |
| | | 90 | | |
| | 0 | 91 | | return dates; |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTi |
| | | 95 | | { |
| | 0 | 96 | | if (IsMetadataLimitActive()) |
| | | 97 | | { |
| | 0 | 98 | | return []; |
| | | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | ArgumentException.ThrowIfNullOrEmpty(channelId); |
| | | 102 | | |
| | | 103 | | // Normalize incoming input |
| | 0 | 104 | | channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase) |
| | | 105 | | |
| | 0 | 106 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 107 | | |
| | 0 | 108 | | if (string.IsNullOrEmpty(token)) |
| | | 109 | | { |
| | 0 | 110 | | _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); |
| | | 111 | | |
| | 0 | 112 | | return []; |
| | | 113 | | } |
| | | 114 | | |
| | 0 | 115 | | var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); |
| | | 116 | | |
| | 0 | 117 | | _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId); |
| | 0 | 118 | | var requestList = new List<RequestScheduleForChannelDto>() |
| | 0 | 119 | | { |
| | 0 | 120 | | new() |
| | 0 | 121 | | { |
| | 0 | 122 | | StationId = channelId, |
| | 0 | 123 | | Date = dates |
| | 0 | 124 | | } |
| | 0 | 125 | | }; |
| | | 126 | | |
| | 0 | 127 | | _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList); |
| | | 128 | | |
| | 0 | 129 | | using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); |
| | 0 | 130 | | options.Content = JsonContent.Create(requestList, options: _jsonOptions); |
| | 0 | 131 | | options.Headers.TryAddWithoutValidation("token", token); |
| | 0 | 132 | | var dailySchedules = await Request<IReadOnlyList<DayDto>>(options, true, info, cancellationToken).ConfigureA |
| | 0 | 133 | | if (dailySchedules is null) |
| | | 134 | | { |
| | 0 | 135 | | return []; |
| | | 136 | | } |
| | | 137 | | |
| | 0 | 138 | | _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, chann |
| | | 139 | | |
| | 0 | 140 | | using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); |
| | 0 | 141 | | programRequestOptions.Headers.TryAddWithoutValidation("token", token); |
| | | 142 | | |
| | 0 | 143 | | var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct(); |
| | 0 | 144 | | programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions); |
| | | 145 | | |
| | 0 | 146 | | var programDetails = await Request<IReadOnlyList<ProgramDetailsDto>>(programRequestOptions, true, info, canc |
| | 0 | 147 | | if (programDetails is null) |
| | | 148 | | { |
| | 0 | 149 | | return []; |
| | | 150 | | } |
| | | 151 | | |
| | 0 | 152 | | var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y); |
| | | 153 | | |
| | 0 | 154 | | var programIdsWithImages = programDetails |
| | 0 | 155 | | .Where(p => p.HasImageArtwork) |
| | 0 | 156 | | .Select(p => p.ProgramId) |
| | 0 | 157 | | .ToList(); |
| | | 158 | | |
| | 0 | 159 | | var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); |
| | | 160 | | |
| | 0 | 161 | | var programsInfo = new List<ProgramInfo>(); |
| | 0 | 162 | | foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs)) |
| | | 163 | | { |
| | 0 | 164 | | if (string.IsNullOrEmpty(schedule.ProgramId)) |
| | | 165 | | { |
| | | 166 | | continue; |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | // Only add images which will be pre-cached until we can implement dynamic token fetching |
| | 0 | 170 | | var endDate = schedule.AirDateTime?.AddSeconds(schedule.Duration); |
| | 0 | 171 | | var willBeCached = endDate.HasValue && endDate.Value < DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays |
| | 0 | 172 | | if (willBeCached && images is not null) |
| | | 173 | | { |
| | 0 | 174 | | var imageIndex = images.FindIndex(i => |
| | 0 | 175 | | i.ProgramId is not null && schedule.ProgramId.StartsWith(i.ProgramId, StringComparison.Ordinal)) |
| | 0 | 176 | | if (imageIndex > -1) |
| | | 177 | | { |
| | 0 | 178 | | var programEntry = programDict[schedule.ProgramId]; |
| | | 179 | | |
| | 0 | 180 | | var allImages = images[imageIndex].Data; |
| | 0 | 181 | | var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalI |
| | 0 | 182 | | var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.Ordina |
| | | 183 | | |
| | | 184 | | const double DesiredAspect = 2.0 / 3; |
| | | 185 | | |
| | 0 | 186 | | programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ?? |
| | 0 | 187 | | GetProgramImage(ApiUrl, allImages, DesiredAspect, token); |
| | | 188 | | |
| | | 189 | | const double WideAspect = 16.0 / 9; |
| | | 190 | | |
| | 0 | 191 | | programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token); |
| | | 192 | | |
| | | 193 | | // Don't supply the same image twice |
| | 0 | 194 | | if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal)) |
| | | 195 | | { |
| | 0 | 196 | | programEntry.ThumbImage = null; |
| | | 197 | | } |
| | | 198 | | |
| | 0 | 199 | | programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token); |
| | | 200 | | |
| | | 201 | | // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ?? |
| | | 202 | | // GetProgramImage(ApiUrl, data, "Banner-L1", false) ?? |
| | | 203 | | // GetProgramImage(ApiUrl, data, "Banner-LO", false) ?? |
| | | 204 | | // GetProgramImage(ApiUrl, data, "Banner-LOT", false); |
| | | 205 | | } |
| | | 206 | | } |
| | | 207 | | |
| | 0 | 208 | | programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId])); |
| | | 209 | | } |
| | | 210 | | |
| | 0 | 211 | | return programsInfo; |
| | 0 | 212 | | } |
| | | 213 | | |
| | | 214 | | private static int GetSizeOrder(ImageDataDto image) |
| | | 215 | | { |
| | 0 | 216 | | if (int.TryParse(image.Height, out int value)) |
| | | 217 | | { |
| | 0 | 218 | | return value; |
| | | 219 | | } |
| | | 220 | | |
| | 0 | 221 | | return 0; |
| | | 222 | | } |
| | | 223 | | |
| | | 224 | | private static string GetChannelNumber(MapDto map) |
| | | 225 | | { |
| | 0 | 226 | | var channelNumber = map.LogicalChannelNumber; |
| | | 227 | | |
| | 0 | 228 | | if (string.IsNullOrWhiteSpace(channelNumber)) |
| | | 229 | | { |
| | 0 | 230 | | channelNumber = map.Channel; |
| | | 231 | | } |
| | | 232 | | |
| | 0 | 233 | | if (string.IsNullOrWhiteSpace(channelNumber)) |
| | | 234 | | { |
| | 0 | 235 | | channelNumber = map.AtscMajor + "." + map.AtscMinor; |
| | | 236 | | } |
| | | 237 | | |
| | 0 | 238 | | return channelNumber.TrimStart('0'); |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | private static bool IsMovie(ProgramDetailsDto programInfo) |
| | | 242 | | { |
| | 0 | 243 | | return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase); |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details) |
| | | 247 | | { |
| | 0 | 248 | | if (programInfo.AirDateTime is null) |
| | | 249 | | { |
| | 0 | 250 | | return null; |
| | | 251 | | } |
| | | 252 | | |
| | 0 | 253 | | var startAt = programInfo.AirDateTime.Value; |
| | 0 | 254 | | var endAt = startAt.AddSeconds(programInfo.Duration); |
| | 0 | 255 | | var audioType = ProgramAudio.Stereo; |
| | | 256 | | |
| | 0 | 257 | | var programId = programInfo.ProgramId ?? string.Empty; |
| | | 258 | | |
| | 0 | 259 | | string newID = programId + "T" + startAt.Ticks + "C" + channelId; |
| | | 260 | | |
| | 0 | 261 | | if (programInfo.AudioProperties.Count != 0) |
| | | 262 | | { |
| | 0 | 263 | | if (programInfo.AudioProperties.Contains("atmos", StringComparison.OrdinalIgnoreCase)) |
| | | 264 | | { |
| | 0 | 265 | | audioType = ProgramAudio.Atmos; |
| | | 266 | | } |
| | 0 | 267 | | else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparison.OrdinalIgnoreCase)) |
| | | 268 | | { |
| | 0 | 269 | | audioType = ProgramAudio.DolbyDigital; |
| | | 270 | | } |
| | 0 | 271 | | else if (programInfo.AudioProperties.Contains("dd", StringComparison.OrdinalIgnoreCase)) |
| | | 272 | | { |
| | 0 | 273 | | audioType = ProgramAudio.DolbyDigital; |
| | | 274 | | } |
| | 0 | 275 | | else if (programInfo.AudioProperties.Contains("stereo", StringComparison.OrdinalIgnoreCase)) |
| | | 276 | | { |
| | 0 | 277 | | audioType = ProgramAudio.Stereo; |
| | | 278 | | } |
| | | 279 | | else |
| | | 280 | | { |
| | 0 | 281 | | audioType = ProgramAudio.Mono; |
| | | 282 | | } |
| | | 283 | | } |
| | | 284 | | |
| | 0 | 285 | | string episodeTitle = null; |
| | 0 | 286 | | if (details.EpisodeTitle150 is not null) |
| | | 287 | | { |
| | 0 | 288 | | episodeTitle = details.EpisodeTitle150; |
| | | 289 | | } |
| | | 290 | | |
| | 0 | 291 | | var info = new ProgramInfo |
| | 0 | 292 | | { |
| | 0 | 293 | | ChannelId = channelId, |
| | 0 | 294 | | Id = newID, |
| | 0 | 295 | | StartDate = startAt, |
| | 0 | 296 | | EndDate = endAt, |
| | 0 | 297 | | Name = details.Titles[0].Title120 ?? "Unknown", |
| | 0 | 298 | | OfficialRating = null, |
| | 0 | 299 | | CommunityRating = null, |
| | 0 | 300 | | EpisodeTitle = episodeTitle, |
| | 0 | 301 | | Audio = audioType, |
| | 0 | 302 | | // IsNew = programInfo.@new ?? false, |
| | 0 | 303 | | IsRepeat = programInfo.New is null, |
| | 0 | 304 | | IsSeries = string.Equals(details.EntityType, "episode", StringComparison.OrdinalIgnoreCase), |
| | 0 | 305 | | ImageUrl = details.PrimaryImage, |
| | 0 | 306 | | ThumbImageUrl = details.ThumbImage, |
| | 0 | 307 | | IsKids = string.Equals(details.Audience, "children", StringComparison.OrdinalIgnoreCase), |
| | 0 | 308 | | IsSports = string.Equals(details.EntityType, "sports", StringComparison.OrdinalIgnoreCase), |
| | 0 | 309 | | IsMovie = IsMovie(details), |
| | 0 | 310 | | Etag = programInfo.Md5, |
| | 0 | 311 | | IsLive = string.Equals(programInfo.LiveTapeDelay, "live", StringComparison.OrdinalIgnoreCase), |
| | 0 | 312 | | IsPremiere = programInfo.Premiere || (programInfo.IsPremiereOrFinale ?? string.Empty).Contains("premiere |
| | 0 | 313 | | }; |
| | | 314 | | |
| | 0 | 315 | | var showId = programId; |
| | | 316 | | |
| | 0 | 317 | | if (!info.IsSeries) |
| | | 318 | | { |
| | | 319 | | // It's also a series if it starts with SH |
| | 0 | 320 | | info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14; |
| | | 321 | | } |
| | | 322 | | |
| | | 323 | | // According to SchedulesDirect, these are generic, unidentified episodes |
| | | 324 | | // SH005316560000 |
| | 0 | 325 | | var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) || |
| | 0 | 326 | | !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase); |
| | | 327 | | |
| | 0 | 328 | | if (!hasUniqueShowId) |
| | | 329 | | { |
| | 0 | 330 | | showId = newID; |
| | | 331 | | } |
| | | 332 | | |
| | 0 | 333 | | info.ShowId = showId; |
| | | 334 | | |
| | 0 | 335 | | if (programInfo.VideoProperties is not null) |
| | | 336 | | { |
| | 0 | 337 | | info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase); |
| | 0 | 338 | | info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase); |
| | | 339 | | } |
| | | 340 | | |
| | 0 | 341 | | if (details.ContentRating is not null && details.ContentRating.Count > 0) |
| | | 342 | | { |
| | 0 | 343 | | info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal) |
| | 0 | 344 | | .Replace("--", "-", StringComparison.Ordinal); |
| | | 345 | | |
| | 0 | 346 | | var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" }; |
| | 0 | 347 | | if (invalid.Contains(info.OfficialRating, StringComparison.OrdinalIgnoreCase)) |
| | | 348 | | { |
| | 0 | 349 | | info.OfficialRating = null; |
| | | 350 | | } |
| | | 351 | | } |
| | | 352 | | |
| | 0 | 353 | | if (details.Descriptions is not null) |
| | | 354 | | { |
| | 0 | 355 | | if (details.Descriptions.Description1000 is not null && details.Descriptions.Description1000.Count > 0) |
| | | 356 | | { |
| | 0 | 357 | | info.Overview = details.Descriptions.Description1000[0].Description; |
| | | 358 | | } |
| | 0 | 359 | | else if (details.Descriptions.Description100 is not null && details.Descriptions.Description100.Count > |
| | | 360 | | { |
| | 0 | 361 | | info.Overview = details.Descriptions.Description100[0].Description; |
| | | 362 | | } |
| | | 363 | | } |
| | | 364 | | |
| | 0 | 365 | | if (info.IsSeries) |
| | | 366 | | { |
| | 0 | 367 | | info.SeriesId = programId.Substring(0, 10); |
| | | 368 | | |
| | 0 | 369 | | info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId; |
| | | 370 | | |
| | 0 | 371 | | if (details.Metadata is not null) |
| | | 372 | | { |
| | 0 | 373 | | foreach (var metadataProgram in details.Metadata) |
| | | 374 | | { |
| | 0 | 375 | | var gracenote = metadataProgram.Gracenote; |
| | 0 | 376 | | if (gracenote is not null) |
| | | 377 | | { |
| | 0 | 378 | | info.SeasonNumber = gracenote.Season; |
| | | 379 | | |
| | 0 | 380 | | if (gracenote.Episode > 0) |
| | | 381 | | { |
| | 0 | 382 | | info.EpisodeNumber = gracenote.Episode; |
| | | 383 | | } |
| | | 384 | | |
| | 0 | 385 | | break; |
| | | 386 | | } |
| | | 387 | | } |
| | | 388 | | } |
| | | 389 | | } |
| | | 390 | | |
| | 0 | 391 | | if (details.OriginalAirDate is not null) |
| | | 392 | | { |
| | 0 | 393 | | info.OriginalAirDate = details.OriginalAirDate; |
| | 0 | 394 | | info.ProductionYear = info.OriginalAirDate.Value.Year; |
| | | 395 | | } |
| | | 396 | | |
| | 0 | 397 | | if (details.Movie is not null) |
| | | 398 | | { |
| | 0 | 399 | | if (!string.IsNullOrEmpty(details.Movie.Year) |
| | 0 | 400 | | && int.TryParse(details.Movie.Year, out int year)) |
| | | 401 | | { |
| | 0 | 402 | | info.ProductionYear = year; |
| | | 403 | | } |
| | | 404 | | } |
| | | 405 | | |
| | 0 | 406 | | if (details.Genres is not null) |
| | | 407 | | { |
| | 0 | 408 | | info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList(); |
| | 0 | 409 | | info.IsNews = details.Genres.Contains("news", StringComparison.OrdinalIgnoreCase); |
| | | 410 | | |
| | 0 | 411 | | if (info.Genres.Contains("children", StringComparison.OrdinalIgnoreCase)) |
| | | 412 | | { |
| | 0 | 413 | | info.IsKids = true; |
| | | 414 | | } |
| | | 415 | | } |
| | | 416 | | |
| | 0 | 417 | | return info; |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, str |
| | | 421 | | { |
| | 0 | 422 | | var match = images |
| | 0 | 423 | | .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) |
| | 0 | 424 | | .ThenByDescending(i => GetSizeOrder(i)) |
| | 0 | 425 | | .FirstOrDefault(); |
| | | 426 | | |
| | 0 | 427 | | if (match is null) |
| | | 428 | | { |
| | 0 | 429 | | return null; |
| | | 430 | | } |
| | | 431 | | |
| | 0 | 432 | | var uri = match.Uri; |
| | | 433 | | |
| | 0 | 434 | | if (string.IsNullOrWhiteSpace(uri)) |
| | | 435 | | { |
| | 0 | 436 | | return null; |
| | | 437 | | } |
| | | 438 | | |
| | 0 | 439 | | if (uri.Contains("http", StringComparison.OrdinalIgnoreCase)) |
| | | 440 | | { |
| | 0 | 441 | | return uri; |
| | | 442 | | } |
| | | 443 | | |
| | 0 | 444 | | return apiUrl + "/image/" + uri + "?token=" + token; |
| | | 445 | | } |
| | | 446 | | |
| | | 447 | | private static double GetAspectRatio(ImageDataDto i) |
| | | 448 | | { |
| | 0 | 449 | | int width = 0; |
| | 0 | 450 | | int height = 0; |
| | | 451 | | |
| | 0 | 452 | | if (!string.IsNullOrWhiteSpace(i.Width)) |
| | | 453 | | { |
| | 0 | 454 | | _ = int.TryParse(i.Width, out width); |
| | | 455 | | } |
| | | 456 | | |
| | 0 | 457 | | if (!string.IsNullOrWhiteSpace(i.Height)) |
| | | 458 | | { |
| | 0 | 459 | | _ = int.TryParse(i.Height, out height); |
| | | 460 | | } |
| | | 461 | | |
| | 0 | 462 | | if (height == 0 || width == 0) |
| | | 463 | | { |
| | 0 | 464 | | return 0; |
| | | 465 | | } |
| | | 466 | | |
| | 0 | 467 | | double result = width; |
| | 0 | 468 | | result /= height; |
| | 0 | 469 | | return result; |
| | | 470 | | } |
| | | 471 | | |
| | | 472 | | private async Task<IReadOnlyList<ShowImagesDto>> GetImageForPrograms( |
| | | 473 | | ListingsProviderInfo info, |
| | | 474 | | IReadOnlyList<string> programIds, |
| | | 475 | | CancellationToken cancellationToken) |
| | | 476 | | { |
| | 0 | 477 | | if (IsImageDailyLimitActive()) |
| | | 478 | | { |
| | 0 | 479 | | return []; |
| | | 480 | | } |
| | | 481 | | |
| | 0 | 482 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 483 | | |
| | 0 | 484 | | if (string.IsNullOrEmpty(token) || programIds.Count == 0) |
| | | 485 | | { |
| | 0 | 486 | | return []; |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | // SD API accepts max 500 program IDs per request |
| | | 490 | | const int BatchSize = 500; |
| | 0 | 491 | | var results = new List<ShowImagesDto>(); |
| | 0 | 492 | | for (int i = 0; i < programIds.Count; i += BatchSize) |
| | | 493 | | { |
| | 0 | 494 | | var batch = programIds.Skip(i).Take(BatchSize); |
| | | 495 | | |
| | 0 | 496 | | using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs/"); |
| | 0 | 497 | | message.Headers.TryAddWithoutValidation("token", token); |
| | 0 | 498 | | message.Content = JsonContent.Create(batch, options: _jsonOptions); |
| | | 499 | | |
| | | 500 | | try |
| | | 501 | | { |
| | 0 | 502 | | var batchResult = await Request<IReadOnlyList<ShowImagesDto>>(message, true, info, cancellationToken |
| | 0 | 503 | | if (batchResult is not null) |
| | | 504 | | { |
| | 0 | 505 | | foreach (var entry in batchResult) |
| | | 506 | | { |
| | 0 | 507 | | if (entry.Code.HasValue) |
| | | 508 | | { |
| | 0 | 509 | | _logger.LogWarning( |
| | 0 | 510 | | "Schedules Direct returned error for program {ProgramId}: code={Code}, message={Mess |
| | 0 | 511 | | entry.ProgramId, |
| | 0 | 512 | | entry.Code, |
| | 0 | 513 | | entry.Message); |
| | 0 | 514 | | continue; |
| | | 515 | | } |
| | | 516 | | |
| | 0 | 517 | | results.Add(entry); |
| | | 518 | | } |
| | | 519 | | } |
| | 0 | 520 | | } |
| | 0 | 521 | | catch (Exception ex) |
| | | 522 | | { |
| | 0 | 523 | | _logger.LogError(ex, "Error getting image info from schedules direct"); |
| | 0 | 524 | | } |
| | 0 | 525 | | } |
| | | 526 | | |
| | 0 | 527 | | return results; |
| | 0 | 528 | | } |
| | | 529 | | |
| | | 530 | | public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, Canc |
| | | 531 | | { |
| | 0 | 532 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 533 | | |
| | 0 | 534 | | var lineups = new List<NameIdPair>(); |
| | | 535 | | |
| | 0 | 536 | | if (string.IsNullOrWhiteSpace(token)) |
| | | 537 | | { |
| | 0 | 538 | | return lineups; |
| | | 539 | | } |
| | | 540 | | |
| | 0 | 541 | | using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&posta |
| | 0 | 542 | | options.Headers.TryAddWithoutValidation("token", token); |
| | | 543 | | |
| | | 544 | | try |
| | | 545 | | { |
| | 0 | 546 | | var root = await Request<IReadOnlyList<HeadendsDto>>(options, false, info, cancellationToken).ConfigureA |
| | 0 | 547 | | if (root is not null) |
| | | 548 | | { |
| | 0 | 549 | | foreach (HeadendsDto headend in root) |
| | | 550 | | { |
| | 0 | 551 | | foreach (LineupDto lineup in headend.Lineups) |
| | | 552 | | { |
| | 0 | 553 | | lineups.Add(new NameIdPair |
| | 0 | 554 | | { |
| | 0 | 555 | | Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name, |
| | 0 | 556 | | Id = lineup.Uri?[18..] |
| | 0 | 557 | | }); |
| | | 558 | | } |
| | | 559 | | } |
| | | 560 | | } |
| | | 561 | | else |
| | | 562 | | { |
| | 0 | 563 | | _logger.LogInformation("No lineups available"); |
| | | 564 | | } |
| | 0 | 565 | | } |
| | 0 | 566 | | catch (Exception ex) |
| | | 567 | | { |
| | 0 | 568 | | _logger.LogError(ex, "Error getting headends"); |
| | 0 | 569 | | } |
| | | 570 | | |
| | 0 | 571 | | return lineups; |
| | 0 | 572 | | } |
| | | 573 | | |
| | | 574 | | private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 575 | | { |
| | 0 | 576 | | var username = info.Username; |
| | | 577 | | |
| | | 578 | | // Reset the token if there's no username |
| | 0 | 579 | | if (string.IsNullOrWhiteSpace(username)) |
| | | 580 | | { |
| | 0 | 581 | | return null; |
| | | 582 | | } |
| | | 583 | | |
| | 0 | 584 | | var password = info.Password; |
| | 0 | 585 | | if (string.IsNullOrEmpty(password)) |
| | | 586 | | { |
| | 0 | 587 | | return null; |
| | | 588 | | } |
| | | 589 | | |
| | | 590 | | // Permanent account error — SD is disabled for this server lifetime. |
| | 0 | 591 | | if (_accountError) |
| | | 592 | | { |
| | 0 | 593 | | return null; |
| | | 594 | | } |
| | | 595 | | |
| | | 596 | | // Avoid hammering SD after transient login failures (e.g. max attempts / temporary lockout) |
| | 0 | 597 | | if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalM |
| | | 598 | | { |
| | 0 | 599 | | return null; |
| | | 600 | | } |
| | | 601 | | |
| | 0 | 602 | | if (!_tokens.TryGetValue(username, out NameValuePair savedToken)) |
| | | 603 | | { |
| | 0 | 604 | | savedToken = new NameValuePair(); |
| | 0 | 605 | | _tokens.TryAdd(username, savedToken); |
| | | 606 | | } |
| | | 607 | | |
| | 0 | 608 | | if (!string.IsNullOrEmpty(savedToken.Name) |
| | 0 | 609 | | && long.TryParse(savedToken.Value, CultureInfo.InvariantCulture, out long ticks)) |
| | | 610 | | { |
| | | 611 | | // If it's under 24 hours old we can still use it |
| | 0 | 612 | | if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks) |
| | | 613 | | { |
| | 0 | 614 | | return savedToken.Name; |
| | | 615 | | } |
| | | 616 | | } |
| | | 617 | | |
| | 0 | 618 | | using (await _tokenLock.LockAsync(cancellationToken).ConfigureAwait(false)) |
| | | 619 | | { |
| | | 620 | | try |
| | | 621 | | { |
| | 0 | 622 | | var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false); |
| | 0 | 623 | | savedToken.Name = result; |
| | 0 | 624 | | savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture); |
| | 0 | 625 | | return result; |
| | | 626 | | } |
| | 0 | 627 | | catch (HttpRequestException ex) |
| | | 628 | | { |
| | | 629 | | // For 4xx errors not already handled by Request<T>'s SD code logic |
| | | 630 | | // (e.g. unparseable response from the /token endpoint), apply a |
| | | 631 | | // temporary backoff to avoid hammering SD. |
| | 0 | 632 | | if (!_accountError |
| | 0 | 633 | | && ex.StatusCode.HasValue |
| | 0 | 634 | | && (int)ex.StatusCode.Value >= 400 |
| | 0 | 635 | | && (int)ex.StatusCode.Value < 500) |
| | | 636 | | { |
| | 0 | 637 | | _tokens.Clear(); |
| | 0 | 638 | | Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); |
| | | 639 | | } |
| | | 640 | | |
| | 0 | 641 | | throw; |
| | | 642 | | } |
| | | 643 | | } |
| | 0 | 644 | | } |
| | | 645 | | |
| | | 646 | | private async Task<T> Request<T>( |
| | | 647 | | HttpRequestMessage message, |
| | | 648 | | bool enableRetry, |
| | | 649 | | ListingsProviderInfo providerInfo, |
| | | 650 | | CancellationToken cancellationToken, |
| | | 651 | | HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) |
| | | 652 | | { |
| | 0 | 653 | | using var response = await _httpClientFactory.CreateClient(NamedClient.Default) |
| | 0 | 654 | | .SendAsync(message, completionOption, cancellationToken) |
| | 0 | 655 | | .ConfigureAwait(false); |
| | 0 | 656 | | if (response.IsSuccessStatusCode) |
| | | 657 | | { |
| | 0 | 658 | | return await response.Content.ReadFromJsonAsync<T>(_jsonOptions, cancellationToken).ConfigureAwait(false |
| | | 659 | | } |
| | | 660 | | |
| | 0 | 661 | | var responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| | | 662 | | |
| | | 663 | | // Try to extract the Schedules Direct error code from the response body. |
| | 0 | 664 | | SdErrorCode? sdCode = null; |
| | | 665 | | try |
| | | 666 | | { |
| | 0 | 667 | | using var doc = JsonDocument.Parse(responseBody); |
| | 0 | 668 | | if (doc.RootElement.TryGetProperty("code", out var codeProp) |
| | 0 | 669 | | && codeProp.TryGetInt32(out var parsedCode) |
| | 0 | 670 | | && Enum.IsDefined((SdErrorCode)parsedCode)) |
| | | 671 | | { |
| | 0 | 672 | | sdCode = (SdErrorCode)parsedCode; |
| | | 673 | | } |
| | 0 | 674 | | } |
| | 0 | 675 | | catch (JsonException) |
| | | 676 | | { |
| | | 677 | | // Response body is not valid JSON; sdCode stays null. |
| | 0 | 678 | | } |
| | | 679 | | |
| | 0 | 680 | | _logger.LogError( |
| | 0 | 681 | | "Request to {Url} failed with HTTP {StatusCode}, SD code {SdCode}: {Response}", |
| | 0 | 682 | | message.RequestUri, |
| | 0 | 683 | | (int)response.StatusCode, |
| | 0 | 684 | | sdCode?.ToString() ?? "N/A", |
| | 0 | 685 | | responseBody); |
| | | 686 | | |
| | 0 | 687 | | if (sdCode is SdErrorCode.InvalidUser or SdErrorCode.InvalidHash or SdErrorCode.AccountLocked or SdErrorCode |
| | | 688 | | { |
| | | 689 | | // Permanent account errors — disable SD for this server lifetime. |
| | 0 | 690 | | _logger.LogError("Schedules Direct account error (code {SdCode}). Disabling SD until server restart", sd |
| | 0 | 691 | | _tokens.Clear(); |
| | 0 | 692 | | _accountError = true; |
| | | 693 | | } |
| | 0 | 694 | | else if (sdCode is SdErrorCode.MaxLoginAttempts or SdErrorCode.TemporaryLockout) |
| | | 695 | | { |
| | | 696 | | // Transient login errors — back off for 30 minutes, then allow retry. |
| | 0 | 697 | | _tokens.Clear(); |
| | 0 | 698 | | Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); |
| | | 699 | | } |
| | 0 | 700 | | else if (sdCode is SdErrorCode.MaxImageDownloads) |
| | | 701 | | { |
| | | 702 | | // Max image downloads — stop image requests until SD resets at 00:00 UTC. |
| | 0 | 703 | | SetImageLimitHit(); |
| | | 704 | | } |
| | 0 | 705 | | else if (sdCode is SdErrorCode.MaxScheduleRequests) |
| | | 706 | | { |
| | | 707 | | // Max schedule/metadata requests — stop metadata requests until SD resets at 00:00 UTC. |
| | 0 | 708 | | SetMetadataLimitHit(); |
| | | 709 | | } |
| | 0 | 710 | | else if (enableRetry |
| | 0 | 711 | | && (int)response.StatusCode < 500 |
| | 0 | 712 | | && (sdCode == SdErrorCode.TokenExpired || (response.StatusCode == HttpStatusCode.Forbidden && sdCode is |
| | | 713 | | { |
| | | 714 | | // Token expired — clear tokens and retry with a fresh token. |
| | | 715 | | // Also retry on 403 with no parseable SD code (legacy/unexpected auth failure). |
| | 0 | 716 | | _tokens.Clear(); |
| | 0 | 717 | | using var retryMessage = new HttpRequestMessage(message.Method, message.RequestUri); |
| | 0 | 718 | | retryMessage.Content = message.Content; |
| | 0 | 719 | | retryMessage.Headers.TryAddWithoutValidation( |
| | 0 | 720 | | "token", |
| | 0 | 721 | | await GetToken(providerInfo, cancellationToken).ConfigureAwait(false)); |
| | | 722 | | |
| | 0 | 723 | | return await Request<T>(retryMessage, false, providerInfo, cancellationToken).ConfigureAwait(false); |
| | | 724 | | } |
| | | 725 | | |
| | 0 | 726 | | throw new HttpRequestException( |
| | 0 | 727 | | string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase), |
| | 0 | 728 | | null, |
| | 0 | 729 | | response.StatusCode); |
| | 0 | 730 | | } |
| | | 731 | | |
| | | 732 | | private async Task<string> GetTokenInternal( |
| | | 733 | | string username, |
| | | 734 | | string password, |
| | | 735 | | CancellationToken cancellationToken) |
| | | 736 | | { |
| | 0 | 737 | | using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); |
| | | 738 | | #pragma warning disable CA5350 // SchedulesDirect is always SHA1. |
| | 0 | 739 | | var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password)); |
| | | 740 | | #pragma warning restore CA5350 |
| | | 741 | | // TODO: remove ToLower when Convert.ToHexString supports lowercase |
| | | 742 | | // Schedules Direct requires the hex to be lowercase |
| | 0 | 743 | | string hashedPassword = Convert.ToHexString(hashedPasswordBytes).ToLowerInvariant(); |
| | 0 | 744 | | options.Content = new StringContent("{\"username\":\"" + username + "\",\"password\":\"" + hashedPassword + |
| | | 745 | | |
| | 0 | 746 | | var root = await Request<TokenDto>(options, false, null, cancellationToken).ConfigureAwait(false); |
| | 0 | 747 | | if (string.Equals(root?.Message, "OK", StringComparison.Ordinal)) |
| | | 748 | | { |
| | 0 | 749 | | _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token); |
| | 0 | 750 | | return root.Token; |
| | | 751 | | } |
| | | 752 | | |
| | 0 | 753 | | throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message); |
| | 0 | 754 | | } |
| | | 755 | | |
| | | 756 | | private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 757 | | { |
| | 0 | 758 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 759 | | |
| | 0 | 760 | | ArgumentException.ThrowIfNullOrEmpty(token); |
| | 0 | 761 | | ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); |
| | | 762 | | |
| | 0 | 763 | | _logger.LogInformation("Adding new lineup {Id}", info.ListingsId); |
| | | 764 | | |
| | 0 | 765 | | using var message = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId); |
| | 0 | 766 | | message.Headers.TryAddWithoutValidation("token", token); |
| | | 767 | | |
| | 0 | 768 | | using var response = await _httpClientFactory.CreateClient(NamedClient.Default) |
| | 0 | 769 | | .SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken) |
| | 0 | 770 | | .ConfigureAwait(false); |
| | | 771 | | |
| | 0 | 772 | | if (!response.IsSuccessStatusCode) |
| | | 773 | | { |
| | 0 | 774 | | _logger.LogError( |
| | 0 | 775 | | "Error adding lineup to account: {Response}", |
| | 0 | 776 | | await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)); |
| | | 777 | | } |
| | 0 | 778 | | } |
| | | 779 | | |
| | | 780 | | private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 781 | | { |
| | 0 | 782 | | ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); |
| | | 783 | | |
| | 0 | 784 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 785 | | |
| | 0 | 786 | | ArgumentException.ThrowIfNullOrEmpty(token); |
| | | 787 | | |
| | 0 | 788 | | _logger.LogInformation("Headends on account "); |
| | | 789 | | |
| | 0 | 790 | | using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups"); |
| | 0 | 791 | | options.Headers.TryAddWithoutValidation("token", token); |
| | | 792 | | |
| | | 793 | | try |
| | | 794 | | { |
| | 0 | 795 | | var root = await Request<LineupsDto>(options, false, null, cancellationToken).ConfigureAwait(false); |
| | 0 | 796 | | return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCas |
| | | 797 | | } |
| | | 798 | | catch (HttpRequestException ex) |
| | | 799 | | { |
| | | 800 | | // SchedulesDirect returns 400 if no lineups are configured. |
| | 0 | 801 | | if (ex.StatusCode is HttpStatusCode.BadRequest) |
| | | 802 | | { |
| | 0 | 803 | | return false; |
| | | 804 | | } |
| | | 805 | | |
| | 0 | 806 | | throw; |
| | | 807 | | } |
| | 0 | 808 | | } |
| | | 809 | | |
| | | 810 | | /// <inheritdoc /> |
| | | 811 | | public async Task<Stream> GetAvailableCountries(CancellationToken cancellationToken) |
| | | 812 | | { |
| | 0 | 813 | | if (_countriesCache is not null) |
| | | 814 | | { |
| | 0 | 815 | | return new MemoryStream(_countriesCache, writable: false); |
| | | 816 | | } |
| | | 817 | | |
| | 0 | 818 | | var cachePath = Path.Combine(_appPaths.CachePath, "sd-countries.json"); |
| | | 819 | | |
| | 0 | 820 | | if (File.Exists(cachePath) |
| | 0 | 821 | | && DateTime.UtcNow - File.GetLastWriteTimeUtc(cachePath) < TimeSpan.FromDays(CountryCacheDays)) |
| | | 822 | | { |
| | | 823 | | try |
| | | 824 | | { |
| | 0 | 825 | | _countriesCache = await File.ReadAllBytesAsync(cachePath, cancellationToken).ConfigureAwait(false); |
| | 0 | 826 | | return new MemoryStream(_countriesCache, writable: false); |
| | | 827 | | } |
| | 0 | 828 | | catch (IOException) |
| | | 829 | | { |
| | | 830 | | // Corrupt or unreadable — delete and re-fetch. |
| | 0 | 831 | | TryDeleteFile(cachePath); |
| | 0 | 832 | | } |
| | | 833 | | } |
| | | 834 | | |
| | 0 | 835 | | var client = _httpClientFactory.CreateClient(NamedClient.Default); |
| | 0 | 836 | | using var response = await client.GetAsync(new Uri(ApiUrl + "/available/countries"), cancellationToken).Conf |
| | 0 | 837 | | response.EnsureSuccessStatusCode(); |
| | | 838 | | |
| | 0 | 839 | | var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 840 | | Directory.CreateDirectory(Path.GetDirectoryName(cachePath)!); |
| | 0 | 841 | | await File.WriteAllBytesAsync(cachePath, bytes, cancellationToken).ConfigureAwait(false); |
| | | 842 | | |
| | 0 | 843 | | _countriesCache = bytes; |
| | 0 | 844 | | return new MemoryStream(bytes, writable: false); |
| | 0 | 845 | | } |
| | | 846 | | |
| | | 847 | | private static DateOnly? LoadDailyLimitDate(string path) |
| | | 848 | | { |
| | 42 | 849 | | if (!File.Exists(path)) |
| | | 850 | | { |
| | 42 | 851 | | return null; |
| | | 852 | | } |
| | | 853 | | |
| | | 854 | | try |
| | | 855 | | { |
| | 0 | 856 | | var text = File.ReadAllText(path).Trim(); |
| | 0 | 857 | | if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var date)) |
| | | 858 | | { |
| | 0 | 859 | | var dateOnly = DateOnly.FromDateTime(date); |
| | 0 | 860 | | if (dateOnly < DateOnly.FromDateTime(DateTime.UtcNow)) |
| | | 861 | | { |
| | | 862 | | // Expired — clean up. |
| | 0 | 863 | | File.Delete(path); |
| | 0 | 864 | | return null; |
| | | 865 | | } |
| | | 866 | | |
| | 0 | 867 | | return dateOnly; |
| | | 868 | | } |
| | 0 | 869 | | } |
| | 0 | 870 | | catch (IOException) |
| | | 871 | | { |
| | | 872 | | // Corrupt or unreadable — delete and reset. |
| | 0 | 873 | | TryDeleteFile(path); |
| | 0 | 874 | | } |
| | | 875 | | |
| | 0 | 876 | | return null; |
| | 0 | 877 | | } |
| | | 878 | | |
| | | 879 | | /// <inheritdoc /> |
| | | 880 | | public bool IsServiceAvailable() |
| | | 881 | | { |
| | 0 | 882 | | if (_accountError) |
| | | 883 | | { |
| | 0 | 884 | | return false; |
| | | 885 | | } |
| | | 886 | | |
| | 0 | 887 | | if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalM |
| | | 888 | | { |
| | 0 | 889 | | return false; |
| | | 890 | | } |
| | | 891 | | |
| | 0 | 892 | | return true; |
| | | 893 | | } |
| | | 894 | | |
| | | 895 | | /// <inheritdoc /> |
| | | 896 | | public bool IsImageDailyLimitActive() |
| | | 897 | | { |
| | 0 | 898 | | if (!_imageLimitHitDate.HasValue) |
| | | 899 | | { |
| | 0 | 900 | | return false; |
| | | 901 | | } |
| | | 902 | | |
| | 0 | 903 | | if (_imageLimitHitDate.Value < DateOnly.FromDateTime(DateTime.UtcNow)) |
| | | 904 | | { |
| | 0 | 905 | | _imageLimitHitDate = null; |
| | 0 | 906 | | TryDeleteFile(ImageLimitFilePath); |
| | 0 | 907 | | return false; |
| | | 908 | | } |
| | | 909 | | |
| | 0 | 910 | | return true; |
| | | 911 | | } |
| | | 912 | | |
| | | 913 | | private bool IsMetadataLimitActive() |
| | | 914 | | { |
| | 0 | 915 | | if (!_metadataLimitHitDate.HasValue) |
| | | 916 | | { |
| | 0 | 917 | | return false; |
| | | 918 | | } |
| | | 919 | | |
| | 0 | 920 | | if (_metadataLimitHitDate.Value < DateOnly.FromDateTime(DateTime.UtcNow)) |
| | | 921 | | { |
| | 0 | 922 | | _metadataLimitHitDate = null; |
| | 0 | 923 | | TryDeleteFile(MetadataLimitFilePath); |
| | 0 | 924 | | return false; |
| | | 925 | | } |
| | | 926 | | |
| | 0 | 927 | | return true; |
| | | 928 | | } |
| | | 929 | | |
| | | 930 | | private void SetImageLimitHit() |
| | | 931 | | { |
| | 0 | 932 | | _imageLimitHitDate = DateOnly.FromDateTime(DateTime.UtcNow); |
| | 0 | 933 | | PersistDailyLimitFile(ImageLimitFilePath); |
| | 0 | 934 | | } |
| | | 935 | | |
| | | 936 | | private void SetMetadataLimitHit() |
| | | 937 | | { |
| | 0 | 938 | | _metadataLimitHitDate = DateOnly.FromDateTime(DateTime.UtcNow); |
| | 0 | 939 | | PersistDailyLimitFile(MetadataLimitFilePath); |
| | 0 | 940 | | } |
| | | 941 | | |
| | | 942 | | private void PersistDailyLimitFile(string filePath) |
| | | 943 | | { |
| | | 944 | | try |
| | | 945 | | { |
| | 0 | 946 | | Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); |
| | 0 | 947 | | File.WriteAllText(filePath, DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)); |
| | 0 | 948 | | } |
| | 0 | 949 | | catch (IOException ex) |
| | | 950 | | { |
| | 0 | 951 | | _logger.LogWarning(ex, "Failed to persist SD daily limit to {Path}", filePath); |
| | 0 | 952 | | } |
| | 0 | 953 | | } |
| | | 954 | | |
| | | 955 | | private static void TryDeleteFile(string path) |
| | | 956 | | { |
| | | 957 | | try |
| | | 958 | | { |
| | 0 | 959 | | File.Delete(path); |
| | 0 | 960 | | } |
| | 0 | 961 | | catch (IOException) |
| | | 962 | | { |
| | | 963 | | // Best effort. |
| | 0 | 964 | | } |
| | 0 | 965 | | } |
| | | 966 | | |
| | | 967 | | public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) |
| | | 968 | | { |
| | 0 | 969 | | if (validateLogin) |
| | | 970 | | { |
| | 0 | 971 | | ArgumentException.ThrowIfNullOrEmpty(info.Username); |
| | 0 | 972 | | ArgumentException.ThrowIfNullOrEmpty(info.Password); |
| | | 973 | | } |
| | | 974 | | |
| | 0 | 975 | | if (validateListings) |
| | | 976 | | { |
| | 0 | 977 | | ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); |
| | | 978 | | |
| | 0 | 979 | | var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false); |
| | | 980 | | |
| | 0 | 981 | | if (!hasLineup) |
| | | 982 | | { |
| | 0 | 983 | | await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false); |
| | | 984 | | } |
| | | 985 | | } |
| | 0 | 986 | | } |
| | | 987 | | |
| | | 988 | | public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location) |
| | | 989 | | { |
| | 0 | 990 | | return GetHeadends(info, country, location, CancellationToken.None); |
| | | 991 | | } |
| | | 992 | | |
| | | 993 | | public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) |
| | | 994 | | { |
| | 0 | 995 | | var listingsId = info.ListingsId; |
| | 0 | 996 | | if (string.IsNullOrEmpty(listingsId)) |
| | | 997 | | { |
| | 0 | 998 | | return []; |
| | | 999 | | } |
| | | 1000 | | |
| | 0 | 1001 | | var token = await GetToken(info, cancellationToken).ConfigureAwait(false); |
| | | 1002 | | |
| | 0 | 1003 | | if (string.IsNullOrEmpty(token)) |
| | | 1004 | | { |
| | 0 | 1005 | | return []; |
| | | 1006 | | } |
| | | 1007 | | |
| | 0 | 1008 | | using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId); |
| | 0 | 1009 | | options.Headers.TryAddWithoutValidation("token", token); |
| | | 1010 | | |
| | 0 | 1011 | | var root = await Request<ChannelDto>(options, true, info, cancellationToken).ConfigureAwait(false); |
| | 0 | 1012 | | if (root is null) |
| | | 1013 | | { |
| | 0 | 1014 | | return new List<ChannelInfo>(); |
| | | 1015 | | } |
| | | 1016 | | |
| | 0 | 1017 | | _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count); |
| | 0 | 1018 | | _logger.LogInformation("Mapping Stations to Channel"); |
| | | 1019 | | |
| | 0 | 1020 | | var allStations = root.Stations; |
| | | 1021 | | |
| | 0 | 1022 | | var map = root.Map; |
| | 0 | 1023 | | var list = new List<ChannelInfo>(map.Count); |
| | 0 | 1024 | | foreach (var channel in map) |
| | | 1025 | | { |
| | 0 | 1026 | | var channelNumber = GetChannelNumber(channel); |
| | | 1027 | | |
| | 0 | 1028 | | var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, String |
| | 0 | 1029 | | var station = stationIndex == -1 |
| | 0 | 1030 | | ? new StationDto { StationId = channel.StationId } |
| | 0 | 1031 | | : allStations[stationIndex]; |
| | | 1032 | | |
| | 0 | 1033 | | var channelInfo = new ChannelInfo |
| | 0 | 1034 | | { |
| | 0 | 1035 | | Id = station.StationId, |
| | 0 | 1036 | | CallSign = station.Callsign, |
| | 0 | 1037 | | Number = channelNumber, |
| | 0 | 1038 | | Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name |
| | 0 | 1039 | | }; |
| | | 1040 | | |
| | 0 | 1041 | | if (station.Logo is not null) |
| | | 1042 | | { |
| | 0 | 1043 | | channelInfo.ImageUrl = station.Logo.Url; |
| | | 1044 | | } |
| | | 1045 | | |
| | 0 | 1046 | | list.Add(channelInfo); |
| | | 1047 | | } |
| | | 1048 | | |
| | 0 | 1049 | | return list; |
| | 0 | 1050 | | } |
| | | 1051 | | |
| | | 1052 | | /// <inheritdoc /> |
| | | 1053 | | public void Dispose() |
| | | 1054 | | { |
| | 63 | 1055 | | Dispose(true); |
| | 63 | 1056 | | GC.SuppressFinalize(this); |
| | 63 | 1057 | | } |
| | | 1058 | | |
| | | 1059 | | /// <summary> |
| | | 1060 | | /// Releases unmanaged and optionally managed resources. |
| | | 1061 | | /// </summary> |
| | | 1062 | | /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release |
| | | 1063 | | protected virtual void Dispose(bool disposing) |
| | | 1064 | | { |
| | 63 | 1065 | | if (_disposed) |
| | | 1066 | | { |
| | 42 | 1067 | | return; |
| | | 1068 | | } |
| | | 1069 | | |
| | 21 | 1070 | | if (disposing) |
| | | 1071 | | { |
| | 21 | 1072 | | _tokenLock?.Dispose(); |
| | | 1073 | | } |
| | | 1074 | | |
| | 21 | 1075 | | _disposed = true; |
| | 21 | 1076 | | } |
| | | 1077 | | } |
| | | 1078 | | } |