aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/LiveTv/Listings/SchedulesDirect.cs
blob: 2fbd47bc7730e051a860aba55b787a6df25db0e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
#nullable disable

#pragma warning disable CS1591

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
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;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.LiveTv.Listings.SchedulesDirectDtos;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.LiveTv;
using Microsoft.Extensions.Logging;

namespace Emby.Server.Implementations.LiveTv.Listings
{
    public class SchedulesDirect : IListingsProvider
    {
        private const string ApiUrl = "https://json.schedulesdirect.org/20141201";

        private readonly ILogger<SchedulesDirect> _logger;
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);

        private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
        private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
        private DateTime _lastErrorResponse;

        public SchedulesDirect(
            ILogger<SchedulesDirect> logger,
            IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
        }

        /// <inheritdoc />
        public string Name => "Schedules Direct";

        /// <inheritdoc />
        public string Type => nameof(SchedulesDirect);

        private static List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
        {
            var dates = new List<string>();

            var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
            var end = new List<DateTime> { 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<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(channelId))
            {
                throw new ArgumentNullException(nameof(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 Enumerable.Empty<ProgramInfo>();
            }

            var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);

            _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId);
            var requestList = new List<RequestScheduleForChannelDto>()
                {
                    new RequestScheduleForChannelDto()
                    {
                        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);
            using var response = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
            await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            var dailySchedules = await JsonSerializer.DeserializeAsync<IReadOnlyList<DayDto>>(responseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (dailySchedules == null)
            {
                return Array.Empty<ProgramInfo>();
            }

            _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);

            using var innerResponse = await Send(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false);
            await using var innerResponseStream = await innerResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            var programDetails = await JsonSerializer.DeserializeAsync<IReadOnlyList<ProgramDetailsDto>>(innerResponseStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (programDetails == null)
            {
                return Array.Empty<ProgramInfo>();
            }

            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<ProgramInfo>();
            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 " +
                //              schedule.ProgramId + " which says it has images? " +
                //              programDict[schedule.ProgramId].hasImageArtwork);

                if (string.IsNullOrEmpty(schedule.ProgramId))
                {
                    continue;
                }

                if (images != null)
                {
                    var imageIndex = images.FindIndex(i => i.ProgramId == schedule.ProgramId[..10]);
                    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) ??
                                                    GetProgramImage(ApiUrl, allImages, DesiredAspect);

                        const double WideAspect = 16.0 / 9;

                        programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect);

                        // 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);

                        // 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 == 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 != 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 == 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).IndexOf("premiere", StringComparison.OrdinalIgnoreCase) != -1
            };

            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 != null)
            {
                info.IsHD = programInfo.VideoProperties.Contains("hdtv", StringComparison.OrdinalIgnoreCase);
                info.Is3D = programInfo.VideoProperties.Contains("3d", StringComparison.OrdinalIgnoreCase);
            }

            if (details.ContentRating != 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 != null)
            {
                if (details.Descriptions.Description1000 != null && details.Descriptions.Description1000.Count > 0)
                {
                    info.Overview = details.Descriptions.Description1000[0].Description;
                }
                else if (details.Descriptions.Description100 != 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 != null)
                {
                    foreach (var metadataProgram in details.Metadata)
                    {
                        var gracenote = metadataProgram.Gracenote;
                        if (gracenote != null)
                        {
                            info.SeasonNumber = gracenote.Season;

                            if (gracenote.Episode > 0)
                            {
                                info.EpisodeNumber = gracenote.Episode;
                            }

                            break;
                        }
                    }
                }
            }

            if (details.OriginalAirDate != null)
            {
                info.OriginalAirDate = details.OriginalAirDate;
                info.ProductionYear = info.OriginalAirDate.Value.Year;
            }

            if (details.Movie != null)
            {
                if (!string.IsNullOrEmpty(details.Movie.Year)
                    && int.TryParse(details.Movie.Year, out int year))
                {
                    info.ProductionYear = year;
                }
            }

