RemoteSeriesProvider.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. using MediaBrowser.Common.Configuration;
  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.Library;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Providers.Extensions;
  12. using System;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Xml;
  21. using System.Xml.Linq;
  22. namespace MediaBrowser.Providers.TV
  23. {
  24. /// <summary>
  25. /// Class RemoteSeriesProvider
  26. /// </summary>
  27. class RemoteSeriesProvider : BaseMetadataProvider, IDisposable
  28. {
  29. /// <summary>
  30. /// The tv db
  31. /// </summary>
  32. internal readonly SemaphoreSlim TvDbResourcePool = new SemaphoreSlim(2, 2);
  33. /// <summary>
  34. /// Gets the current.
  35. /// </summary>
  36. /// <value>The current.</value>
  37. internal static RemoteSeriesProvider Current { get; private set; }
  38. /// <summary>
  39. /// The _zip client
  40. /// </summary>
  41. private readonly IZipClient _zipClient;
  42. /// <summary>
  43. /// Gets the HTTP client.
  44. /// </summary>
  45. /// <value>The HTTP client.</value>
  46. protected IHttpClient HttpClient { get; private set; }
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="RemoteSeriesProvider" /> class.
  49. /// </summary>
  50. /// <param name="httpClient">The HTTP client.</param>
  51. /// <param name="logManager">The log manager.</param>
  52. /// <param name="configurationManager">The configuration manager.</param>
  53. /// <param name="zipClient">The zip client.</param>
  54. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  55. public RemoteSeriesProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IZipClient zipClient)
  56. : base(logManager, configurationManager)
  57. {
  58. if (httpClient == null)
  59. {
  60. throw new ArgumentNullException("httpClient");
  61. }
  62. HttpClient = httpClient;
  63. _zipClient = zipClient;
  64. Current = this;
  65. }
  66. /// <summary>
  67. /// Releases unmanaged and - optionally - managed resources.
  68. /// </summary>
  69. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  70. protected virtual void Dispose(bool dispose)
  71. {
  72. if (dispose)
  73. {
  74. TvDbResourcePool.Dispose();
  75. }
  76. }
  77. /// <summary>
  78. /// The root URL
  79. /// </summary>
  80. private const string RootUrl = "http://www.thetvdb.com/api/";
  81. /// <summary>
  82. /// The series query
  83. /// </summary>
  84. private const string SeriesQuery = "GetSeries.php?seriesname={0}";
  85. /// <summary>
  86. /// The series get zip
  87. /// </summary>
  88. private const string SeriesGetZip = "http://www.thetvdb.com/api/{0}/series/{1}/all/{2}.zip";
  89. /// <summary>
  90. /// The LOCA l_ MET a_ FIL e_ NAME
  91. /// </summary>
  92. protected const string LocalMetaFileName = "series.xml";
  93. /// <summary>
  94. /// Supportses the specified item.
  95. /// </summary>
  96. /// <param name="item">The item.</param>
  97. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  98. public override bool Supports(BaseItem item)
  99. {
  100. return item is Series;
  101. }
  102. /// <summary>
  103. /// Gets the priority.
  104. /// </summary>
  105. /// <value>The priority.</value>
  106. public override MetadataProviderPriority Priority
  107. {
  108. get { return MetadataProviderPriority.Second; }
  109. }
  110. /// <summary>
  111. /// Gets a value indicating whether [requires internet].
  112. /// </summary>
  113. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  114. public override bool RequiresInternet
  115. {
  116. get
  117. {
  118. return true;
  119. }
  120. }
  121. /// <summary>
  122. /// Gets a value indicating whether [refresh on version change].
  123. /// </summary>
  124. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  125. protected override bool RefreshOnVersionChange
  126. {
  127. get
  128. {
  129. return true;
  130. }
  131. }
  132. /// <summary>
  133. /// Gets the provider version.
  134. /// </summary>
  135. /// <value>The provider version.</value>
  136. protected override string ProviderVersion
  137. {
  138. get
  139. {
  140. return "1";
  141. }
  142. }
  143. protected override DateTime CompareDate(BaseItem item)
  144. {
  145. var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
  146. if (!string.IsNullOrEmpty(seriesId))
  147. {
  148. // Process images
  149. var path = GetSeriesDataPath(ConfigurationManager.ApplicationPaths, seriesId);
  150. var files = new DirectoryInfo(path)
  151. .EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly)
  152. .Select(i => i.LastWriteTimeUtc)
  153. .ToArray();
  154. if (files.Length > 0)
  155. {
  156. return files.Max();
  157. }
  158. }
  159. return base.CompareDate(item);
  160. }
  161. /// <summary>
  162. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  163. /// </summary>
  164. /// <param name="item">The item.</param>
  165. /// <param name="force">if set to <c>true</c> [force].</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task{System.Boolean}.</returns>
  168. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  169. {
  170. cancellationToken.ThrowIfCancellationRequested();
  171. var series = (Series)item;
  172. var seriesId = series.GetProviderId(MetadataProviders.Tvdb);
  173. if (string.IsNullOrEmpty(seriesId))
  174. {
  175. seriesId = await FindSeries(series.Name, cancellationToken).ConfigureAwait(false);
  176. }
  177. cancellationToken.ThrowIfCancellationRequested();
  178. if (!string.IsNullOrEmpty(seriesId))
  179. {
  180. series.SetProviderId(MetadataProviders.Tvdb, seriesId);
  181. var seriesDataPath = GetSeriesDataPath(ConfigurationManager.ApplicationPaths, seriesId);
  182. await FetchSeriesData(series, seriesId, seriesDataPath, force, cancellationToken).ConfigureAwait(false);
  183. }
  184. SetLastRefreshed(item, DateTime.UtcNow);
  185. return true;
  186. }
  187. /// <summary>
  188. /// Fetches the series data.
  189. /// </summary>
  190. /// <param name="series">The series.</param>
  191. /// <param name="seriesId">The series id.</param>
  192. /// <param name="seriesDataPath">The series data path.</param>
  193. /// <param name="isForcedRefresh">if set to <c>true</c> [is forced refresh].</param>
  194. /// <param name="cancellationToken">The cancellation token.</param>
  195. /// <returns>Task{System.Boolean}.</returns>
  196. private async Task FetchSeriesData(Series series, string seriesId, string seriesDataPath, bool isForcedRefresh, CancellationToken cancellationToken)
  197. {
  198. var files = Directory.EnumerateFiles(seriesDataPath, "*.xml", SearchOption.TopDirectoryOnly).Select(Path.GetFileName).ToArray();
  199. var seriesXmlFilename = ConfigurationManager.Configuration.PreferredMetadataLanguage.ToLower() + ".xml";
  200. // Only download if not already there
  201. // The prescan task will take care of updates so we don't need to re-download here
  202. if (!files.Contains("banners.xml", StringComparer.OrdinalIgnoreCase) || !files.Contains("actors.xml", StringComparer.OrdinalIgnoreCase) || !files.Contains(seriesXmlFilename, StringComparer.OrdinalIgnoreCase))
  203. {
  204. await DownloadSeriesZip(seriesId, seriesDataPath, cancellationToken).ConfigureAwait(false);
  205. }
  206. // Examine if there's no local metadata, or save local is on (to get updates)
  207. if (isForcedRefresh || ConfigurationManager.Configuration.EnableTvDbUpdates || !HasLocalMeta(series))
  208. {
  209. var seriesXmlPath = Path.Combine(seriesDataPath, seriesXmlFilename);
  210. var actorsXmlPath = Path.Combine(seriesDataPath, "actors.xml");
  211. var seriesDoc = new XmlDocument();
  212. seriesDoc.Load(seriesXmlPath);
  213. FetchMainInfo(series, seriesDoc);
  214. if (!series.LockedFields.Contains(MetadataFields.Cast))
  215. {
  216. var actorsDoc = new XmlDocument();
  217. actorsDoc.Load(actorsXmlPath);
  218. FetchActors(series, actorsDoc, seriesDoc);
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Downloads the series zip.
  224. /// </summary>
  225. /// <param name="seriesId">The series id.</param>
  226. /// <param name="seriesDataPath">The series data path.</param>
  227. /// <param name="cancellationToken">The cancellation token.</param>
  228. /// <returns>Task.</returns>
  229. internal async Task DownloadSeriesZip(string seriesId, string seriesDataPath, CancellationToken cancellationToken)
  230. {
  231. var url = string.Format(SeriesGetZip, TVUtils.TvdbApiKey, seriesId, ConfigurationManager.Configuration.PreferredMetadataLanguage);
  232. using (var zipStream = await HttpClient.Get(new HttpRequestOptions
  233. {
  234. Url = url,
  235. ResourcePool = TvDbResourcePool,
  236. CancellationToken = cancellationToken
  237. }).ConfigureAwait(false))
  238. {
  239. // Copy to memory stream because we need a seekable stream
  240. using (var ms = new MemoryStream())
  241. {
  242. await zipStream.CopyToAsync(ms).ConfigureAwait(false);
  243. ms.Position = 0;
  244. _zipClient.ExtractAll(ms, seriesDataPath, true);
  245. }
  246. }
  247. }
  248. /// <summary>
  249. /// Gets the series data path.
  250. /// </summary>
  251. /// <param name="appPaths">The app paths.</param>
  252. /// <param name="seriesId">The series id.</param>
  253. /// <returns>System.String.</returns>
  254. internal static string GetSeriesDataPath(IApplicationPaths appPaths, string seriesId)
  255. {
  256. var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
  257. if (!Directory.Exists(seriesDataPath))
  258. {
  259. Directory.CreateDirectory(seriesDataPath);
  260. }
  261. return seriesDataPath;
  262. }
  263. /// <summary>
  264. /// Gets the series data path.
  265. /// </summary>
  266. /// <param name="appPaths">The app paths.</param>
  267. /// <returns>System.String.</returns>
  268. internal static string GetSeriesDataPath(IApplicationPaths appPaths)
  269. {
  270. var dataPath = Path.Combine(appPaths.DataPath, "tvdb");
  271. if (!Directory.Exists(dataPath))
  272. {
  273. Directory.CreateDirectory(dataPath);
  274. }
  275. return dataPath;
  276. }
  277. /// <summary>
  278. /// Fetches the main info.
  279. /// </summary>
  280. /// <param name="series">The series.</param>
  281. /// <param name="doc">The doc.</param>
  282. private void FetchMainInfo(Series series, XmlDocument doc)
  283. {
  284. if (!series.LockedFields.Contains(MetadataFields.Name))
  285. {
  286. series.Name = doc.SafeGetString("//SeriesName");
  287. }
  288. if (!series.LockedFields.Contains(MetadataFields.Overview))
  289. {
  290. series.Overview = doc.SafeGetString("//Overview");
  291. }
  292. var imdbId = doc.SafeGetString("//IMDB_ID");
  293. if (!string.IsNullOrWhiteSpace(imdbId))
  294. {
  295. series.SetProviderId(MetadataProviders.Imdb, imdbId);
  296. }
  297. var zap2ItId = doc.SafeGetString("//zap2it_id");
  298. if (!string.IsNullOrWhiteSpace(zap2ItId))
  299. {
  300. series.SetProviderId(MetadataProviders.Zap2It, zap2ItId);
  301. }
  302. // Only fill this if it doesn't already have a value, since we get it from imdb which has better data
  303. if (!series.CommunityRating.HasValue || string.IsNullOrWhiteSpace(series.GetProviderId(MetadataProviders.Imdb)))
  304. {
  305. series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
  306. }
  307. series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
  308. series.AirTime = doc.SafeGetString("//Airs_Time");
  309. SeriesStatus seriesStatus;
  310. if(Enum.TryParse(doc.SafeGetString("//Status"), true, out seriesStatus))
  311. series.Status = seriesStatus;
  312. series.PremiereDate = doc.SafeGetDateTime("//FirstAired");
  313. if (series.PremiereDate.HasValue)
  314. series.ProductionYear = series.PremiereDate.Value.Year;
  315. series.RunTimeTicks = TimeSpan.FromMinutes(doc.SafeGetInt32("//Runtime")).Ticks;
  316. if (!series.LockedFields.Contains(MetadataFields.Studios))
  317. {
  318. string s = doc.SafeGetString("//Network");
  319. if (!string.IsNullOrWhiteSpace(s))
  320. {
  321. series.Studios.Clear();
  322. foreach (var studio in s.Trim().Split('|'))
  323. {
  324. series.AddStudio(studio);
  325. }
  326. }
  327. }
  328. series.OfficialRating = doc.SafeGetString("//ContentRating");
  329. if (!series.LockedFields.Contains(MetadataFields.Genres))
  330. {
  331. string g = doc.SafeGetString("//Genre");
  332. if (g != null)
  333. {
  334. string[] genres = g.Trim('|').Split('|');
  335. if (g.Length > 0)
  336. {
  337. series.Genres.Clear();
  338. foreach (var genre in genres)
  339. {
  340. series.AddGenre(genre);
  341. }
  342. }
  343. }
  344. }
  345. if (series.Status == SeriesStatus.Ended) {
  346. var document = XDocument.Load(new XmlNodeReader(doc));
  347. var dates = document.Descendants("Episode").Where(x => {
  348. var seasonNumber = x.Element("SeasonNumber");
  349. var firstAired = x.Element("FirstAired");
  350. return firstAired != null && seasonNumber != null && (!string.IsNullOrEmpty(seasonNumber.Value) && seasonNumber.Value != "0") && !string.IsNullOrEmpty(firstAired.Value);
  351. }).Select(x => {
  352. DateTime? date = null;
  353. DateTime tempDate;
  354. var firstAired = x.Element("FirstAired");
  355. if (firstAired != null && DateTime.TryParse(firstAired.Value, out tempDate))
  356. {
  357. date = tempDate;
  358. }
  359. return date;
  360. }).ToList();
  361. if(dates.Any(x=>x.HasValue))
  362. series.EndDate = dates.Where(x => x.HasValue).Max();
  363. }
  364. }
  365. /// <summary>
  366. /// Fetches the actors.
  367. /// </summary>
  368. /// <param name="series">The series.</param>
  369. /// <param name="actorsDoc">The actors doc.</param>
  370. /// <param name="seriesDoc">The seriesDoc.</param>
  371. /// <returns>Task.</returns>
  372. private void FetchActors(Series series, XmlDocument actorsDoc, XmlDocument seriesDoc)
  373. {
  374. var xmlNodeList = actorsDoc.SelectNodes("Actors/Actor");
  375. if (xmlNodeList != null)
  376. {
  377. series.People.Clear();
  378. foreach (XmlNode p in xmlNodeList)
  379. {
  380. string actorName = p.SafeGetString("Name");
  381. string actorRole = p.SafeGetString("Role");
  382. if (!string.IsNullOrWhiteSpace(actorName))
  383. {
  384. // Sometimes tvdb actors have leading spaces
  385. series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName.Trim(), Role = actorRole });
  386. }
  387. }
  388. }
  389. }
  390. /// <summary>
  391. /// The us culture
  392. /// </summary>
  393. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  394. /// <summary>
  395. /// Determines whether [has local meta] [the specified item].
  396. /// </summary>
  397. /// <param name="item">The item.</param>
  398. /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
  399. private bool HasLocalMeta(BaseItem item)
  400. {
  401. return item.ResolveArgs.ContainsMetaFileByName(LocalMetaFileName);
  402. }
  403. /// <summary>
  404. /// Finds the series.
  405. /// </summary>
  406. /// <param name="name">The name.</param>
  407. /// <param name="cancellationToken">The cancellation token.</param>
  408. /// <returns>Task{System.String}.</returns>
  409. private async Task<string> FindSeries(string name, CancellationToken cancellationToken)
  410. {
  411. var url = string.Format(RootUrl + SeriesQuery, WebUtility.UrlEncode(name));
  412. var doc = new XmlDocument();
  413. using (var results = await HttpClient.Get(new HttpRequestOptions
  414. {
  415. Url = url,
  416. ResourcePool = TvDbResourcePool,
  417. CancellationToken = cancellationToken
  418. }).ConfigureAwait(false))
  419. {
  420. doc.Load(results);
  421. }
  422. if (doc.HasChildNodes)
  423. {
  424. var nodes = doc.SelectNodes("//Series");
  425. var comparableName = GetComparableName(name);
  426. if (nodes != null)
  427. foreach (XmlNode node in nodes)
  428. {
  429. var n = node.SelectSingleNode("./SeriesName");
  430. if (n != null && string.Equals(GetComparableName(n.InnerText), comparableName, StringComparison.OrdinalIgnoreCase))
  431. {
  432. n = node.SelectSingleNode("./seriesid");
  433. if (n != null)
  434. return n.InnerText;
  435. }
  436. else
  437. {
  438. if (n != null)
  439. Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
  440. }
  441. }
  442. }
  443. // Try stripping off the year if it was supplied
  444. var parenthIndex = name.LastIndexOf('(');
  445. if (parenthIndex != -1)
  446. {
  447. var newName = name.Substring(0, parenthIndex);
  448. return await FindSeries(newName, cancellationToken);
  449. }
  450. Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
  451. return null;
  452. }
  453. /// <summary>
  454. /// The remove
  455. /// </summary>
  456. const string remove = "\"'!`?";
  457. /// <summary>
  458. /// The spacers
  459. /// </summary>
  460. const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  461. /// <summary>
  462. /// Gets the name of the comparable.
  463. /// </summary>
  464. /// <param name="name">The name.</param>
  465. /// <returns>System.String.</returns>
  466. internal static string GetComparableName(string name)
  467. {
  468. name = name.ToLower();
  469. name = name.Normalize(NormalizationForm.FormKD);
  470. var sb = new StringBuilder();
  471. foreach (var c in name)
  472. {
  473. if ((int)c >= 0x2B0 && (int)c <= 0x0333)
  474. {
  475. // skip char modifier and diacritics
  476. }
  477. else if (remove.IndexOf(c) > -1)
  478. {
  479. // skip chars we are removing
  480. }
  481. else if (spacers.IndexOf(c) > -1)
  482. {
  483. sb.Append(" ");
  484. }
  485. else if (c == '&')
  486. {
  487. sb.Append(" and ");
  488. }
  489. else
  490. {
  491. sb.Append(c);
  492. }
  493. }
  494. name = sb.ToString();
  495. name = name.Replace(", the", "");
  496. name = name.Replace("the ", " ");
  497. name = name.Replace(" the ", " ");
  498. string prevName;
  499. do
  500. {
  501. prevName = name;
  502. name = name.Replace(" ", " ");
  503. } while (name.Length != prevName.Length);
  504. return name.Trim();
  505. }
  506. /// <summary>
  507. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  508. /// </summary>
  509. public void Dispose()
  510. {
  511. Dispose(true);
  512. }
  513. }
  514. }