SchedulesDirect.cs 48 KB

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