            if (details.Genres != 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<ImageDataDto> images, double desiredAspect)
        {
            var match = images
                .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i)))
                .ThenByDescending(i => GetSizeOrder(i))
                .FirstOrDefault();

            if (match == null)
            {
                return null;
            }

            var uri = match.Uri;

            if (string.IsNullOrWhiteSpace(uri))
            {
                return null;
            }
            else if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return uri;
            }
            else
            {
                return apiUrl + "/image/" + uri;
            }
        }

        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<IReadOnlyList<ShowImagesDto>> GetImageForPrograms(
            ListingsProviderInfo info,
            IReadOnlyList<string> programIds,
            CancellationToken cancellationToken)
        {
            if (programIds.Count == 0)
            {
                return Array.Empty<ShowImagesDto>();
            }

            StringBuilder str = new StringBuilder("[", 1 + (programIds.Count * 13));
            foreach (ReadOnlySpan<char> i in programIds)
            {
                str.Append('"')
                    .Append(i.Slice(0, 10))
                    .Append("\",");
            }

            // Remove last ,
            str.Length--;
            str.Append(']');

            using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/metadata/programs")
            {
                Content = new StringContent(str.ToString(), Encoding.UTF8, MediaTypeNames.Application.Json)
            };

            try
            {
                using var innerResponse2 = await Send(message, true, info, cancellationToken).ConfigureAwait(false);
                await using var response = await innerResponse2.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
                return await JsonSerializer.DeserializeAsync<IReadOnlyList<ShowImagesDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting image info from schedules direct");

                return Array.Empty<ShowImagesDto>();
            }
        }

        public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
        {
            var token = await GetToken(info, cancellationToken).ConfigureAwait(false);

            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);

            try
            {
                using var httpResponse = await Send(options, false, info, cancellationToken).ConfigureAwait(false);
                await using var response = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

                var root = await JsonSerializer.DeserializeAsync<IReadOnlyList<HeadendsDto>>(response, _jsonOptions, cancellationToken).ConfigureAwait(false);

                if (root != 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<string> 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;
            }

            // Avoid hammering SD
            if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
            {
                return null;
            }

            if (!_tokens.TryGetValue(username, out NameValuePair savedToken))
            {
                savedToken = new NameValuePair();
                _tokens.TryAdd(username, savedToken);
            }

            if (!string.IsNullOrEmpty(savedToken.Name) && !string.IsNullOrEmpty(savedToken.Value))
            {
                if (long.TryParse(savedToken.Value, NumberStyles.Any, 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;
                    }
                }
            }

            await _tokenSemaphore.WaitAsync(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)
            {
                if (ex.StatusCode.HasValue)
                {
                    if ((int)ex.StatusCode.Value == 400)
                    {
                        _tokens.Clear();
                        _lastErrorResponse = DateTime.UtcNow;
                    }
                }

                throw;
            }
            finally
            {
                _tokenSemaphore.Release();
            }
        }

        private async Task<HttpResponseMessage> Send(
            HttpRequestMessage options,
            bool enableRetry,
            ListingsProviderInfo providerInfo,
            CancellationToken cancellationToken,
            HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
        {
            var response = await _httpClientFactory.CreateClient(NamedClient.Default)
                .SendAsync(options, completionOption, cancellationToken).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                return response;
            }

            // 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);
            }

            _tokens.Clear();
            options.Headers.TryAddWithoutValidation("token", await GetToken(providerInfo, cancellationToken).ConfigureAwait(false));
            return await Send(options, false, providerInfo, cancellationToken).ConfigureAwait(false);
        }

        private async Task<string> GetTokenInternal(
            string username,
            string password,
            CancellationToken cancellationToken)
        {
            using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/token");
            var hashedPasswordBytes = SHA1.HashData(Encoding.ASCII.GetBytes(password));
            // 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);

            using var response = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();
            await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            var root = await JsonSerializer.DeserializeAsync<TokenDto>(stream, _jsonOptions, 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 Exception("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);

            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Authentication required.");
            }

            if (string.IsNullOrEmpty(info.ListingsId))
            {
                throw new ArgumentException("Listings Id required");
            }

            _logger.LogInformation("Adding new LineUp ");

            using var options = new HttpRequestMessage(HttpMethod.Put, ApiUrl + "/lineups/" + info.ListingsId);
            options.Headers.TryAddWithoutValidation("token", token);
            using var response = await _httpClientFactory.CreateClient(NamedClient.Default).SendAsync(options, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        }

        private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(info.ListingsId))
            {
                throw new ArgumentException("Listings Id required");
            }

            var token = await GetToken(info, cancellationToken).ConfigureAwait(false);

            if (string.IsNullOrEmpty(token))
            {
                throw new Exception("token required");
            }

            _logger.LogInformation("Headends on account ");

            using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups");
            options.Headers.TryAddWithoutValidation("token", token);

            try
            {
                using var httpResponse = await Send(options, false, null, cancellationToken).ConfigureAwait(false);
                httpResponse.EnsureSuccessStatusCode();
                await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
                using var response = httpResponse.Content;
                var root = await JsonSerializer.DeserializeAsync<LineupsDto>(stream, _jsonOptions, 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 Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
        {
            if (validateLogin)
            {
                if (string.IsNullOrEmpty(info.Username))
                {
                    throw new ArgumentException("Username is required");
                }

                if (string.IsNullOrEmpty(info.Password))
                {
                    throw new ArgumentException("Password is required");
                }
            }

            if (validateListings)
            {
                if (string.IsNullOrEmpty(info.ListingsId))
                {
                    throw new ArgumentException("Listings Id required");
                }

                var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);

                if (!hasLineup)
                {
                    await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
                }
            }
        }

        public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
        {
            return GetHeadends(info, country, location, CancellationToken.None);
        }

        public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
        {
            var listingsId = info.ListingsId;
            if (string.IsNullOrEmpty(listingsId))
            {
                throw new Exception("ListingsId required");
            }

            var token = await GetToken(info, cancellationToken).ConfigureAwait(false);

            if (string.IsNullOrEmpty(token))
            {
                throw new Exception("token required");
            }

            using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId);
            options.Headers.TryAddWithoutValidation("token", token);

            using var httpResponse = await Send(options, true, info, cancellationToken).ConfigureAwait(false);
            await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
            var root = await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (root == null)
            {
                return new List<ChannelInfo>();
            }

            _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<ChannelInfo>(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 != null)
                {
                    channelInfo.ImageUrl = station.Logo.Url;
                }

                list.Add(channelInfo);
            }

            return list;
        }
    }
}