RemoteSeriesProvider.cs 24 KB

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