SchedulesDirect.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 = IsMovie(programEntry) ? 0.666666667 : wideAspect;
  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. var showType = programInfo.showType ?? string.Empty;
  195. return showType.IndexOf("movie", StringComparison.OrdinalIgnoreCase) != -1 || showType.IndexOf("film", StringComparison.OrdinalIgnoreCase) != -1;
  196. }
  197. private ProgramInfo GetProgram(string channelId, ScheduleDirect.Program programInfo, ScheduleDirect.ProgramDetails details)
  198. {
  199. DateTime startAt = GetDate(programInfo.airDateTime);
  200. DateTime endAt = startAt.AddSeconds(programInfo.duration);
  201. ProgramAudio audioType = ProgramAudio.Stereo;
  202. bool repeat = programInfo.@new == null;
  203. string newID = programInfo.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 showType = details.showType ?? string.Empty;
  233. var info = new ProgramInfo
  234. {
  235. ChannelId = channelId,
  236. Id = newID,
  237. StartDate = startAt,
  238. EndDate = endAt,
  239. Name = details.titles[0].title120 ?? "Unkown",
  240. OfficialRating = null,
  241. CommunityRating = null,
  242. EpisodeTitle = episodeTitle,
  243. Audio = audioType,
  244. IsRepeat = repeat,
  245. IsSeries = showType.IndexOf("series", StringComparison.OrdinalIgnoreCase) != -1,
  246. ImageUrl = details.primaryImage,
  247. ThumbImageUrl = details.thumbImage,
  248. IsKids = string.Equals(details.audience, "children", StringComparison.OrdinalIgnoreCase),
  249. IsSports = showType.IndexOf("sports", StringComparison.OrdinalIgnoreCase) != -1,
  250. IsMovie = IsMovie(details),
  251. Etag = programInfo.md5
  252. };
  253. var showId = programInfo.programID ?? string.Empty;
  254. if (!info.IsSeries)
  255. {
  256. // It's also a series if it starts with SH
  257. info.IsSeries = showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) && showId.Length >= 14;
  258. }
  259. // According to SchedulesDirect, these are generic, unidentified episodes
  260. // SH005316560000
  261. var hasUniqueShowId = !showId.StartsWith("SH", StringComparison.OrdinalIgnoreCase) ||
  262. !showId.EndsWith("0000", StringComparison.OrdinalIgnoreCase);
  263. if (!hasUniqueShowId)
  264. {
  265. showId = newID;
  266. }
  267. info.ShowId = showId;
  268. if (programInfo.videoProperties != null)
  269. {
  270. info.IsHD = programInfo.videoProperties.Contains("hdtv", StringComparer.OrdinalIgnoreCase);
  271. info.Is3D = programInfo.videoProperties.Contains("3d", StringComparer.OrdinalIgnoreCase);
  272. }
  273. if (details.contentRating != null && details.contentRating.Count > 0)
  274. {
  275. info.OfficialRating = details.contentRating[0].code.Replace("TV", "TV-").Replace("--", "-");
  276. var invalid = new[] { "N/A", "Approved", "Not Rated", "Passed" };
  277. if (invalid.Contains(info.OfficialRating, StringComparer.OrdinalIgnoreCase))
  278. {
  279. info.OfficialRating = null;
  280. }
  281. }
  282. if (details.descriptions != null)
  283. {
  284. if (details.descriptions.description1000 != null)
  285. {
  286. info.Overview = details.descriptions.description1000[0].description;
  287. }
  288. else if (details.descriptions.description100 != null)
  289. {
  290. info.Overview = details.descriptions.description100[0].description;
  291. }
  292. }
  293. if (info.IsSeries)
  294. {
  295. info.SeriesId = programInfo.programID.Substring(0, 10);
  296. if (details.metadata != null)
  297. {
  298. var gracenote = details.metadata.Find(x => x.Gracenote != null).Gracenote;
  299. info.SeasonNumber = gracenote.season;
  300. if (gracenote.episode > 0)
  301. {
  302. info.EpisodeNumber = gracenote.episode;
  303. }
  304. }
  305. }
  306. if (!string.IsNullOrWhiteSpace(details.originalAirDate) && (!info.IsSeries || info.IsRepeat))
  307. {
  308. info.OriginalAirDate = DateTime.Parse(details.originalAirDate);
  309. info.ProductionYear = info.OriginalAirDate.Value.Year;
  310. }
  311. if (details.genres != null)
  312. {
  313. info.Genres = details.genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
  314. info.IsNews = details.genres.Contains("news", StringComparer.OrdinalIgnoreCase);
  315. if (info.Genres.Contains("children", StringComparer.OrdinalIgnoreCase))
  316. {
  317. info.IsKids = true;
  318. }
  319. }
  320. return info;
  321. }
  322. private DateTime GetDate(string value)
  323. {
  324. var date = DateTime.ParseExact(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture);
  325. if (date.Kind != DateTimeKind.Utc)
  326. {
  327. date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
  328. }
  329. return date;
  330. }
  331. private string GetProgramImage(string apiUrl, List<ScheduleDirect.ImageData> images, bool returnDefaultImage, double desiredAspect)
  332. {
  333. string url = null;
  334. var matches = images;
  335. matches = matches
  336. .OrderBy(i => Math.Abs(desiredAspect - GetApsectRatio(i)))
  337. .ThenByDescending(GetSizeOrder)
  338. .ToList();
  339. var match = matches.FirstOrDefault();
  340. if (match == null)
  341. {
  342. return null;
  343. }
  344. var uri = match.uri;
  345. if (!string.IsNullOrWhiteSpace(uri))
  346. {
  347. if (uri.IndexOf("http", StringComparison.OrdinalIgnoreCase) != -1)
  348. {
  349. url = uri;
  350. }
  351. else
  352. {
  353. url = apiUrl + "/image/" + uri;
  354. }
  355. }
  356. //_logger.Debug("URL for image is : " + url);
  357. return url;
  358. }
  359. private double GetApsectRatio(ScheduleDirect.ImageData i)
  360. {
  361. int width = 0;
  362. int height = 0;
  363. if (!string.IsNullOrWhiteSpace(i.width))
  364. {
  365. int.TryParse(i.width, out width);
  366. }
  367. if (!string.IsNullOrWhiteSpace(i.height))
  368. {
  369. int.TryParse(i.height, out height);
  370. }
  371. if (height == 0 || width == 0)
  372. {
  373. return 0;
  374. }
  375. double result = width;
  376. result /= height;
  377. return result;
  378. }
  379. private async Task<List<ScheduleDirect.ShowImages>> GetImageForPrograms(
  380. ListingsProviderInfo info,
  381. List<string> programIds,
  382. CancellationToken cancellationToken)
  383. {
  384. if (programIds.Count == 0)
  385. {
  386. return new List<ScheduleDirect.ShowImages>();
  387. }
  388. var imageIdString = "[";
  389. foreach (var i in programIds)
  390. {
  391. var imageId = i.Substring(0, 10);
  392. if (!imageIdString.Contains(imageId))
  393. {
  394. imageIdString += "\"" + imageId + "\",";
  395. }
  396. }
  397. imageIdString = imageIdString.TrimEnd(',') + "]";
  398. var httpOptions = new HttpRequestOptions()
  399. {
  400. Url = ApiUrl + "/metadata/programs",
  401. UserAgent = UserAgent,
  402. CancellationToken = cancellationToken,
  403. RequestContent = imageIdString,
  404. LogErrorResponseBody = true,
  405. // The data can be large so give it some extra time
  406. TimeoutMs = 60000
  407. };
  408. try
  409. {
  410. using (var innerResponse2 = await Post(httpOptions, true, info).ConfigureAwait(false))
  411. {
  412. return _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.ShowImages>>(
  413. innerResponse2.Content);
  414. }
  415. }
  416. catch (Exception ex)
  417. {
  418. _logger.ErrorException("Error getting image info from schedules direct", ex);
  419. return new List<ScheduleDirect.ShowImages>();
  420. }
  421. }
  422. public async Task<List<NameIdPair>> GetHeadends(ListingsProviderInfo info, string country, string location, CancellationToken cancellationToken)
  423. {
  424. var token = await GetToken(info, cancellationToken);
  425. var lineups = new List<NameIdPair>();
  426. if (string.IsNullOrWhiteSpace(token))
  427. {
  428. return lineups;
  429. }
  430. var options = new HttpRequestOptions()
  431. {
  432. Url = ApiUrl + "/headends?country=" + country + "&postalcode=" + location,
  433. UserAgent = UserAgent,
  434. CancellationToken = cancellationToken,
  435. LogErrorResponseBody = true
  436. };
  437. options.RequestHeaders["token"] = token;
  438. try
  439. {
  440. using (Stream responce = await Get(options, false, info).ConfigureAwait(false))
  441. {
  442. var root = _jsonSerializer.DeserializeFromStream<List<ScheduleDirect.Headends>>(responce);
  443. if (root != null)
  444. {
  445. foreach (ScheduleDirect.Headends headend in root)
  446. {
  447. foreach (ScheduleDirect.Lineup lineup in headend.lineups)
  448. {
  449. lineups.Add(new NameIdPair
  450. {
  451. Name = string.IsNullOrWhiteSpace(lineup.name) ? lineup.lineup : lineup.name,
  452. Id = lineup.uri.Substring(18)
  453. });
  454. }
  455. }
  456. }
  457. else
  458. {
  459. _logger.Info("No lineups available");
  460. }
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. _logger.Error("Error getting headends", ex);
  466. }
  467. return lineups;
  468. }
  469. private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new ConcurrentDictionary<string, NameValuePair>();
  470. private DateTime _lastErrorResponse;
  471. private async Task<string> GetToken(ListingsProviderInfo info, CancellationToken cancellationToken)
  472. {
  473. var username = info.Username;
  474. // Reset the token if there's no username
  475. if (string.IsNullOrWhiteSpace(username))
  476. {
  477. return null;
  478. }
  479. var password = info.Password;
  480. if (string.IsNullOrWhiteSpace(password))
  481. {
  482. return null;
  483. }
  484. // Avoid hammering SD
  485. if ((DateTime.UtcNow - _lastErrorResponse).TotalMinutes < 1)
  486. {
  487. return null;
  488. }
  489. NameValuePair savedToken = null;
  490. if (!_tokens.TryGetValue(username, out savedToken))
  491. {
  492. savedToken = new NameValuePair();
  493. _tokens.TryAdd(username, savedToken);
  494. }
  495. if (!string.IsNullOrWhiteSpace(savedToken.Name) && !string.IsNullOrWhiteSpace(savedToken.Value))
  496. {
  497. long ticks;
  498. if (long.TryParse(savedToken.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out ticks))
  499. {
  500. // If it's under 24 hours old we can still use it
  501. if (DateTime.UtcNow.Ticks - ticks < TimeSpan.FromHours(20).Ticks)
  502. {
  503. return savedToken.Name;
  504. }
  505. }
  506. }
  507. await _tokenSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  508. try
  509. {
  510. var result = await GetTokenInternal(username, password, cancellationToken).ConfigureAwait(false);
  511. savedToken.Name = result;
  512. savedToken.Value = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  513. return result;
  514. }
  515. catch (HttpException ex)
  516. {
  517. if (ex.StatusCode.HasValue)
  518. {
  519. if ((int)ex.StatusCode.Value == 400)
  520. {
  521. _tokens.Clear();
  522. _lastErrorResponse = DateTime.UtcNow;
  523. }
  524. }
  525. throw;
  526. }
  527. finally
  528. {
  529. _tokenSemaphore.Release();
  530. }
  531. }
  532. private async Task<HttpResponseInfo> Post(HttpRequestOptions options,
  533. bool enableRetry,
  534. ListingsProviderInfo providerInfo)
  535. {
  536. try
  537. {
  538. return await _httpClient.Post(options).ConfigureAwait(false);
  539. }
  540. catch (HttpException ex)
  541. {
  542. _tokens.Clear();
  543. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  544. {
  545. enableRetry = false;
  546. }
  547. if (!enableRetry)
  548. {
  549. throw;
  550. }
  551. }
  552. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  553. options.RequestHeaders["token"] = newToken;
  554. return await Post(options, false, providerInfo).ConfigureAwait(false);
  555. }
  556. private async Task<Stream> Get(HttpRequestOptions options,
  557. bool enableRetry,
  558. ListingsProviderInfo providerInfo)
  559. {
  560. try
  561. {
  562. return await _httpClient.Get(options).ConfigureAwait(false);
  563. }
  564. catch (HttpException ex)
  565. {
  566. _tokens.Clear();
  567. if (!ex.StatusCode.HasValue || (int)ex.StatusCode.Value >= 500)
  568. {
  569. enableRetry = false;
  570. }
  571. if (!enableRetry)
  572. {
  573. throw;
  574. }
  575. }
  576. var newToken = await GetToken(providerInfo, options.CancellationToken).ConfigureAwait(false);
  577. options.RequestHeaders["token"] = newToken;
  578. return await Get(options, false, providerInfo).ConfigureAwait(false);
  579. }
  580. private async Task<string> GetTokenInternal(string username, string password,
  581. CancellationToken cancellationToken)
  582. {
  583. var httpOptions = new HttpRequestOptions()
  584. {
  585. Url = ApiUrl + "/token",
  586. UserAgent = UserAgent,
  587. RequestContent = "{\"username\":\"" + username + "\",\"password\":\"" + password + "\"}",
  588. CancellationToken = cancellationToken,
  589. LogErrorResponseBody = true
  590. };
  591. //_logger.Info("Obtaining token from Schedules Direct from addres: " + httpOptions.Url + " with body " +
  592. // httpOptions.RequestContent);
  593. using (var responce = await Post(httpOptions, false, null).ConfigureAwait(false))
  594. {
  595. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Token>(responce.Content);
  596. if (root.message == "OK")
  597. {
  598. _logger.Info("Authenticated with Schedules Direct token: " + root.token);
  599. return root.token;
  600. }
  601. throw new Exception("Could not authenticate with Schedules Direct Error: " + root.message);
  602. }
  603. }
  604. private async Task AddLineupToAccount(ListingsProviderInfo info, CancellationToken cancellationToken)
  605. {
  606. var token = await GetToken(info, cancellationToken);
  607. if (string.IsNullOrWhiteSpace(token))
  608. {
  609. throw new ArgumentException("Authentication required.");
  610. }
  611. if (string.IsNullOrWhiteSpace(info.ListingsId))
  612. {
  613. throw new ArgumentException("Listings Id required");
  614. }
  615. _logger.Info("Adding new LineUp ");
  616. var httpOptions = new HttpRequestOptions()
  617. {
  618. Url = ApiUrl + "/lineups/" + info.ListingsId,
  619. UserAgent = UserAgent,
  620. CancellationToken = cancellationToken,
  621. LogErrorResponseBody = true,
  622. BufferContent = false
  623. };
  624. httpOptions.RequestHeaders["token"] = token;
  625. using (var response = await _httpClient.SendAsync(httpOptions, "PUT"))
  626. {
  627. }
  628. }
  629. public string Name
  630. {
  631. get { return "Schedules Direct"; }
  632. }
  633. public static string TypeName = "SchedulesDirect";
  634. public string Type
  635. {
  636. get { return TypeName; }
  637. }
  638. private async Task<bool> HasLineup(ListingsProviderInfo info, CancellationToken cancellationToken)
  639. {
  640. if (string.IsNullOrWhiteSpace(info.ListingsId))
  641. {
  642. throw new ArgumentException("Listings Id required");
  643. }
  644. var token = await GetToken(info, cancellationToken);
  645. if (string.IsNullOrWhiteSpace(token))
  646. {
  647. throw new Exception("token required");
  648. }
  649. _logger.Info("Headends on account ");
  650. var options = new HttpRequestOptions()
  651. {
  652. Url = ApiUrl + "/lineups",
  653. UserAgent = UserAgent,
  654. CancellationToken = cancellationToken,
  655. LogErrorResponseBody = true
  656. };
  657. options.RequestHeaders["token"] = token;
  658. try
  659. {
  660. using (var response = await Get(options, false, null).ConfigureAwait(false))
  661. {
  662. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Lineups>(response);
  663. return root.lineups.Any(i => string.Equals(info.ListingsId, i.lineup, StringComparison.OrdinalIgnoreCase));
  664. }
  665. }
  666. catch (HttpException ex)
  667. {
  668. // Apparently we're supposed to swallow this
  669. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.BadRequest)
  670. {
  671. return false;
  672. }
  673. throw;
  674. }
  675. }
  676. public async Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings)
  677. {
  678. if (validateLogin)
  679. {
  680. if (string.IsNullOrWhiteSpace(info.Username))
  681. {
  682. throw new ArgumentException("Username is required");
  683. }
  684. if (string.IsNullOrWhiteSpace(info.Password))
  685. {
  686. throw new ArgumentException("Password is required");
  687. }
  688. }
  689. if (validateListings)
  690. {
  691. if (string.IsNullOrWhiteSpace(info.ListingsId))
  692. {
  693. throw new ArgumentException("Listings Id required");
  694. }
  695. var hasLineup = await HasLineup(info, CancellationToken.None).ConfigureAwait(false);
  696. if (!hasLineup)
  697. {
  698. await AddLineupToAccount(info, CancellationToken.None).ConfigureAwait(false);
  699. }
  700. }
  701. }
  702. public Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location)
  703. {
  704. return GetHeadends(info, country, location, CancellationToken.None);
  705. }
  706. public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken)
  707. {
  708. var listingsId = info.ListingsId;
  709. if (string.IsNullOrWhiteSpace(listingsId))
  710. {
  711. throw new Exception("ListingsId required");
  712. }
  713. var token = await GetToken(info, cancellationToken);
  714. if (string.IsNullOrWhiteSpace(token))
  715. {
  716. throw new Exception("token required");
  717. }
  718. var httpOptions = new HttpRequestOptions()
  719. {
  720. Url = ApiUrl + "/lineups/" + listingsId,
  721. UserAgent = UserAgent,
  722. CancellationToken = cancellationToken,
  723. LogErrorResponseBody = true,
  724. // The data can be large so give it some extra time
  725. TimeoutMs = 60000
  726. };
  727. httpOptions.RequestHeaders["token"] = token;
  728. var list = new List<ChannelInfo>();
  729. using (var response = await Get(httpOptions, true, info).ConfigureAwait(false))
  730. {
  731. var root = _jsonSerializer.DeserializeFromStream<ScheduleDirect.Channel>(response);
  732. _logger.Info("Found " + root.map.Count + " channels on the lineup on ScheduleDirect");
  733. _logger.Info("Mapping Stations to Channel");
  734. var allStations = root.stations ?? new List<ScheduleDirect.Station>();
  735. foreach (ScheduleDirect.Map map in root.map)
  736. {
  737. var channelNumber = GetChannelNumber(map);
  738. var station = allStations.FirstOrDefault(item => string.Equals(item.stationID, map.stationID, StringComparison.OrdinalIgnoreCase));
  739. if (station == null)
  740. {
  741. station = new ScheduleDirect.Station
  742. {
  743. stationID = map.stationID
  744. };
  745. }
  746. var name = channelNumber;
  747. var channelInfo = new ChannelInfo
  748. {
  749. Number = channelNumber,
  750. Name = name
  751. };
  752. if (station != null)
  753. {
  754. if (!string.IsNullOrWhiteSpace(station.name))
  755. {
  756. channelInfo.Name = station.name;
  757. }
  758. channelInfo.Id = station.stationID;
  759. channelInfo.CallSign = station.callsign;
  760. if (station.logo != null)
  761. {
  762. channelInfo.ImageUrl = station.logo.URL;
  763. channelInfo.HasImage = true;
  764. }
  765. }
  766. list.Add(channelInfo);
  767. }
  768. }
  769. return list;
  770. }
  771. private ScheduleDirect.Station GetStation(List<ScheduleDirect.Station> allStations, string channelNumber, string channelName)
  772. {
  773. if (!string.IsNullOrWhiteSpace(channelName))
  774. {
  775. channelName = NormalizeName(channelName);
  776. var result = allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.callsign ?? string.Empty), channelName, StringComparison.OrdinalIgnoreCase));
  777. if (result != null)
  778. {
  779. return result;
  780. }
  781. }
  782. if (!string.IsNullOrWhiteSpace(channelNumber))
  783. {
  784. return allStations.FirstOrDefault(i => string.Equals(NormalizeName(i.stationID ?? string.Empty), channelNumber, StringComparison.OrdinalIgnoreCase));
  785. }
  786. return null;
  787. }
  788. private string NormalizeName(string value)
  789. {
  790. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  791. }
  792. public class ScheduleDirect
  793. {
  794. public class Token
  795. {
  796. public int code { get; set; }
  797. public string message { get; set; }
  798. public string serverID { get; set; }
  799. public string token { get; set; }
  800. }
  801. public class Lineup
  802. {
  803. public string lineup { get; set; }
  804. public string name { get; set; }
  805. public string transport { get; set; }
  806. public string location { get; set; }
  807. public string uri { get; set; }
  808. }
  809. public class Lineups
  810. {
  811. public int code { get; set; }
  812. public string serverID { get; set; }
  813. public string datetime { get; set; }
  814. public List<Lineup> lineups { get; set; }
  815. }
  816. public class Headends
  817. {
  818. public string headend { get; set; }
  819. public string transport { get; set; }
  820. public string location { get; set; }
  821. public List<Lineup> lineups { get; set; }
  822. }
  823. public class Map
  824. {
  825. public string stationID { get; set; }
  826. public string channel { get; set; }
  827. public string logicalChannelNumber { get; set; }
  828. public int uhfVhf { get; set; }
  829. public int atscMajor { get; set; }
  830. public int atscMinor { get; set; }
  831. }
  832. public class Broadcaster
  833. {
  834. public string city { get; set; }
  835. public string state { get; set; }
  836. public string postalcode { get; set; }
  837. public string country { get; set; }
  838. }
  839. public class Logo
  840. {
  841. public string URL { get; set; }
  842. public int height { get; set; }
  843. public int width { get; set; }
  844. public string md5 { get; set; }
  845. }
  846. public class Station
  847. {
  848. public string stationID { get; set; }
  849. public string name { get; set; }
  850. public string callsign { get; set; }
  851. public List<string> broadcastLanguage { get; set; }
  852. public List<string> descriptionLanguage { get; set; }
  853. public Broadcaster broadcaster { get; set; }
  854. public string affiliate { get; set; }
  855. public Logo logo { get; set; }
  856. public bool? isCommercialFree { get; set; }
  857. }
  858. public class Metadata
  859. {
  860. public string lineup { get; set; }
  861. public string modified { get; set; }
  862. public string transport { get; set; }
  863. }
  864. public class Channel
  865. {
  866. public List<Map> map { get; set; }
  867. public List<Station> stations { get; set; }
  868. public Metadata metadata { get; set; }
  869. }
  870. public class RequestScheduleForChannel
  871. {
  872. public string stationID { get; set; }
  873. public List<string> date { get; set; }
  874. }
  875. public class Rating
  876. {
  877. public string body { get; set; }
  878. public string code { get; set; }
  879. }
  880. public class Multipart
  881. {
  882. public int partNumber { get; set; }
  883. public int totalParts { get; set; }
  884. }
  885. public class Program
  886. {
  887. public string programID { get; set; }
  888. public string airDateTime { get; set; }
  889. public int duration { get; set; }
  890. public string md5 { get; set; }
  891. public List<string> audioProperties { get; set; }
  892. public List<string> videoProperties { get; set; }
  893. public List<Rating> ratings { get; set; }
  894. public bool? @new { get; set; }
  895. public Multipart multipart { get; set; }
  896. }
  897. public class MetadataSchedule
  898. {
  899. public string modified { get; set; }
  900. public string md5 { get; set; }
  901. public string startDate { get; set; }
  902. public string endDate { get; set; }
  903. public int days { get; set; }
  904. }
  905. public class Day
  906. {
  907. public string stationID { get; set; }
  908. public List<Program> programs { get; set; }
  909. public MetadataSchedule metadata { get; set; }
  910. public Day()
  911. {
  912. programs = new List<Program>();
  913. }
  914. }
  915. //
  916. public class Title
  917. {
  918. public string title120 { get; set; }
  919. }
  920. public class EventDetails
  921. {
  922. public string subType { get; set; }
  923. }
  924. public class Description100
  925. {
  926. public string descriptionLanguage { get; set; }
  927. public string description { get; set; }
  928. }
  929. public class Description1000
  930. {
  931. public string descriptionLanguage { get; set; }
  932. public string description { get; set; }
  933. }
  934. public class DescriptionsProgram
  935. {
  936. public List<Description100> description100 { get; set; }
  937. public List<Description1000> description1000 { get; set; }
  938. }
  939. public class Gracenote
  940. {
  941. public int season { get; set; }
  942. public int episode { get; set; }
  943. }
  944. public class MetadataPrograms
  945. {
  946. public Gracenote Gracenote { get; set; }
  947. }
  948. public class ContentRating
  949. {
  950. public string body { get; set; }
  951. public string code { get; set; }
  952. }
  953. public class Cast
  954. {
  955. public string billingOrder { get; set; }
  956. public string role { get; set; }
  957. public string nameId { get; set; }
  958. public string personId { get; set; }
  959. public string name { get; set; }
  960. public string characterName { get; set; }
  961. }
  962. public class Crew
  963. {
  964. public string billingOrder { get; set; }
  965. public string role { get; set; }
  966. public string nameId { get; set; }
  967. public string personId { get; set; }
  968. public string name { get; set; }
  969. }
  970. public class QualityRating
  971. {
  972. public string ratingsBody { get; set; }
  973. public string rating { get; set; }
  974. public string minRating { get; set; }
  975. public string maxRating { get; set; }
  976. public string increment { get; set; }
  977. }
  978. public class Movie
  979. {
  980. public string year { get; set; }
  981. public int duration { get; set; }
  982. public List<QualityRating> qualityRating { get; set; }
  983. }
  984. public class Recommendation
  985. {
  986. public string programID { get; set; }
  987. public string title120 { get; set; }
  988. }
  989. public class ProgramDetails
  990. {
  991. public string audience { get; set; }
  992. public string programID { get; set; }
  993. public List<Title> titles { get; set; }
  994. public EventDetails eventDetails { get; set; }
  995. public DescriptionsProgram descriptions { get; set; }
  996. public string originalAirDate { get; set; }
  997. public List<string> genres { get; set; }
  998. public string episodeTitle150 { get; set; }
  999. public List<MetadataPrograms> metadata { get; set; }
  1000. public List<ContentRating> contentRating { get; set; }
  1001. public List<Cast> cast { get; set; }
  1002. public List<Crew> crew { get; set; }
  1003. public string showType { get; set; }
  1004. public bool hasImageArtwork { get; set; }
  1005. public string primaryImage { get; set; }
  1006. public string thumbImage { get; set; }
  1007. public string backdropImage { get; set; }
  1008. public string bannerImage { get; set; }
  1009. public string imageID { get; set; }
  1010. public string md5 { get; set; }
  1011. public List<string> contentAdvisory { get; set; }
  1012. public Movie movie { get; set; }
  1013. public List<Recommendation> recommendations { get; set; }
  1014. }
  1015. public class Caption
  1016. {
  1017. public string content { get; set; }
  1018. public string lang { get; set; }
  1019. }
  1020. public class ImageData
  1021. {
  1022. public string width { get; set; }
  1023. public string height { get; set; }
  1024. public string uri { get; set; }
  1025. public string size { get; set; }
  1026. public string aspect { get; set; }
  1027. public string category { get; set; }
  1028. public string text { get; set; }
  1029. public string primary { get; set; }
  1030. public string tier { get; set; }
  1031. public Caption caption { get; set; }
  1032. }
  1033. public class ShowImages
  1034. {
  1035. public string programID { get; set; }
  1036. public List<ImageData> data { get; set; }
  1037. }
  1038. }
  1039. }
  1040. }