RemoteSeriesProvider.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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 GetSeriesId(series, cancellationToken);
  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. series.CommunityRating = doc.SafeGetSingle("//Rating", 0, 10);
  293. series.AirDays = TVUtils.GetAirDays(doc.SafeGetString("//Airs_DayOfWeek"));
  294. series.AirTime = doc.SafeGetString("//Airs_Time");
  295. SeriesStatus seriesStatus;
  296. if(Enum.TryParse(doc.SafeGetString("//Status"), true, out seriesStatus))
  297. series.Status = seriesStatus;
  298. series.PremiereDate = doc.SafeGetDateTime("//FirstAired");
  299. if (series.PremiereDate.HasValue)
  300. series.ProductionYear = series.PremiereDate.Value.Year;
  301. series.RunTimeTicks = TimeSpan.FromMinutes(doc.SafeGetInt32("//Runtime")).Ticks;
  302. if (!series.LockedFields.Contains(MetadataFields.Studios))
  303. {
  304. string s = doc.SafeGetString("//Network");
  305. if (!string.IsNullOrWhiteSpace(s))
  306. {
  307. series.Studios.Clear();
  308. foreach (var studio in s.Trim().Split('|'))
  309. {
  310. series.AddStudio(studio);
  311. }
  312. }
  313. }
  314. series.OfficialRating = doc.SafeGetString("//ContentRating");
  315. if (!series.LockedFields.Contains(MetadataFields.Genres))
  316. {
  317. string g = doc.SafeGetString("//Genre");
  318. if (g != null)
  319. {
  320. string[] genres = g.Trim('|').Split('|');
  321. if (g.Length > 0)
  322. {
  323. series.Genres.Clear();
  324. foreach (var genre in genres)
  325. {
  326. series.AddGenre(genre);
  327. }
  328. }
  329. }
  330. }
  331. if (series.Status == SeriesStatus.Ended) {
  332. var document = XDocument.Load(new XmlNodeReader(doc));
  333. var dates = document.Descendants("Episode").Where(x => {
  334. var seasonNumber = x.Element("SeasonNumber");
  335. var firstAired = x.Element("FirstAired");
  336. return firstAired != null && seasonNumber != null && (!string.IsNullOrEmpty(seasonNumber.Value) && seasonNumber.Value != "0") && !string.IsNullOrEmpty(firstAired.Value);
  337. }).Select(x => {
  338. DateTime? date = null;
  339. DateTime tempDate;
  340. var firstAired = x.Element("FirstAired");
  341. if (firstAired != null && DateTime.TryParse(firstAired.Value, out tempDate))
  342. {
  343. date = tempDate;
  344. }
  345. return date;
  346. }).ToList();
  347. if(dates.Any(x=>x.HasValue))
  348. series.EndDate = dates.Where(x => x.HasValue).Max();
  349. }
  350. }
  351. /// <summary>
  352. /// Fetches the actors.
  353. /// </summary>
  354. /// <param name="series">The series.</param>
  355. /// <param name="actorsDoc">The actors doc.</param>
  356. /// <param name="seriesDoc">The seriesDoc.</param>
  357. /// <returns>Task.</returns>
  358. private void FetchActors(Series series, XmlDocument actorsDoc, XmlDocument seriesDoc)
  359. {
  360. var xmlNodeList = actorsDoc.SelectNodes("Actors/Actor");
  361. if (xmlNodeList != null)
  362. {
  363. series.People.Clear();
  364. foreach (XmlNode p in xmlNodeList)
  365. {
  366. string actorName = p.SafeGetString("Name");
  367. string actorRole = p.SafeGetString("Role");
  368. if (!string.IsNullOrWhiteSpace(actorName))
  369. {
  370. // Sometimes tvdb actors have leading spaces
  371. series.AddPerson(new PersonInfo { Type = PersonType.Actor, Name = actorName.Trim(), Role = actorRole });
  372. }
  373. }
  374. }
  375. }
  376. /// <summary>
  377. /// The us culture
  378. /// </summary>
  379. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  380. /// <summary>
  381. /// Determines whether [has local meta] [the specified item].
  382. /// </summary>
  383. /// <param name="item">The item.</param>
  384. /// <returns><c>true</c> if [has local meta] [the specified item]; otherwise, <c>false</c>.</returns>
  385. private bool HasLocalMeta(BaseItem item)
  386. {
  387. return item.ResolveArgs.ContainsMetaFileByName(LocalMetaFileName);
  388. }
  389. /// <summary>
  390. /// Gets the series id.
  391. /// </summary>
  392. /// <param name="item">The item.</param>
  393. /// <param name="cancellationToken">The cancellation token.</param>
  394. /// <returns>Task{System.String}.</returns>
  395. private async Task<string> GetSeriesId(BaseItem item, CancellationToken cancellationToken)
  396. {
  397. var seriesId = item.GetProviderId(MetadataProviders.Tvdb);
  398. if (string.IsNullOrEmpty(seriesId))
  399. {
  400. seriesId = await FindSeries(item.Name, cancellationToken).ConfigureAwait(false);
  401. }
  402. return seriesId;
  403. }
  404. /// <summary>
  405. /// Finds the series.
  406. /// </summary>
  407. /// <param name="name">The name.</param>
  408. /// <param name="cancellationToken">The cancellation token.</param>
  409. /// <returns>Task{System.String}.</returns>
  410. public async Task<string> FindSeries(string name, CancellationToken cancellationToken)
  411. {
  412. //nope - search for it
  413. string url = string.Format(RootUrl + SeriesQuery, WebUtility.UrlEncode(name));
  414. var doc = new XmlDocument();
  415. using (var results = await HttpClient.Get(new HttpRequestOptions
  416. {
  417. Url = url,
  418. ResourcePool = TvDbResourcePool,
  419. CancellationToken = cancellationToken
  420. }).ConfigureAwait(false))
  421. {
  422. doc.Load(results);
  423. }
  424. if (doc.HasChildNodes)
  425. {
  426. XmlNodeList nodes = doc.SelectNodes("//Series");
  427. string comparableName = GetComparableName(name);
  428. if (nodes != null)
  429. foreach (XmlNode node in nodes)
  430. {
  431. var n = node.SelectSingleNode("./SeriesName");
  432. if (n != null && GetComparableName(n.InnerText) == comparableName)
  433. {
  434. n = node.SelectSingleNode("./seriesid");
  435. if (n != null)
  436. return n.InnerText;
  437. }
  438. else
  439. {
  440. if (n != null)
  441. Logger.Info("TVDb Provider - " + n.InnerText + " did not match " + comparableName);
  442. }
  443. }
  444. }
  445. Logger.Info("TVDb Provider - Could not find " + name + ". Check name on Thetvdb.org.");
  446. return null;
  447. }
  448. /// <summary>
  449. /// The remove
  450. /// </summary>
  451. const string remove = "\"'!`?";
  452. /// <summary>
  453. /// The spacers
  454. /// </summary>
  455. const string spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  456. /// <summary>
  457. /// Gets the name of the comparable.
  458. /// </summary>
  459. /// <param name="name">The name.</param>
  460. /// <returns>System.String.</returns>
  461. internal static string GetComparableName(string name)
  462. {
  463. name = name.ToLower();
  464. name = name.Normalize(NormalizationForm.FormKD);
  465. var sb = new StringBuilder();
  466. foreach (var c in name)
  467. {
  468. if ((int)c >= 0x2B0 && (int)c <= 0x0333)
  469. {
  470. // skip char modifier and diacritics
  471. }
  472. else if (remove.IndexOf(c) > -1)
  473. {
  474. // skip chars we are removing
  475. }
  476. else if (spacers.IndexOf(c) > -1)
  477. {
  478. sb.Append(" ");
  479. }
  480. else if (c == '&')
  481. {
  482. sb.Append(" and ");
  483. }
  484. else
  485. {
  486. sb.Append(c);
  487. }
  488. }
  489. name = sb.ToString();
  490. name = name.Replace(", the", "");
  491. name = name.Replace("the ", " ");
  492. name = name.Replace(" the ", " ");
  493. string prevName;
  494. do
  495. {
  496. prevName = name;
  497. name = name.Replace(" ", " ");
  498. } while (name.Length != prevName.Length);
  499. return name.Trim();
  500. }
  501. /// <summary>
  502. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  503. /// </summary>
  504. public void Dispose()
  505. {
  506. Dispose(true);
  507. }
  508. }
  509. }