SchedulesDirect.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. using System.Net;
  2. using MediaBrowser.Common;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.LiveTv;
  5. using MediaBrowser.Model.Dto;
  6. using MediaBrowser.Model.LiveTv;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using MediaBrowser.Model.Extensions;
  19. namespace Emby.Server.Implementations.LiveTv.Listings
  20. {
  21. public class SchedulesDirect : IListingsProvider
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IJsonSerializer _jsonSerializer;
  25. private readonly IHttpClient _httpClient;
  26. private readonly SemaphoreSlim _tokenSemaphore = new SemaphoreSlim(1, 1);
  27. private readonly IApplicationHost _appHost;
  28. private const string ApiUrl = "https://json.schedulesdirect.org/20141201";
  29. private readonly Dictionary<string, Dictionary<string, ScheduleDirect.Station>> _channelPairingCache =
  30. new Dictionary<string, Dictionary<string, ScheduleDirect.Station>>(StringComparer.OrdinalIgnoreCase);
  31. public SchedulesDirect(ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IApplicationHost appHost)
  32. {
  33. _logger = logger;
  34. _jsonSerializer = jsonSerializer;
  35. _httpClient = httpClient;
  36. _appHost = appHost;
  37. }
  38. private string UserAgent
  39. {
  40. get { return "Emby/" + _appHost.ApplicationVersion; }
  41. }
  42. private List<string> GetScheduleRequestDates(DateTime startDateUtc, DateTime endDateUtc)
  43. {
  44. List<string> dates = new List<string>();
  45. var start = new List<DateTime> { startDateUtc, startDateUtc.ToLocalTime() }.Min().Date;
  46. var end = new List<DateTime> { endDateUtc, endDateUtc.ToLocalTime() }.Max().Date;
  47. while (start <= end)
  48. {
  49. dates.Add(start.ToString("yyyy-MM-dd"));
  50. start = start.AddDays(1);
  51. }
  52. return dates;
  53. }
  54. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  55. {
  56. if (string.IsNullOrWhiteSpace(channelId))
  57. {
  58. throw new ArgumentNullException("channelId");
  59. }
  60. // Normalize incoming input
  61. channelId = channelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  62. List<ProgramInfo> programsInfo = new List<ProgramInfo>();
  63. var token = await GetToken(info, cancellationToken).ConfigureAwait(false);
  64. if (string.IsNullOrWhiteSpace(token))
  65. {
  66. _logger.Warn("SchedulesDirect token is empty, returning empty program list");
  67. return programsInfo;
  68. }
  69. var dates = GetScheduleRequestDates(startDateUtc, endDateUtc);
  70. string stationID = channelId;
  71. _logger.Info("Channel Station ID is: " + stationID);
  72. List<ScheduleDirect.RequestScheduleForChannel> requestList =
  73. new List<ScheduleDirect.RequestScheduleForChannel>()
  74. {
  75. new ScheduleDirect.RequestScheduleForChannel()
  76. {
  77. stationID = stationID,
  78. date = dates
  79. }
  80. };
  81. var requestString = _jsonSerializer.SerializeToString(requestList);
  82. _logger.Debug("Request string for schedules is: " + requestString);
  83. var httpOptions = new HttpRequestOptions()
  84. {
  85. Url = ApiUrl + "/schedules",
  86. UserAgent = UserAgent,
  87. CancellationToken = cancellationToken,
  88. // The data can be large so give it some extra time
  89. TimeoutMs = 60000,
  90. LogErrorResponseBody = true
  91. };
  92. httpOptions.RequestHeaders["token"] = token;
  93. httpOptions.RequestContent = requestString;
  94. using (var response = await Post(httpOptions, true, info).ConfigureAwait(false))
  95. {
  96. StreamReader reader = new StreamReader(response.Content);
  97. string responseString = reader.ReadToEnd();
  98. var dailySchedules = _jsonSerializer.DeserializeFromString<List<ScheduleDirect.Day>>(responseString);
  99. _logger.Debug("Found " + dailySchedules.Count + " programs on " + stationID + " ScheduleDirect");
  100. httpOptions = new HttpRequestOptions()
  101. {
  102. Url = ApiUrl + "/programs",
  103. UserAgent = UserAgent,
  104. CancellationToken = cancellationToken,
  105. LogErrorResponseBody = true,
  106. // The data can be large so give it some extra time
  107. TimeoutMs = 60000
  108. };
  109. httpOptions.RequestHeaders["token"] = token;
  110. List<string> programsID = new List<string>();
  111. programsID = dailySchedules.SelectMany(d => d.programs.Select(s => s.programID)).Distinct().ToList();
  112. var requestBody = "[\"" + string.Join("\", \"", programsID) + "\"]";
  113. httpOptions.RequestContent = requestBody;
  114. double wideAspect = 1.77777778;
  115. var primaryImageCategory = "Logo";
  116. using (var innerResponse = await Post(httpOptions, true, info).ConfigureAwait(false))
  117. {
  118. StreamReader innerReader = new StreamReader(innerResponse.Content);
  119. responseString = innerReader.ReadToEnd();
  120. var programDetails =
  121. _jsonSerializer.DeserializeFromString<List<ScheduleDirect.ProgramDetails>>(
  122. responseString);
  123. var programDict = programDetails.ToDictionary(p => p.programID, y => y);
  124. var programIdsWithImages =
  125. programDetails.Where(p => p.hasImageArtwork).Select(p => p.programID)
  126. .ToList();
  127. var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false);
  128. var schedules = dailySchedules.SelectMany(d => d.programs);
  129. foreach (ScheduleDirect.Program schedule in schedules)
  130. {
  131. //_logger.Debug("Proccesing Schedule for statio ID " + stationID +
  132. // " which corresponds to channel " + channelNumber + " and program id " +
  133. // schedule.programID + " which says it has images? " +
  134. // programDict[schedule.programID].hasImageArtwork);
  135. if (images != null)
  136. {
  137. var imageIndex = images.FindIndex(i => i.programID == schedule.programID.Substring(0, 10));
  138. if (imageIndex > -1)
  139. {
  140. var programEntry = programDict[schedule.programID];
  141. var allImages = (images[imageIndex].data ?? new List<ScheduleDirect.ImageData>()).ToList();
  142. var imagesWithText = allImages.Where(i => string.Equals(i.text, "yes", StringComparison.OrdinalIgnoreCase)).ToList();
  143. var imagesWithoutText = allImages.Where(i => string.Equals(i.text, "no", StringComparison.OrdinalIgnoreCase)).ToList();
  144. double desiredAspect = 0.666666667;
  145. programEntry.primaryImage = GetProgramImage(ApiUrl, imagesWithText, true, desiredAspect) ??
  146. GetProgramImage(ApiUrl, allImages, true, desiredAspect);
  147. programEntry.thumbImage = GetProgramImage(ApiUrl, imagesWithText, true, wideAspect);
  148. // Don't supply the same image twice
  149. if (string.Equals(programEntry.primaryImage, programEntry.thumbImage, StringComparison.Ordinal))
  150. {
  151. programEntry.thumbImage = null;
  152. }
  153. programEntry.backdropImage = GetProgramImage(ApiUrl, imagesWithoutText, true, wideAspect);
  154. //programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ??
  155. // GetProgramImage(ApiUrl, data, "Banner-L1", false) ??
  156. // GetProgramImage(ApiUrl, data, "Banner-LO", false) ??
  157. // GetProgramImage(ApiUrl, data, "Banner-LOT", false);
  158. }
  159. }
  160. programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.programID]));
  161. }
  162. }
  163. }
  164. return programsInfo;
  165. }
  166. private int GetSizeOrder(ScheduleDirect.ImageData image)
  167. {
  168. if (!string.IsNullOrWhiteSpace(image.height))
  169. {
  170. int value;
  171. if (int.TryParse(image.height, out value))
  172. {
  173. return value;
  174. }
  175. }
  176. return 0;
  177. }
  178. private string GetChannelNumber(ScheduleDirect.Map map)
  179. {
  180. var channelNumber = map.logicalChannelNumber;
  181. if (string.IsNullOrWhiteSpace(channelNumber))
  182. {
  183. channelNumber = map.channel;
  184. }
  185. if (string.IsNullOrWhiteSpace(channelNumber))
  186. {
  187. channelNumber = map.atscMajor + "." + map.atscMinor;
  188. }
  189. channelNumber = channelNumber.TrimStart('0');
  190. return channelNumber;
  191. }
  192. private bool IsMovie(ScheduleDirect.ProgramDetails programInfo)
  193. {
  194. return string.Equals(programInfo.entityType, "movie", StringComparison.OrdinalIgnoreCase);
  195. }
  196. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  197. {
  198. DateTime startAt = GetDate(programInfo.airDateTime);
  199. DateTime endAt = startAt.AddSeconds(programInfo.duration);
  200. ProgramAudio audioType = ProgramAudio.Stereo;
  201. bool repeat = programInfo.@new == null;
  202. var programId = programInfo.programID ?? string.Empty;
  203. string newID = programId + "T" + startAt.Ticks + "C" + channelId;
  204. if (programInfo.audioProperties != null)
  205. {
  206. if (programInfo.audioProperties.Exists(item => string.Equals(item, "atmos", StringComparison.OrdinalIgnoreCase)))
  207. {
  208. audioType = ProgramAudio.Atmos;
  209. }
  210. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd 5.1", StringComparison.OrdinalIgnoreCase)))
  211. {
  212. audioType = ProgramAudio.DolbyDigital;
  213. }
  214. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "dd", StringComparison.OrdinalIgnoreCase)))
  215. {
  216. audioType = ProgramAudio.DolbyDigital;
  217. }
  218. else if (programInfo.audioProperties.Exists(item => string.Equals(item, "stereo", StringComparison.OrdinalIgnoreCase)))
  219. {
  220. audioType = ProgramAudio.Stereo;
  221. }
  222. else
  223. {
  224. audioType = ProgramAudio.Mono;
  225. }
  226. }
  227. string episodeTitle = null;
  228. if (details.episodeTitle150 != null)
  229. {
  230. episodeTitle = details.episodeTitle150;
  231. }
  232. var info = new ProgramInfo
  233. {
  234. ChannelId = channelId,
  235. Id = newID,
  236. StartDate = startAt,
  237. EndDate = endAt,
  238. Name = details.titles[0].title120 ?? "Unkown",
  239. OfficialRating = null,
  240. CommunityRating = null,
  241. EpisodeTitle = episodeTitle,
  242. Audio = audioType,
  243. IsRepeat = repeat,
  244. IsSeries = string.Equals(details.entityType, "episode", StringComparison.OrdinalIgnoreCase),
  245. ImageUrl = details.primaryImage,
  246. ThumbImageUrl = details.thumbImage,
  247. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  248. IsSports = string.Equals(details.entityType, "sports", StringComparison.OrdinalIgnoreCase),
  249. IsMovie = IsMovie(details),
  250. Etag = programInfo.md5
  251. };
  252. var showId = programId;
  253. if (!info.IsSeries)
  254. {
  255. // It's also a series if it starts with SH
  256. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  257. }
  258. // According to SchedulesDirect, these are generic, unidentified episodes
  259. // SH005316560000
  260. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  261. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  262. if (!hasUniqueShowId)
  263. {
  264. showId = newID;
  265. }
  266. info.ShowId = showId;
  267. if (programInfo.videoProperties != null)
  268. {
  269. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  270. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  271. }
  272. if (details.contentRating != null && details.contentRating.Count > 0)
  273. {
  274. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
  275. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  276. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  277. {
  278. info.OfficialRating = null;
  279. }
  280. }
  281. if (details.descriptions != null)
  282. {
  283. if (details.descriptions.description1000 != null && details.descriptions.description1000.Count > 0)
  284. {
  285. info.Overview = details.descriptions.description1000[0].description;
  286. }
  287. else if (details.descriptions.description100 != null && details.descriptions.description100.Count > 0)
  288. {
  289. info.Overview = details.descriptions.description100[0].description;
  290. }
  291. }
  292. if (info.IsSeries)
  293. {
  294. info.SeriesId = programId.Substring(0, 10);
  295. if (details.metadata != null)
  296. {
  297. foreach (var metadataProgram in details.metadata)
  298. {
  299. var gracenote = metadataProgram.Gracenote;
  300. if (gracenote != null)
  301. {
  302. info.SeasonNumber = gracenote.season;
  303. if (gracenote.episode > 0)
  304. {
  305. info.EpisodeNumber = gracenote.episode;
  306. }
  307. break;
  308. }
  309. }
  310. }
  311. }
  312. if (!string.IsNullOrWhiteSpace(details.originalAirDate) && (!info.IsSeries || info.IsRepeat))
  313. {
  314. info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
  315. info.ProductionYear = info.OriginalAirDate.Value.Year;
  316. }
  317. if (details.genres != null)
  318. {
  319. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  320. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  321. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  322. {
  323. info.IsKids = true;
  324. }
  325. }
  326. return info;
  327. }
  328. private DateTime GetDate(string value)
  329. {
  330. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  331. if (date.Kind != DateTimeKind.Utc)
  332. {
  333. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  334. }
  335. return date;
  336. }
  337. private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
  338. {
  339. string url = null;
  340. var matches = images;
  341. matches = matches
  342. .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i)))
  343. .ThenByDescending(GetSizeOrder)
  344. .ToList();
  345. var match = matches.FirstOrDefault();
  346. if (match == null)
  347. {
  348. return null;
  349. }
  350. var uri = match.uri;
  351. if (!string.IsNullOrWhiteSpace(uri))
  352. {
  353. if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  354. {
  355. url = uri;
  356. }
  357. else
  358. {
  359. url = apiUrl + "/image/" + uri;
  360. }
  361. }
  362. //_logger.Debug("URL for image is : " + url);
  363. return url;
  364. }
  365. private double GetApsectRatio(ScheduleDirect.ImageData i)
  366. {
  367. int width = 0;
  368. int height = 0;
  369. if (!string.IsNullOrWhiteSpace(i.width))
  370. {
  371. int.TryParse(i.width, out width);
  372. }
  373. if (!string.IsNullOrWhiteSpace(i.height))
  374. {
  375. int.TryParse(i.height, out height);
  376. }
  377. if (height == 0 || width == 0)
  378. {
  379. return 0;
  380. }
  381. double result = width;
  382. result /= height;
  383. return result;
  384. }
  385. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  386. ListingsProviderInfo info,
  387. List<string> programIds,
  388. CancellationToken cancellationToken)
  389. {
  390. if (programIds.Count == 0)
  391. {
  392. return new List<ScheduleDirect.ShowImages>();
  393. }
  394. var imageIdString = "[";
  395. foreach (var i in programIds)
  396. {
  397. var imageId = i.Substring(0, 10);
  398. if (!imageIdString.Contains(imageId))
  399. {
  400. imageIdString += "\"" + imageId + "\",";
  401. }
  402. }
  403. imageIdString = imageIdString.TrimEnd(',') + "]";
  404. var httpOptions = new HttpRequestOptions()
  405. {
  406. Url = ApiUrl + "/metadata/programs",
  407. UserAgent = UserAgent,
  408. CancellationToken = cancellationToken,
  409. RequestContent = imageIdString,
  410. LogErrorResponseBody = true,
  411. // The data can be large so give it some extra time
  412. TimeoutMs = 60000
  413. };
  414. try
  415. {
  416. using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
  417. {
  418. return _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.ShowImages>>(
  419. innerResponse2.Content);
  420. }
  421. }
  422. catch (Exception ex)
  423. {
  424. _logger.ErrorException("Error getting image info from schedules direct", ex);
  425. return new List<ScheduleDirect.ShowImages>();
  426. }
  427. }
  428. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  429. {
  430. var token = await GetToken(info, cancellationToken);
  431. var lineups = new List<NameIdPair>();
  432. if (string.IsNullOrWhiteSpace(token))
  433. {
  434. return lineups;
  435. }
  436. var options = new HttpRequestOptions()
  437. {
  438. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  439. UserAgent = UserAgent,
  440. CancellationToken = cancellationToken,
  441. LogErrorResponseBody = true
  442. };
  443. options.RequestHeaders["token"] = token;
  444. try
  445. {
  446. using (var httpResponse = await Get(options, false, info).ConfigureAwait(false))
  447. {
  448. using (Stream responce = httpResponse.Content)
  449. {
  450. var root = _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.Headends>>(responce);
  451. if (root != null)
  452. {
  453. foreach (ScheduleDirect.Headends headend in root)
  454. {
  455. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  456. {
  457. lineups.Add(new NameIdPair
  458. {
  459. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  460. Id = lineup.uri.Substring(18)
  461. });
  462. }
  463. }
  464. }
  465. else
  466. {
  467. _logger.Info("No lineups available");
  468. }
  469. }
  470. }
  471. }
  472. catch (Exception ex)
  473. {
  474. _logger.Error("Error getting headends", ex);
  475. }
  476. return lineups;
  477. }
  478. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  479. private DateTime _lastErrorResponse;
  480. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  481. {
  482. var username = info.Username;
  483. // Reset the token if there's no username
  484. if (string.IsNullOrWhiteSpace(username))
  485. {
  486. return null;
  487. }
  488. var password = info.Password;
  489. if (string.IsNullOrWhiteSpace(password))
  490. {
  491. return null;
  492. }
  493. // Avoid hammering SD
  494. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  495. {
  496. return null;
  497. }
  498. NameValuePair savedToken = null;
  499. if (!_tokens.TryGetValue(username, out savedToken))
  500. {
  501. savedToken = new NameValuePair();
  502. _tokens.TryAdd(username, savedToken);
  503. }
  504. if (!string.IsNullOrWhiteSpace(savedToken.Name) && !string.IsNullOrWhiteSpace(savedToken.Value))
  505. {
  506. long ticks;
  507. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
  508. {
  509. // If it's under 24 hours old we can still use it
  510. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  511. {
  512. return savedToken.Name;
  513. }
  514. }
  515. }
  516. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  517. try
  518. {
  519. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  520. savedToken.Name = result;
  521. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  522. return result;
  523. }
  524. catch (HttpException ex)
  525. {
  526. if (ex.StatusCode.HasValue)
  527. {
  528. if ((int)ex.StatusCode.Value == 400)
  529. {
  530. _tokens.Clear();
  531. _lastErrorResponse = DateTime.UtcNow;
  532. }
  533. }
  534. throw;
  535. }
  536. finally
  537. {
  538. _tokenSemaphore.Release();
  539. }
  540. }
  541. private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
  542. bool enableRetry,
  543. ListingsProviderInfo providerInfo)
  544. {
  545. // Schedules direct requires that the client support compression and will return a 400 response without it
  546. options.EnableHttpCompression = true;
  547. try
  548. {
  549. return await _httpClient.Post(options).ConfigureAwait(false);
  550. }
  551. catch (HttpException ex)
  552. {
  553. _tokens.Clear();
  554. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  555. {
  556. enableRetry = false;
  557. }
  558. if (!enableRetry)
  559. {
  560. throw;
  561. }
  562. }
  563. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  564. options.RequestHeaders["token"] = newToken;
  565. return await Post(options, false, providerInfo).ConfigureAwait(false);
  566. }
  567. private async Task<HttpResponseInfo> Get(HttpRequestOptions options,
  568. bool enableRetry,
  569. ListingsProviderInfo providerInfo)
  570. {
  571. // Schedules direct requires that the client support compression and will return a 400 response without it
  572. options.EnableHttpCompression = true;
  573. try
  574. {
  575. return await _httpClient.SendAsync(options, "GET").ConfigureAwait(false);
  576. }
  577. catch (HttpException ex)
  578. {
  579. _tokens.Clear();
  580. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  581. {
  582. enableRetry = false;
  583. }
  584. if (!enableRetry)
  585. {
  586. throw;
  587. }
  588. }
  589. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  590. options.RequestHeaders["token"] = newToken;
  591. return await Get(options, false, providerInfo).ConfigureAwait(false);
  592. }
  593. private async Task<string> GetTokenInternal(string username, string password,
  594. CancellationToken cancellationToken)
  595. {
  596. var httpOptions = new HttpRequestOptions()
  597. {
  598. Url = ApiUrl + "/token",
  599. UserAgent = UserAgent,
  600. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  601. CancellationToken = cancellationToken,
  602. LogErrorResponseBody = true
  603. };
  604. //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  605. // httpOptions.RequestContent);
  606. using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false))
  607. {
  608. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Token>(responce.Content);
  609. if (root.message == "OK")
  610. {
  611. _logger.Info("Authenticated with Schedules Direct token: " + root.token);
  612. return root.token;
  613. }
  614. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  615. }
  616. }
  617. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  618. {
  619. var token = await GetToken(info, cancellationToken);
  620. if (string.IsNullOrWhiteSpace(token))
  621. {
  622. throw new ArgumentException("Authentication required.");
  623. }
  624. if (string.IsNullOrWhiteSpace(info.ListingsId))
  625. {
  626. throw new ArgumentException("Listings Id required");
  627. }
  628. _logger.Info("Adding new LineUp ");
  629. var httpOptions = new HttpRequestOptions()
  630. {
  631. Url = ApiUrl + "/lineups/" + info.ListingsId,
  632. UserAgent = UserAgent,
  633. CancellationToken = cancellationToken,
  634. LogErrorResponseBody = true,
  635. BufferContent = false
  636. };
  637. httpOptions.RequestHeaders["token"] = token;
  638. using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
  639. {
  640. }
  641. }
  642. public string Name
  643. {
  644. get { return "Schedules Direct"; }
  645. }
  646. public static string TypeName = "SchedulesDirect";
  647. public string Type
  648. {
  649. get { return TypeName; }
  650. }
  651. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  652. {
  653. if (string.IsNullOrWhiteSpace(info.ListingsId))
  654. {
  655. throw new ArgumentException("Listings Id required");
  656. }
  657. var token = await GetToken(info, cancellationToken);
  658. if (string.IsNullOrWhiteSpace(token))
  659. {
  660. throw new Exception("token required");
  661. }
  662. _logger.Info("Headends on account ");
  663. var options = new HttpRequestOptions()
  664. {
  665. Url = ApiUrl + "/lineups",
  666. UserAgent = UserAgent,
  667. CancellationToken = cancellationToken,
  668. LogErrorResponseBody = true
  669. };
  670. options.RequestHeaders["token"] = token;
  671. try
  672. {
  673. using (var httpResponse = await Get(options, false, null).ConfigureAwait(false))
  674. {
  675. using (var response = httpResponse.Content)
  676. {
  677. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Lineups>(response);
  678. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  679. }
  680. }
  681. }
  682. catch (HttpException ex)
  683. {
  684. // Apparently we're supposed to swallow this
  685. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  686. {
  687. return false;
  688. }
  689. throw;
  690. }
  691. }
  692. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  693. {
  694. if (validateLogin)
  695. {
  696. if (string.IsNullOrWhiteSpace(info.Username))
  697. {
  698. throw new ArgumentException("Username is required");
  699. }
  700. if (string.IsNullOrWhiteSpace(info.Password))
  701. {
  702. throw new ArgumentException("Password is required");
  703. }
  704. }
  705. if (validateListings)
  706. {
  707. if (string.IsNullOrWhiteSpace(info.ListingsId))
  708. {
  709. throw new ArgumentException("Listings Id required");
  710. }
  711. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  712. if (!hasLineup)
  713. {
  714. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  715. }
  716. }
  717. }
  718. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  719. {
  720. return GetHeadends(info, country, location, CancellationToken.None);
  721. }
  722. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  723. {
  724. var listingsId = info.ListingsId;
  725. if (string.IsNullOrWhiteSpace(listingsId))
  726. {
  727. throw new Exception("ListingsId required");
  728. }
  729. var token = await GetToken(info, cancellationToken);
  730. if (string.IsNullOrWhiteSpace(token))
  731. {
  732. throw new Exception("token required");
  733. }
  734. var httpOptions = new HttpRequestOptions()
  735. {
  736. Url = ApiUrl + "/lineups/" + listingsId,
  737. UserAgent = UserAgent,
  738. CancellationToken = cancellationToken,
  739. LogErrorResponseBody = true,
  740. // The data can be large so give it some extra time
  741. TimeoutMs = 60000
  742. };
  743. httpOptions.RequestHeaders["token"] = token;
  744. var list = new List<ChannelInfo>();
  745. using (var httpResponse = await Get(httpOptions, true, info).ConfigureAwait(false))
  746. {
  747. using (var response = httpResponse.Content)
  748. {
  749. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Channel>(response);
  750. _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect");
  751. _logger.Info("Mapping Stations to Channel");
  752. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  753. foreach (ScheduleDirect.Map map in root.map)
  754. {
  755. var channelNumber = GetChannelNumber(map);
  756. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  757. if (station == null)
  758. {
  759. station = new ScheduleDirect.Station
  760. {
  761. stationID = map.stationID
  762. };
  763. }
  764. var name = channelNumber;
  765. var channelInfo = new ChannelInfo
  766. {
  767. Number = channelNumber,
  768. Name = name
  769. };
  770. if (station != null)
  771. {
  772. if (!string.IsNullOrWhiteSpace(station.name))
  773. {
  774. channelInfo.Name = station.name;
  775. }
  776. channelInfo.Id = station.stationID;
  777. channelInfo.CallSign = station.callsign;
  778. if (station.logo != null)
  779. {
  780. channelInfo.ImageUrl = station.logo.URL;
  781. channelInfo.HasImage = true;
  782. }
  783. }
  784. list.Add(channelInfo);
  785. }
  786. }
  787. }
  788. return list;
  789. }
  790. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  791. {
  792. if (!string.IsNullOrWhiteSpace(channelName))
  793. {
  794. channelName = NormalizeName(channelName);
  795. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  796. if (result != null)
  797. {
  798. return result;
  799. }
  800. }
  801. if (!string.IsNullOrWhiteSpace(channelNumber))
  802. {
  803. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  804. }
  805. return null;
  806. }
  807. private string NormalizeName(string value)
  808. {
  809. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  810. }
  811. public class ScheduleDirect
  812. {
  813. public class Token
  814. {
  815. public int code { get; set; }
  816. public string message { get; set; }
  817. public string serverID { get; set; }
  818. public string token { get; set; }
  819. }
  820. public class Lineup
  821. {
  822. public string lineup { get; set; }
  823. public string name { get; set; }
  824. public string transport { get; set; }
  825. public string location { get; set; }
  826. public string uri { get; set; }
  827. }
  828. public class Lineups
  829. {
  830. public int code { get; set; }
  831. public string serverID { get; set; }
  832. public string datetime { get; set; }
  833. public List<Lineup> lineups { get; set; }
  834. }
  835. public class Headends
  836. {
  837. public string headend { get; set; }
  838. public string transport { get; set; }
  839. public string location { get; set; }
  840. public List<Lineup> lineups { get; set; }
  841. }
  842. public class Map
  843. {
  844. public string stationID { get; set; }
  845. public string channel { get; set; }
  846. public string logicalChannelNumber { get; set; }
  847. public int uhfVhf { get; set; }
  848. public int atscMajor { get; set; }
  849. public int atscMinor { get; set; }
  850. }
  851. public class Broadcaster
  852. {
  853. public string city { get; set; }
  854. public string state { get; set; }
  855. public string postalcode { get; set; }
  856. public string country { get; set; }
  857. }
  858. public class Logo
  859. {
  860. public string URL { get; set; }
  861. public int height { get; set; }
  862. public int width { get; set; }
  863. public string md5 { get; set; }
  864. }
  865. public class Station
  866. {
  867. public string stationID { get; set; }
  868. public string name { get; set; }
  869. public string callsign { get; set; }
  870. public List<string> broadcastLanguage { get; set; }
  871. public List<string> descriptionLanguage { get; set; }
  872. public Broadcaster broadcaster { get; set; }
  873. public string affiliate { get; set; }
  874. public Logo logo { get; set; }
  875. public bool? isCommercialFree { get; set; }
  876. }
  877. public class Metadata
  878. {
  879. public string lineup { get; set; }
  880. public string modified { get; set; }
  881. public string transport { get; set; }
  882. }
  883. public class Channel
  884. {
  885. public List<Map> map { get; set; }
  886. public List<Station> stations { get; set; }
  887. public Metadata metadata { get; set; }
  888. }
  889. public class RequestScheduleForChannel
  890. {
  891. public string stationID { get; set; }
  892. public List<string> date { get; set; }
  893. }
  894. public class Rating
  895. {
  896. public string body { get; set; }
  897. public string code { get; set; }
  898. }
  899. public class Multipart
  900. {
  901. public int partNumber { get; set; }
  902. public int totalParts { get; set; }
  903. }
  904. public class Program
  905. {
  906. public string programID { get; set; }
  907. public string airDateTime { get; set; }
  908. public int duration { get; set; }
  909. public string md5 { get; set; }
  910. public List<string> audioProperties { get; set; }
  911. public List<string> videoProperties { get; set; }
  912. public List<Rating> ratings { get; set; }
  913. public bool? @new { get; set; }
  914. public Multipart multipart { get; set; }
  915. }
  916. public class MetadataSchedule
  917. {
  918. public string modified { get; set; }
  919. public string md5 { get; set; }
  920. public string startDate { get; set; }
  921. public string endDate { get; set; }
  922. public int days { get; set; }
  923. }
  924. public class Day
  925. {
  926. public string stationID { get; set; }
  927. public List<Program> programs { get; set; }
  928. public MetadataSchedule metadata { get; set; }
  929. public Day()
  930. {
  931. programs = new List<Program>();
  932. }
  933. }
  934. //
  935. public class Title
  936. {
  937. public string title120 { get; set; }
  938. }
  939. public class EventDetails
  940. {
  941. public string subType { get; set; }
  942. }
  943. public class Description100
  944. {
  945. public string descriptionLanguage { get; set; }
  946. public string description { get; set; }
  947. }
  948. public class Description1000
  949. {
  950. public string descriptionLanguage { get; set; }
  951. public string description { get; set; }
  952. }
  953. public class DescriptionsProgram
  954. {
  955. public List<Description100> description100 { get; set; }
  956. public List<Description1000> description1000 { get; set; }
  957. }
  958. public class Gracenote
  959. {
  960. public int season { get; set; }
  961. public int episode { get; set; }
  962. }
  963. public class MetadataPrograms
  964. {
  965. public Gracenote Gracenote { get; set; }
  966. }
  967. public class ContentRating
  968. {
  969. public string body { get; set; }
  970. public string code { get; set; }
  971. }
  972. public class Cast
  973. {
  974. public string billingOrder { get; set; }
  975. public string role { get; set; }
  976. public string nameId { get; set; }
  977. public string personId { get; set; }
  978. public string name { get; set; }
  979. public string characterName { get; set; }
  980. }
  981. public class Crew
  982. {
  983. public string billingOrder { get; set; }
  984. public string role { get; set; }
  985. public string nameId { get; set; }
  986. public string personId { get; set; }
  987. public string name { get; set; }
  988. }
  989. public class QualityRating
  990. {
  991. public string ratingsBody { get; set; }
  992. public string rating { get; set; }
  993. public string minRating { get; set; }
  994. public string maxRating { get; set; }
  995. public string increment { get; set; }
  996. }
  997. public class Movie
  998. {
  999. public string year { get; set; }
  1000. public int duration { get; set; }
  1001. public List<QualityRating> qualityRating { get; set; }
  1002. }
  1003. public class Recommendation
  1004. {
  1005. public string programID { get; set; }
  1006. public string title120 { get; set; }
  1007. }
  1008. public class ProgramDetails
  1009. {
  1010. public string audience { get; set; }
  1011. public string programID { get; set; }
  1012. public List<Title> titles { get; set; }
  1013. public EventDetails eventDetails { get; set; }
  1014. public DescriptionsProgram descriptions { get; set; }
  1015. public string originalAirDate { get; set; }
  1016. public List<string> genres { get; set; }
  1017. public string episodeTitle150 { get; set; }
  1018. public List<MetadataPrograms> metadata { get; set; }
  1019. public List<ContentRating> contentRating { get; set; }
  1020. public List<Cast> cast { get; set; }
  1021. public List<Crew> crew { get; set; }
  1022. public string entityType { get; set; }
  1023. public string showType { get; set; }
  1024. public bool hasImageArtwork { get; set; }
  1025. public string primaryImage { get; set; }
  1026. public string thumbImage { get; set; }
  1027. public string backdropImage { get; set; }
  1028. public string bannerImage { get; set; }
  1029. public string imageID { get; set; }
  1030. public string md5 { get; set; }
  1031. public List<string> contentAdvisory { get; set; }
  1032. public Movie movie { get; set; }
  1033. public List<Recommendation> recommendations { get; set; }
  1034. }
  1035. public class Caption
  1036. {
  1037. public string content { get; set; }
  1038. public string lang { get; set; }
  1039. }
  1040. public class ImageData
  1041. {
  1042. public string width { get; set; }
  1043. public string height { get; set; }
  1044. public string uri { get; set; }
  1045. public string size { get; set; }
  1046. public string aspect { get; set; }
  1047. public string category { get; set; }
  1048. public string text { get; set; }
  1049. public string primary { get; set; }
  1050. public string tier { get; set; }
  1051. public Caption caption { get; set; }
  1052. }
  1053. public class ShowImages
  1054. {
  1055. public string programID { get; set; }
  1056. public List<ImageData> data { get; set; }
  1057. }
  1058. }
  1059. }
  1060. }