RemoteSeriesProvider.cs 22 KB

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