#nullable disable #pragma warning disable CS1591 using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; 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; using System.Threading; using System.Threading.Tasks; using AsyncKeyedLock; using Jellyfin.Extensions; using Jellyfin.Extensions.Json; using Jellyfin.LiveTv.Guide; using Jellyfin.LiveTv.Listings.SchedulesDirectDtos; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; using Microsoft.Extensions.Logging; namespace Jellyfin.LiveTv.Listings { public class SchedulesDirect : IListingsProvider, ISchedulesDirectService, IDisposable { private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; private const int CountryCacheDays = 7; private readonly ILogger _logger; private readonly IHttpClientFactory _httpClientFactory; private readonly IApplicationPaths _appPaths; private readonly AsyncNonKeyedLocker _tokenLock = new(1); private readonly ConcurrentDictionary _tokens = new(); private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; private long _lastErrorResponseTicks; private volatile bool _accountError; private bool _disposed = false; private byte[] _countriesCache; private DateOnly? _imageLimitHitDate; private DateOnly? _metadataLimitHitDate; public SchedulesDirect( ILogger logger, IHttpClientFactory httpClientFactory, IApplicationPaths appPaths) { _logger = logger; _httpClientFactory = httpClientFactory; _appPaths = appPaths; _imageLimitHitDate = LoadDailyLimitDate(ImageLimitFilePath); _metadataLimitHitDate = LoadDailyLimitDate(MetadataLimitFilePath); } /// public string Name => "Schedules Direct"; private string ImageLimitFilePath => Path.Combine(_appPaths.CachePath, "sd-image-limit.txt"); private string MetadataLimitFilePath => Path.Combine(_appPaths.CachePath, "sd-metadata-limit.txt"); /// public string Type => nameof(SchedulesDirect); private static List GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc) { var dates = new List(); var start = new[] { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date; var end = new[] { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date; while (start <= end) { dates.Add(start.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)); start = start.AddDays(1); } return dates; } public async Task> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) { if (IsMetadataLimitActive()) { return []; } ArgumentException.ThrowIfNullOrEmpty(channelId); // Normalize incoming input channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I'); var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); return []; } var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId); var requestList = new List() { new() { StationId = channelId, Date = dates } }; _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList); using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); options.Content = JsonContent.Create(requestList, options: _jsonOptions); options.Headers.TryAddWithoutValidation("token", token); var dailySchedules = await Request>(options, true, info, cancellationToken).ConfigureAwait(false); if (dailySchedules is null) { return []; } _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); programRequestOptions.Headers.TryAddWithoutValidation("token", token); var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct(); programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions); var programDetails = await Request>(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false); if (programDetails is null) { return []; } var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y); var programIdsWithImages = programDetails .Where(p => p.HasImageArtwork) .Select(p => p.ProgramId) .ToList(); var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); var programsInfo = new List(); foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs)) { if (string.IsNullOrEmpty(schedule.ProgramId)) { continue; } // Only add images which will be pre-cached until we can implement dynamic token fetching var endDate = schedule.AirDateTime?.AddSeconds(schedule.Duration); var willBeCached = endDate.HasValue && endDate.Value < DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays); if (willBeCached && images is not null) { var imageIndex = images.FindIndex(i => i.ProgramId is not null && schedule.ProgramId.StartsWith(i.ProgramId, StringComparison.Ordinal)); if (imageIndex > -1) { var programEntry = programDict[schedule.ProgramId]; var allImages = images[imageIndex].Data; 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(); const double DesiredAspect = 2.0 / 3; programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ?? GetProgramImage(ApiUrl, allImages, DesiredAspect, token); const double WideAspect = 16.0 / 9; programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token); // Don't supply the same image twice if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal)) { programEntry.ThumbImage = null; } programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token); // 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); } } programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId])); } return programsInfo; } private static int GetSizeOrder(ImageDataDto image) { if (int.TryParse(image.Height, out int value)) { return value; } return 0; } private static string GetChannelNumber(MapDto map) { var channelNumber = map.LogicalChannelNumber; if (string.IsNullOrWhiteSpace(channelNumber)) { channelNumber = map.Channel; } if (string.IsNullOrWhiteSpace(channelNumber)) { channelNumber = map.AtscMajor + "." + map.AtscMinor; } return channelNumber.TrimStart('0'); } private static bool IsMovie(ProgramDetailsDto programInfo) { return string.Equals(programInfo.EntityType, "movie", StringComparison.OrdinalIgnoreCase); } private ProgramInfo GetProgram(string channelId, ProgramDto programInfo, ProgramDetailsDto details) { if (programInfo.AirDateTime is null) { return null; } var startAt = programInfo.AirDateTime.Value; var endAt = startAt.AddSeconds(programInfo.Duration); var audioType = ProgramAudio.Stereo; var programId = programInfo.ProgramId ?? string.Empty; string newID = programId + "T" + startAt.Ticks + "C" + channelId; if (programInfo.AudioProperties.Count != 0) { if (programInfo.AudioProperties.Contains("atmos", StringComparison.OrdinalIgnoreCase)) { audioType = ProgramAudio.Atmos; } else if (programInfo.AudioProperties.Contains("dd 5.1", StringComparison.OrdinalIgnoreCase)) { audioType = ProgramAudio.DolbyDigital; } else if (programInfo.AudioProperties.Contains("dd", StringComparison.OrdinalIgnoreCase)) { audioType = ProgramAudio.DolbyDigital; } else if (programInfo.AudioProperties.Contains("stereo", StringComparison.OrdinalIgnoreCase)) { audioType = ProgramAudio.Stereo; } else { audioType = ProgramAudio.Mono; } } string episodeTitle = null; if (details.EpisodeTitle150 is not null) { episodeTitle = details.EpisodeTitle150; } var info = new ProgramInfo { ChannelId = channelId, Id = newID, StartDate = startAt, EndDate = endAt, Name = details.Titles[0].Title120 ?? "Unknown", OfficialRating = null, CommunityRating = null, EpisodeTitle = episodeTitle, Audio = audioType, // IsNew = programInfo.@new ?? false, IsRepeat = programInfo.New is null, 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), IsMovie = IsMovie(details), Etag = programInfo.Md5, IsLive = string.Equals(programInfo.LiveTapeDelay, "live", StringComparison.OrdinalIgnoreCase), IsPremiere = programInfo.Premiere || (programInfo.IsPremiereOrFinale ?? string.Empty).Contains("premiere", StringComparison.OrdinalIgnoreCase) }; var showId = programId; if (!info.IsSeries) { // It's also a series if it starts with SH info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14; } // 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; if (programInfo.VideoProperties is not null) { info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase); info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase); } if (details.ContentRating is not null && details.ContentRating.Count > 0) { info.OfficialRating = details.ContentRating[0].Code.Replace("TV", "TV-", StringComparison.Ordinal) .Replace("--", "-", StringComparison.Ordinal); var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" }; if (invalid.Contains(info.OfficialRating, StringComparison.OrdinalIgnoreCase)) { info.OfficialRating = null; } } if (details.Descriptions is not null) { if (details.Descriptions.Description1000 is not null && details.Descriptions.Description1000.Count > 0) { info.Overview = details.Descriptions.Description1000[0].Description; } else if (details.Descriptions.Description100 is not null && details.Descriptions.Description100.Count > 0) { info.Overview = details.Descriptions.Description100[0].Description; } } if (info.IsSeries) { info.SeriesId = programId.Substring(0, 10); info.SeriesProviderIds[MetadataProvider.Zap2It.ToString()] = info.SeriesId; if (details.Metadata is not null) { foreach (var metadataProgram in details.Metadata) { var gracenote = metadataProgram.Gracenote; if (gracenote is not null) { info.SeasonNumber = gracenote.Season; if (gracenote.Episode > 0) { info.EpisodeNumber = gracenote.Episode; } break; } } } } if (details.OriginalAirDate is not null) { info.OriginalAirDate = details.OriginalAirDate; info.ProductionYear = info.OriginalAirDate.Value.Year; } if (details.Movie is not null) { if (!string.IsNullOrEmpty(details.Movie.Year) && int.TryParse(details.Movie.Year, out int year)) { info.ProductionYear = year; } } if (details.Genres is not null) { info.Genres = details.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList(); info.IsNews = details.Genres.Contains("news", StringComparison.OrdinalIgnoreCase); if (info.Genres.Contains("children", StringComparison.OrdinalIgnoreCase)) { info.IsKids = true; } } return info; } private static string GetProgramImage(string apiUrl, IEnumerable images, double desiredAspect, string token) { var match = images .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) .ThenByDescending(i => GetSizeOrder(i)) .FirstOrDefault(); if (match is null) { return null; } var uri = match.Uri; if (string.IsNullOrWhiteSpace(uri)) { return null; } if (uri.Contains("http", StringComparison.OrdinalIgnoreCase)) { return uri; } return apiUrl + "/image/" + uri + "?token=" + token; } private static double GetAspectRatio(ImageDataDto i) { int width = 0; int height = 0; if (!string.IsNullOrWhiteSpace(i.Width)) { _ = int.TryParse(i.Width, out width); } if (!string.IsNullOrWhiteSpace(i.Height)) { _ = int.TryParse(i.Height, out height); } if (height == 0 || width == 0) { return 0; } double result = width; result /= height; return result; } private async Task> GetImageForPrograms( ListingsProviderInfo info, IReadOnlyList programIds, CancellationToken cancellationToken) { if (IsImageDailyLimitActive()) { return []; } var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token) || programIds.Count == 0) { return []; } // SD API accepts max 500 program IDs per request const int BatchSize = 500; var results = new List(); for (int i = 0; i < programIds.Count; i += BatchSize) { var batch = programIds.Skip(i).Take(BatchSize); using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs/"); message.Headers.TryAddWithoutValidation("token", token); message.Content = JsonContent.Create(batch, options: _jsonOptions); try { var batchResult = await Request>(message, true, info, cancellationToken).ConfigureAwait(false); if (batchResult is not null) { foreach (var entry in batchResult) { if (entry.Code.HasValue) { _logger.LogWarning( "Schedules Direct returned error for program {ProgramId}: code={Code}, message={Message}", entry.ProgramId, entry.Code, entry.Message); continue; } results.Add(entry); } } } catch (Exception ex) { _logger.LogError(ex, "Error getting image info from schedules direct"); } } return results; } public async Task> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken) { var token = await GetToken(info, cancellationToken).ConfigureAwait(false); var lineups = new List(); if (string.IsNullOrWhiteSpace(token)) { return lineups; } using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location); options.Headers.TryAddWithoutValidation("token", token); try { var root = await Request>(options, false, info, cancellationToken).ConfigureAwait(false); if (root is not null) { foreach (HeadendsDto headend in root) { foreach (LineupDto lineup in headend.Lineups) { lineups.Add(new NameIdPair { Name = string.IsNullOrWhiteSpace(lineup.Name) ? lineup.Lineup : lineup.Name, Id = lineup.Uri?[18..] }); } } } else { _logger.LogInformation("No lineups available"); } } catch (Exception ex) { _logger.LogError(ex, "Error getting headends"); } return lineups; } private async Task GetToken(ListingsProviderInfo info, CancellationToken cancellationToken) { var username = info.Username; // Reset the token if there's no username if (string.IsNullOrWhiteSpace(username)) { return null; } var password = info.Password; if (string.IsNullOrEmpty(password)) { return null; } // Permanent account error — SD is disabled for this server lifetime. if (_accountError) { return null; } // Avoid hammering SD after transient login failures (e.g. max attempts / temporary lockout) if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalMinutes < 30) { return null; } if (!_tokens.TryGetValue(username, out NameValuePair savedToken)) { savedToken = new NameValuePair(); _tokens.TryAdd(username, savedToken); } if (!string.IsNullOrEmpty(savedToken.Name) && long.TryParse(savedToken.Value, CultureInfo.InvariantCulture, out long ticks)) { // If it's under 24 hours old we can still use it if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks) { return savedToken.Name; } } using (await _tokenLock.LockAsync(cancellationToken).ConfigureAwait(false)) { try { var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false); savedToken.Name = result; savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture); return result; } catch (HttpRequestException ex) { // For 4xx errors not already handled by Request's SD code logic // (e.g. unparseable response from the /token endpoint), apply a // temporary backoff to avoid hammering SD. if (!_accountError && ex.StatusCode.HasValue && (int)ex.StatusCode.Value >= 400 && (int)ex.StatusCode.Value < 500) { _tokens.Clear(); Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); } throw; } } } private async Task Request( HttpRequestMessage message, bool enableRetry, ListingsProviderInfo providerInfo, CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .SendAsync(message, completionOption, cancellationToken) .ConfigureAwait(false); if (response.IsSuccessStatusCode) { return await response.Content.ReadFromJsonAsync(_jsonOptions, cancellationToken).ConfigureAwait(false); } var responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); // Try to extract the Schedules Direct error code from the response body. SdErrorCode? sdCode = null; try { using var doc = JsonDocument.Parse(responseBody); if (doc.RootElement.TryGetProperty("code", out var codeProp) && codeProp.TryGetInt32(out var parsedCode) && Enum.IsDefined((SdErrorCode)parsedCode)) { sdCode = (SdErrorCode)parsedCode; } } catch (JsonException) { // Response body is not valid JSON; sdCode stays null. } _logger.LogError( "Request to {Url} failed with HTTP {StatusCode}, SD code {SdCode}: {Response}", message.RequestUri, (int)response.StatusCode, sdCode?.ToString() ?? "N/A", responseBody); if (sdCode is SdErrorCode.AccountExpired or SdErrorCode.InvalidHash or SdErrorCode.InvalidUser or SdErrorCode.AccountLocked or SdErrorCode.AppLocked or SdErrorCode.AccountInactive) { // Permanent account errors — disable SD for this server lifetime. _logger.LogError("Schedules Direct account error (code {SdCode}). Disabling SD until server restart.", sdCode); _tokens.Clear(); _accountError = true; } else if (sdCode is SdErrorCode.ServiceOffline or SdErrorCode.ServiceBusy or SdErrorCode.AccountTempLock) { // Transient login errors — back off for 30 minutes, then allow retry. _logger.LogError("Schedules Direct transient error (code {SdCode}). Backing off for 30 minutes.", sdCode); _tokens.Clear(); Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); } else if (sdCode is SdErrorCode.MaxLoginAttempts or SdErrorCode.MaxIPAttempts) { // 24 hour bans - stop image and metadata requests until SD reset at 00:00 UTC. _logger.LogError("Schedules Direct service limit error (code {SdCode}). Disabling until SD reset.", sdCode); SetImageLimitHit(); SetMetadataLimitHit(); } else if (sdCode is SdErrorCode.MaxImageDownloads or SdErrorCode.MaxImageDownloadsTrial) { // Max image downloads — stop image requests until SD resets at 00:00 UTC. _logger.LogError("Schedules Direct image download limit hit (code {SdCode}). Disabling image acquisition until SD reset.", sdCode); SetImageLimitHit(); } else if (sdCode is SdErrorCode.MaxScheduleRequests) { // Max schedule/metadata requests — stop metadata requests until SD resets at 00:00 UTC. _logger.LogError("Schedules Direct metadata download limit hit (code {SdCode}). Disabling metadata acquisition until SD reset.", sdCode); SetMetadataLimitHit(); } else if (enableRetry && (int)response.StatusCode < 500 && (sdCode == SdErrorCode.TokenExpired || (response.StatusCode == HttpStatusCode.Forbidden && sdCode is null))) { // Token expired — clear tokens and retry with a fresh token. // Also retry on 403 with no parseable SD code (legacy/unexpected auth failure). _tokens.Clear(); using var retryMessage = new HttpRequestMessage(message.Method, message.RequestUri); retryMessage.Content = message.Content; retryMessage.Headers.TryAddWithoutValidation( "token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false)); return await Request(retryMessage, false, providerInfo, cancellationToken).ConfigureAwait(false); } throw new HttpRequestException( string.Format(CultureInfo.InvariantCulture, "Request failed: {0}", response.ReasonPhrase), null, response.StatusCode); } private async Task GetTokenInternal( string username, string password, CancellationToken cancellationToken) { using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token"); #pragma warning disable CA5350 // SchedulesDirect is always SHA1. var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password)); #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); var root = await Request(options, false, null, cancellationToken).ConfigureAwait(false); if (string.Equals(root?.Message, "OK", StringComparison.Ordinal)) { _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token); return root.Token; } throw new AuthenticationException("Could not authenticate with Schedules Direct Error: " + root.Message); } private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken) { var token = await GetToken(info, cancellationToken).ConfigureAwait(false); ArgumentException.ThrowIfNullOrEmpty(token); ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); _logger.LogInformation("Adding new lineup {Id}", info.ListingsId); using var message = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId); message.Headers.TryAddWithoutValidation("token", token); using var response = await _httpClientFactory.CreateClient(NamedClient.Default) .SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken) .ConfigureAwait(false); if (!response.IsSuccessStatusCode) { _logger.LogError( "Error adding lineup to account: {Response}", await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)); } } private async Task HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken) { ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); var token = await GetToken(info, cancellationToken).ConfigureAwait(false); ArgumentException.ThrowIfNullOrEmpty(token); _logger.LogInformation("Headends on account "); using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups"); options.Headers.TryAddWithoutValidation("token", token); try { var root = await Request(options, false, null, cancellationToken).ConfigureAwait(false); return root?.Lineups.Any(i => string.Equals(info.ListingsId, i.Lineup, StringComparison.OrdinalIgnoreCase)) ?? false; } catch (HttpRequestException ex) { // SchedulesDirect returns 400 if no lineups are configured. if (ex.StatusCode is HttpStatusCode.BadRequest) { return false; } throw; } } /// public async Task GetAvailableCountries(CancellationToken cancellationToken) { if (_countriesCache is not null) { return new MemoryStream(_countriesCache, writable: false); } var cachePath = Path.Combine(_appPaths.CachePath, "sd-countries.json"); if (File.Exists(cachePath) && DateTime.UtcNow - File.GetLastWriteTimeUtc(cachePath) < TimeSpan.FromDays(CountryCacheDays)) { try { _countriesCache = await File.ReadAllBytesAsync(cachePath, cancellationToken).ConfigureAwait(false); return new MemoryStream(_countriesCache, writable: false); } catch (IOException) { // Corrupt or unreadable — delete and re-fetch. TryDeleteFile(cachePath); } } var client = _httpClientFactory.CreateClient(NamedClient.Default); using var response = await client.GetAsync(new Uri(ApiUrl + "/available/countries"), cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); Directory.CreateDirectory(Path.GetDirectoryName(cachePath)!); await File.WriteAllBytesAsync(cachePath, bytes, cancellationToken).ConfigureAwait(false); _countriesCache = bytes; return new MemoryStream(bytes, writable: false); } private static DateOnly? LoadDailyLimitDate(string path) { if (!File.Exists(path)) { return null; } try { var text = File.ReadAllText(path).Trim(); if (DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var date)) { var dateOnly = DateOnly.FromDateTime(date); if (dateOnly < DateOnly.FromDateTime(DateTime.UtcNow)) { // Expired — clean up. File.Delete(path); return null; } return dateOnly; } } catch (IOException) { // Corrupt or unreadable — delete and reset. TryDeleteFile(path); } return null; } /// public bool IsServiceAvailable() { if (_accountError) { return false; } if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalMinutes < 30) { return false; } return true; } /// public bool IsImageDailyLimitActive() { if (!_imageLimitHitDate.HasValue) { return false; } if (_imageLimitHitDate.Value < DateOnly.FromDateTime(DateTime.UtcNow)) { _imageLimitHitDate = null; TryDeleteFile(ImageLimitFilePath); return false; } return true; } private bool IsMetadataLimitActive() { if (!_metadataLimitHitDate.HasValue) { return false; } if (_metadataLimitHitDate.Value < DateOnly.FromDateTime(DateTime.UtcNow)) { _metadataLimitHitDate = null; TryDeleteFile(MetadataLimitFilePath); return false; } return true; } private void SetImageLimitHit() { _imageLimitHitDate = DateOnly.FromDateTime(DateTime.UtcNow); PersistDailyLimitFile(ImageLimitFilePath); } private void SetMetadataLimitHit() { _metadataLimitHitDate = DateOnly.FromDateTime(DateTime.UtcNow); PersistDailyLimitFile(MetadataLimitFilePath); } private void PersistDailyLimitFile(string filePath) { try { Directory.CreateDirectory(Path.GetDirectoryName(filePath)!); File.WriteAllText(filePath, DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)); } catch (IOException ex) { _logger.LogWarning(ex, "Failed to persist SD daily limit to {Path}", filePath); } } private static void TryDeleteFile(string path) { try { File.Delete(path); } catch (IOException) { // Best effort. } } public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) { if (validateLogin) { ArgumentException.ThrowIfNullOrEmpty(info.Username); ArgumentException.ThrowIfNullOrEmpty(info.Password); } if (validateListings) { ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false); if (!hasLineup) { await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false); } } } public Task> GetLineups(ListingsProviderInfo info, string country, string location) { return GetHeadends(info, country, location, CancellationToken.None); } public async Task> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) { var listingsId = info.ListingsId; if (string.IsNullOrEmpty(listingsId)) { return []; } var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { return []; } using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId); options.Headers.TryAddWithoutValidation("token", token); var root = await Request(options, true, info, cancellationToken).ConfigureAwait(false); if (root is null) { return new List(); } _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count); _logger.LogInformation("Mapping Stations to Channel"); var allStations = root.Stations; var map = root.Map; var list = new List(map.Count); foreach (var channel in map) { var channelNumber = GetChannelNumber(channel); var stationIndex = allStations.FindIndex(item => string.Equals(item.StationId, channel.StationId, StringComparison.OrdinalIgnoreCase)); var station = stationIndex == -1 ? new StationDto { StationId = channel.StationId } : allStations[stationIndex]; var channelInfo = new ChannelInfo { Id = station.StationId, CallSign = station.Callsign, Number = channelNumber, Name = string.IsNullOrWhiteSpace(station.Name) ? channelNumber : station.Name }; if (station.Logo is not null) { channelInfo.ImageUrl = station.Logo.Url; } list.Add(channelInfo); } return list; } /// public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// /// Releases unmanaged and optionally managed resources. /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _tokenLock?.Dispose(); } _disposed = true; } } }