RemoteSeriesProvider.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Extensions;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Net;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Xml;
  20. namespace MediaBrowser.Controller.Providers.TV
  21. {
  22. /// <summary>
  23. /// Class RemoteSeriesProvider
  24. /// </summary>
  25. class RemoteSeriesProvider : BaseMetadataProvider, IDisposable
  26. {
  27. private readonly IProviderManager _providerManager;
  28. /// <summary>
  29. /// The tv db
  30. /// </summary>
  31. internal readonly SemaphoreSlim TvDbResourcePool = new SemaphoreSlim(5, 5);
  32. internal static RemoteSeriesProvider Current { get; private set; }
  33. /// <summary>
  34. /// Gets the HTTP client.
  35. /// </summary>
  36. /// <value>The HTTP client.</value>
  37. protected IHttpClient HttpClient { get; private set; }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="RemoteSeriesProvider" /> class.
  40. /// </summary>
  41. /// <param name="httpClient">The HTTP client.</param>
  42. /// <param name="logManager">The log manager.</param>
  43. /// <param name="configurationManager">The configuration manager.</param>
  44. /// <param name="providerManager">The provider manager.</param>
  45. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  46. public RemoteSeriesProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  47. : base(logManager, configurationManager)
  48. {
  49. if (httpClient == null)
  50. {
  51. throw new ArgumentNullException("httpClient");
  52. }
  53. HttpClient = httpClient;
  54. _providerManager = providerManager;
  55. Current = this;
  56. }
  57. /// <summary>
  58. /// Releases unmanaged and - optionally - managed resources.
  59. /// </summary>
  60. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  61. protected virtual void Dispose(bool dispose)
  62. {
  63. if (dispose)
  64. {
  65. TvDbResourcePool.Dispose();
  66. }
  67. }
  68. /// <summary>
  69. /// The root URL
  70. /// </summary>
  71. private const string rootUrl = "http://www.thetvdb.com/api/";
  72. /// <summary>
  73. /// The series query
  74. /// </summary>
  75. private const string seriesQuery = "GetSeries.php?seriesname={0}";
  76. /// <summary>
  77. /// The series get
  78. /// </summary>
  79. private const string seriesGet = "http://www.thetvdb.com/api/{0}/series/{1}/{2}.xml";
  80. /// <summary>
  81. /// The get actors
  82. /// </summary>
  83. private const string getActors = "http://www.thetvdb.com/api/{0}/series/{1}/actors.xml";
  84. /// <summary>
  85. /// The LOCA l_ MET a_ FIL e_ NAME
  86. /// </summary>
  87. protected const string LOCAL_META_FILE_NAME = "Series.xml";
  88. /// <summary>
  89. /// Supportses the specified item.
  90. /// </summary>
  91. /// <param name="item">The item.</param>
  92. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  93. public override bool Supports(BaseItem item)
  94. {
  95. return item is Series;
  96. }
  97. /// <summary>
  98. /// Gets the priority.
  99. /// </summary>
  100. /// <value>The priority.</value>
  101. public override MetadataProviderPriority Priority
  102. {
  103. get { return MetadataProviderPriority.Second; }
  104. }
  105. /// <summary>
  106. /// Gets a value indicating whether [requires internet].
  107. /// </summary>
  108. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  109. public override bool RequiresInternet
  110. {
  111. get
  112. {
  113. return true;
  114. }
  115. }
  116. /// <summary>
  117. /// Needses the refresh internal.
  118. /// </summary>
  119. /// <param name="item">The item.</param>
  120. /// <param name="providerInfo">The provider info.</param>
  121. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  122. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  123. {
  124. var downloadDate = providerInfo.LastRefreshed;
  125. if (ConfigurationManager.Configuration.MetadataRefreshDays == -1 && downloadDate != DateTime.MinValue)
  126. {
  127. return false;
  128. }
  129. if (item.DontFetchMeta) return false;
  130. return !HasLocalMeta(item) && base.NeedsRefreshInternal(item, providerInfo);
  131. }
  132. /// <summary>
  133. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  134. /// </summary>
  135. /// <param name="item">The item.</param>
  136. /// <param name="force">if set to <c>true</c> [force].</param>
  137. /// <param name="cancellationToken">The cancellation token.</param>
  138. /// <returns>Task{System.Boolean}.</returns>
  139. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  140. {
  141. cancellationToken.ThrowIfCancellationRequested();
  142. var series = (Series)item;
  143. if (!item.DontFetchMeta && !HasLocalMeta(series))
  144. {
  145. var path = item.Path ?? "";
  146. var seriesId = Path.GetFileName(path).GetAttributeValue("tvdbid") ?? await GetSeriesId(series, cancellationToken);
  147. cancellationToken.ThrowIfCancellationRequested();
  148. var status = ProviderRefreshStatus.Success;
  149. if (!string.IsNullOrEmpty(seriesId))
  150. {
  151. series.SetProviderId(MetadataProviders.Tvdb, seriesId);
  152. status = await FetchSeriesData(series, seriesId, cancellationToken).ConfigureAwait(false);
  153. }
  154. SetLastRefreshed(item, DateTime.UtcNow, status);
  155. return true;
  156. }
  157. Logger.Info("Series provider not fetching because local meta exists or requested to ignore: " + item.Name);
  158. return false;
  159. }
  160. /// <summary>
  161. /// Fetches the series data.
  162. /// </summary>
  163. /// <param name="series">The series.</param>
  164. /// <param name="seriesId">The series id.</param>
  165. /// <param name="cancellationToken">The cancellation token.</param>
  166. /// <returns>Task{System.Boolean}.</returns>
  167. private async Task<ProviderRefreshStatus> FetchSeriesData(Series series, string seriesId, CancellationToken cancellationToken)
  168. {
  169. var status = ProviderRefreshStatus.Success;
  170. if (!string.IsNullOrEmpty(seriesId))
  171. {
  172. string url = string.Format(seriesGet, TVUtils.TvdbApiKey, seriesId, ConfigurationManager.Configuration.PreferredMetadataLanguage);
  173. var doc = new XmlDocument();
  174. using (var xml = await HttpClient.Get(new HttpRequestOptions
  175. {
  176. Url = url,
  177. ResourcePool = TvDbResourcePool,
  178. CancellationToken = cancellationToken,
  179. EnableResponseCache = true
  180. }).ConfigureAwait(false))
  181. {
  182. doc.Load(xml);
  183. }
  184. if (doc.HasChildNodes)
  185. {
  186. //kick off the actor and image fetch simultaneously
  187. var actorTask = FetchActors(series, seriesId, doc, cancellationToken);
  188. var imageTask = FetchImages(series, seriesId, cancellationToken);
  189. series.Name = doc.SafeGetString("//SeriesName");
  190. series.Overview = doc.SafeGetString("//Overview");
  191. series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
  192. series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
  193. series.AirTime = doc.SafeGetString("//Airs_Time");
  194. string n = doc.SafeGetString("//banner");
  195. if (!string.IsNullOrWhiteSpace(n))
  196. {
  197. series.SetImage(ImageType.Banner, await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n, "banner" + Path.GetExtension(n), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  198. }
  199. string s = doc.SafeGetString("//Network");
  200. if (!string.IsNullOrWhiteSpace(s))
  201. {
  202. series.Studios.Clear();
  203. foreach (var studio in s.Trim().Split('|'))
  204. {
  205. series.AddStudio(studio);
  206. }
  207. }
  208. series.OfficialRating = doc.SafeGetString("//ContentRating");
  209. string g = doc.SafeGetString("//Genre");
  210. if (g != null)
  211. {
  212. string[] genres = g.Trim('|').Split('|');
  213. if (g.Length > 0)
  214. {
  215. series.Genres.Clear();
  216. foreach (var genre in genres)
  217. {
  218. series.AddGenre(genre);
  219. }
  220. }
  221. }
  222. try
  223. {
  224. //wait for other tasks
  225. await Task.WhenAll(actorTask, imageTask).ConfigureAwait(false);
  226. }
  227. catch (HttpException)
  228. {
  229. status = ProviderRefreshStatus.CompletedWithErrors;
  230. }
  231. if (ConfigurationManager.Configuration.SaveLocalMeta)
  232. {
  233. var ms = new MemoryStream();
  234. doc.Save(ms);
  235. await _providerManager.SaveToLibraryFilesystem(series, Path.Combine(series.MetaLocation, LOCAL_META_FILE_NAME), ms, cancellationToken).ConfigureAwait(false);
  236. }
  237. }
  238. }
  239. return status;
  240. }
  241. /// <summary>
  242. /// Fetches the actors.
  243. /// </summary>
  244. /// <param name="series">The series.</param>
  245. /// <param name="seriesId">The series id.</param>
  246. /// <param name="doc">The doc.</param>
  247. /// <param name="cancellationToken">The cancellation token.</param>
  248. /// <returns>Task.</returns>
  249. private async Task FetchActors(Series series, string seriesId, XmlDocument doc, CancellationToken cancellationToken)
  250. {
  251. string urlActors = string.Format(getActors, TVUtils.TvdbApiKey, seriesId);
  252. var docActors = new XmlDocument();
  253. using (var actors = await HttpClient.Get(new HttpRequestOptions
  254. {
  255. Url = urlActors,
  256. ResourcePool = TvDbResourcePool,
  257. CancellationToken = cancellationToken,
  258. EnableResponseCache = true
  259. }).ConfigureAwait(false))
  260. {
  261. docActors.Load(actors);
  262. }
  263. if (docActors.HasChildNodes)
  264. {
  265. XmlNode actorsNode = null;
  266. if (ConfigurationManager.Configuration.SaveLocalMeta)
  267. {
  268. //add to the main doc for saving
  269. var seriesNode = doc.SelectSingleNode("//Series");
  270. if (seriesNode != null)
  271. {
  272. actorsNode = doc.CreateNode(XmlNodeType.Element, "Persons", null);
  273. seriesNode.AppendChild(actorsNode);
  274. }
  275. }
  276. var xmlNodeList = docActors.SelectNodes("Actors/Actor");
  277. if (xmlNodeList != null)
  278. {
  279. series.People.Clear();
  280. foreach (XmlNode p in xmlNodeList)
  281. {
  282. string actorName = p.SafeGetString("Name");
  283. string actorRole = p.SafeGetString("Role");
  284. if (!string.IsNullOrWhiteSpace(actorName))
  285. {
  286. series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName, Role = actorRole });
  287. if (ConfigurationManager.Configuration.SaveLocalMeta && actorsNode != null)
  288. {
  289. //create in main doc
  290. var personNode = doc.CreateNode(XmlNodeType.Element, "Person", null);
  291. foreach (XmlNode subNode in p.ChildNodes)
  292. personNode.AppendChild(doc.ImportNode(subNode, true));
  293. //need to add the type
  294. var typeNode = doc.CreateNode(XmlNodeType.Element, "Type", null);
  295. typeNode.InnerText = PersonType.Actor;
  296. personNode.AppendChild(typeNode);
  297. actorsNode.AppendChild(personNode);
  298. }
  299. }
  300. }
  301. }
  302. }
  303. }
  304. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  305. /// <summary>
  306. /// Fetches the images.
  307. /// </summary>
  308. /// <param name="series">The series.</param>
  309. /// <param name="seriesId">The series id.</param>
  310. /// <param name="cancellationToken">The cancellation token.</param>
  311. /// <returns>Task.</returns>
  312. private async Task FetchImages(Series series, string seriesId, CancellationToken cancellationToken)
  313. {
  314. if ((!string.IsNullOrEmpty(seriesId)) && ((series.PrimaryImagePath == null) || (series.BackdropImagePaths == null)))
  315. {
  316. string url = string.Format("http://www.thetvdb.com/api/" + TVUtils.TvdbApiKey + "/series/{0}/banners.xml", seriesId);
  317. var images = new XmlDocument();
  318. using (var imgs = await HttpClient.Get(new HttpRequestOptions
  319. {
  320. Url = url,
  321. ResourcePool = TvDbResourcePool,
  322. CancellationToken = cancellationToken,
  323. EnableResponseCache = true
  324. }).ConfigureAwait(false))
  325. {
  326. images.Load(imgs);
  327. }
  328. if (images.HasChildNodes)
  329. {
  330. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("folder"))
  331. {
  332. var n = images.SelectSingleNode("//Banner[BannerType='poster']");
  333. if (n != null)
  334. {
  335. n = n.SelectSingleNode("./BannerPath");
  336. if (n != null)
  337. {
  338. series.PrimaryImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "folder" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false);
  339. }
  340. }
  341. }
  342. if (ConfigurationManager.Configuration.DownloadSeriesImages.Banner && (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage("banner")))
  343. {
  344. var n = images.SelectSingleNode("//Banner[BannerType='series']");
  345. if (n != null)
  346. {
  347. n = n.SelectSingleNode("./BannerPath");
  348. if (n != null)
  349. {
  350. var bannerImagePath = await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + n.InnerText, "banner" + Path.GetExtension(n.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken);
  351. series.SetImage(ImageType.Banner, bannerImagePath);
  352. }
  353. }
  354. }
  355. var bdNo = 0;
  356. var xmlNodeList = images.SelectNodes("//Banner[BannerType='fanart']");
  357. if (xmlNodeList != null)
  358. foreach (XmlNode b in xmlNodeList)
  359. {
  360. series.BackdropImagePaths = new List<string>();
  361. var p = b.SelectSingleNode("./BannerPath");
  362. if (p != null)
  363. {
  364. var bdName = "backdrop" + (bdNo > 0 ? bdNo.ToString(UsCulture) : "");
  365. if (ConfigurationManager.Configuration.RefreshItemImages || !series.HasLocalImage(bdName))
  366. {
  367. series.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(series, TVUtils.BannerUrl + p.InnerText, bdName + Path.GetExtension(p.InnerText), ConfigurationManager.Configuration.SaveLocalMeta, TvDbResourcePool, cancellationToken).ConfigureAwait(false));
  368. }
  369. bdNo++;
  370. if (bdNo >= ConfigurationManager.Configuration.MaxBackdrops) break;
  371. }
  372. }
  373. }
  374. }
  375. }
  376. /// <summary>
  377. /// Determines whether [has local meta] [the specified item].
  378. /// </summary>
  379. /// <param name="item">The item.</param>
  380. /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
  381. private bool HasLocalMeta(BaseItem item)
  382. {
  383. return item.ResolveArgs.ContainsMetaFileByName(LOCAL_META_FILE_NAME);
  384. }
  385. /// <summary>
  386. /// Gets the series id.
  387. /// </summary>
  388. /// <param name="item">The item.</param>
  389. /// <param name="cancellationToken">The cancellation token.</param>
  390. /// <returns>Task{System.String}.</returns>
  391. private async Task<string> GetSeriesId(BaseItem item, CancellationToken cancellationToken)
  392. {
  393. var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
  394. if (string.IsNullOrEmpty(seriesId))
  395. {
  396. seriesId = await FindSeries(item.Name, cancellationToken).ConfigureAwait(false);
  397. }
  398. return seriesId;
  399. }
  400. /// <summary>
  401. /// Finds the series.
  402. /// </summary>
  403. /// <param name="name">The name.</param>
  404. /// <param name="cancellationToken">The cancellation token.</param>
  405. /// <returns>Task{System.String}.</returns>
  406. public async Task<string> FindSeries(string name, CancellationToken cancellationToken)
  407. {
  408. //nope - search for it
  409. string url = string.Format(rootUrl + seriesQuery, WebUtility.UrlEncode(name));
  410. var doc = new XmlDocument();
  411. using (var results = await HttpClient.Get(new HttpRequestOptions
  412. {
  413. Url = url,
  414. ResourcePool = TvDbResourcePool,
  415. CancellationToken = cancellationToken,
  416. EnableResponseCache = true
  417. }).ConfigureAwait(false))
  418. {
  419. doc.Load(results);
  420. }
  421. if (doc.HasChildNodes)
  422. {
  423. XmlNodeList nodes = doc.SelectNodes("//Series");
  424. string comparableName = GetComparableName(name);
  425. if (nodes != null)
  426. foreach (XmlNode node in nodes)
  427. {
  428. var n = node.SelectSingleNode("./SeriesName");
  429. if (n != null && GetComparableName(n.InnerText) == comparableName)
  430. {
  431. n = node.SelectSingleNode("./seriesid");
  432. if (n != null)
  433. return n.InnerText;
  434. }
  435. else
  436. {
  437. if (n != null)
  438. Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
  439. }
  440. }
  441. }
  442. Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
  443. return null;
  444. }
  445. /// <summary>
  446. /// The remove
  447. /// </summary>
  448. const string remove = "\"'!`?";
  449. /// <summary>
  450. /// The spacers
  451. /// </summary>
  452. const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  453. /// <summary>
  454. /// Gets the name of the comparable.
  455. /// </summary>
  456. /// <param name="name">The name.</param>
  457. /// <returns>System.String.</returns>
  458. internal static string GetComparableName(string name)
  459. {
  460. name = name.ToLower();
  461. name = name.Normalize(NormalizationForm.FormKD);
  462. var sb = new StringBuilder();
  463. foreach (var c in name)
  464. {
  465. if ((int)c >= 0x2B0 && (int)c <= 0x0333)
  466. {
  467. // skip char modifier and diacritics
  468. }
  469. else if (remove.IndexOf(c) > -1)
  470. {
  471. // skip chars we are removing
  472. }
  473. else if (spacers.IndexOf(c) > -1)
  474. {
  475. sb.Append(" ");
  476. }
  477. else if (c == '&')
  478. {
  479. sb.Append(" and ");
  480. }
  481. else
  482. {
  483. sb.Append(c);
  484. }
  485. }
  486. name = sb.ToString();
  487. name = name.Replace(", the", "");
  488. name = name.Replace("the ", " ");
  489. name = name.Replace(" the ", " ");
  490. string prevName;
  491. do
  492. {
  493. prevName = name;
  494. name = name.Replace(" ", " ");
  495. } while (name.Length != prevName.Length);
  496. return name.Trim();
  497. }
  498. public void Dispose()
  499. {
  500. Dispose(true);
  501. }
  502. }
  503. }