SchedulesDirect.cs 46 KB

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