SchedulesDirect.cs 39 KB

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