SchedulesDirect.cs 48 KB

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