BaseNfoParser.cs 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Threading;
  10. using System.Xml;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.TV;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.XbmcMetadata.Configuration;
  17. using MediaBrowser.XbmcMetadata.Savers;
  18. using Microsoft.Extensions.Logging;
  19. namespace MediaBrowser.XbmcMetadata.Parsers
  20. {
  21. public class BaseNfoParser<T>
  22. where T : BaseItem
  23. {
  24. private readonly IConfigurationManager _config;
  25. private Dictionary<string, string> _validProviderIds;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
  28. /// </summary>
  29. /// <param name="logger">The logger.</param>
  30. /// <param name="config">the configuration manager.</param>
  31. /// <param name="providerManager">The provider manager.</param>
  32. public BaseNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager)
  33. {
  34. Logger = logger;
  35. _config = config;
  36. ProviderManager = providerManager;
  37. _validProviderIds = new Dictionary<string, string>();
  38. }
  39. protected CultureInfo UsCulture { get; } = new CultureInfo("en-US");
  40. /// <summary>
  41. /// Gets the logger.
  42. /// </summary>
  43. protected ILogger Logger { get; }
  44. protected IProviderManager ProviderManager { get; }
  45. protected virtual bool SupportsUrlAfterClosingXmlTag => false;
  46. protected virtual string MovieDbParserSearchString => "themoviedb.org/movie/";
  47. /// <summary>
  48. /// Fetches metadata for an item from one xml file.
  49. /// </summary>
  50. /// <param name="item">The item.</param>
  51. /// <param name="metadataFile">The metadata file.</param>
  52. /// <param name="cancellationToken">The cancellation token.</param>
  53. /// <exception cref="ArgumentNullException"><c>item</c> is <c>null</c>.</exception>
  54. /// <exception cref="ArgumentException"><c>metadataFile</c> is <c>null</c> or empty.</exception>
  55. public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
  56. {
  57. if (item == null)
  58. {
  59. throw new ArgumentNullException(nameof(item));
  60. }
  61. if (string.IsNullOrEmpty(metadataFile))
  62. {
  63. throw new ArgumentException("The metadata file was empty or null.", nameof(metadataFile));
  64. }
  65. _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  66. var idInfos = ProviderManager.GetExternalIdInfos(item.Item);
  67. foreach (var info in idInfos)
  68. {
  69. var id = info.Key + "Id";
  70. if (!_validProviderIds.ContainsKey(id))
  71. {
  72. _validProviderIds.Add(id, info.Key);
  73. }
  74. }
  75. // Additional Mappings
  76. _validProviderIds.Add("collectionnumber", "TmdbCollection");
  77. _validProviderIds.Add("tmdbcolid", "TmdbCollection");
  78. _validProviderIds.Add("imdb_id", "Imdb");
  79. Fetch(item, metadataFile, GetXmlReaderSettings(), cancellationToken);
  80. }
  81. /// <summary>
  82. /// Fetches the specified item.
  83. /// </summary>
  84. /// <param name="item">The item.</param>
  85. /// <param name="metadataFile">The metadata file.</param>
  86. /// <param name="settings">The settings.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. protected virtual void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
  89. {
  90. if (!SupportsUrlAfterClosingXmlTag)
  91. {
  92. using (var fileStream = File.OpenRead(metadataFile))
  93. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  94. using (var reader = XmlReader.Create(streamReader, settings))
  95. {
  96. item.ResetPeople();
  97. reader.MoveToContent();
  98. reader.Read();
  99. // Loop through each element
  100. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  101. {
  102. cancellationToken.ThrowIfCancellationRequested();
  103. if (reader.NodeType == XmlNodeType.Element)
  104. {
  105. FetchDataFromXmlNode(reader, item);
  106. }
  107. else
  108. {
  109. reader.Read();
  110. }
  111. }
  112. }
  113. return;
  114. }
  115. using (var fileStream = File.OpenRead(metadataFile))
  116. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  117. {
  118. item.ResetPeople();
  119. // Need to handle a url after the xml data
  120. // http://kodi.wiki/view/NFO_files/movies
  121. var xml = streamReader.ReadToEnd();
  122. // Find last closing Tag
  123. // Need to do this in two steps to account for random > characters after the closing xml
  124. var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
  125. // If closing tag exists, move to end of Tag
  126. if (index != -1)
  127. {
  128. index = xml.IndexOf('>', index);
  129. }
  130. if (index != -1)
  131. {
  132. var endingXml = xml.Substring(index);
  133. ParseProviderLinks(item.Item, endingXml);
  134. // If the file is just an imdb url, don't go any further
  135. if (index == 0)
  136. {
  137. return;
  138. }
  139. xml = xml.Substring(0, index + 1);
  140. }
  141. else
  142. {
  143. // If the file is just an Imdb url, handle that
  144. ParseProviderLinks(item.Item, xml);
  145. return;
  146. }
  147. // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
  148. try
  149. {
  150. using (var stringReader = new StringReader(xml))
  151. using (var reader = XmlReader.Create(stringReader, settings))
  152. {
  153. reader.MoveToContent();
  154. reader.Read();
  155. // Loop through each element
  156. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  157. {
  158. cancellationToken.ThrowIfCancellationRequested();
  159. if (reader.NodeType == XmlNodeType.Element)
  160. {
  161. FetchDataFromXmlNode(reader, item);
  162. }
  163. else
  164. {
  165. reader.Read();
  166. }
  167. }
  168. }
  169. }
  170. catch (XmlException)
  171. {
  172. }
  173. }
  174. }
  175. protected void ParseProviderLinks(T item, string xml)
  176. {
  177. // Look for a match for the Regex pattern "tt" followed by 7 or 8 digits
  178. var m = Regex.Match(xml, "tt([0-9]{7,8})", RegexOptions.IgnoreCase);
  179. if (m.Success)
  180. {
  181. item.SetProviderId(MetadataProvider.Imdb, m.Value);
  182. }
  183. // Support Tmdb
  184. // https://www.themoviedb.org/movie/30287-fallo
  185. var srch = MovieDbParserSearchString;
  186. var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  187. if (index != -1)
  188. {
  189. var tmdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/');
  190. index = tmdbId.IndexOf('-');
  191. if (index != -1)
  192. {
  193. tmdbId = tmdbId.Slice(0, index);
  194. }
  195. if (!tmdbId.IsEmpty
  196. && !tmdbId.IsWhiteSpace()
  197. && int.TryParse(tmdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
  198. {
  199. item.SetProviderId(MetadataProvider.Tmdb, value.ToString(UsCulture));
  200. }
  201. }
  202. if (item is Series)
  203. {
  204. srch = "thetvdb.com/?tab=series&id=";
  205. index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  206. if (index != -1)
  207. {
  208. var tvdbId = xml.AsSpan().Slice(index + srch.Length).TrimEnd('/');
  209. if (!tvdbId.IsEmpty
  210. && !tvdbId.IsWhiteSpace()
  211. && int.TryParse(tvdbId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
  212. {
  213. item.SetProviderId(MetadataProvider.Tvdb, value.ToString(UsCulture));
  214. }
  215. }
  216. }
  217. }
  218. protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
  219. {
  220. var item = itemResult.Item;
  221. switch (reader.Name)
  222. {
  223. // DateCreated
  224. case "dateadded":
  225. {
  226. var val = reader.ReadElementContentAsString();
  227. if (!string.IsNullOrWhiteSpace(val))
  228. {
  229. if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var added))
  230. {
  231. item.DateCreated = added.ToUniversalTime();
  232. }
  233. else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  234. {
  235. item.DateCreated = added.ToUniversalTime();
  236. }
  237. else
  238. {
  239. Logger.LogWarning("Invalid Added value found: " + val);
  240. }
  241. }
  242. break;
  243. }
  244. case "originaltitle":
  245. {
  246. var val = reader.ReadElementContentAsString();
  247. if (!string.IsNullOrEmpty(val))
  248. {
  249. item.OriginalTitle = val;
  250. }
  251. break;
  252. }
  253. case "title":
  254. case "localtitle":
  255. item.Name = reader.ReadElementContentAsString();
  256. break;
  257. case "criticrating":
  258. {
  259. var text = reader.ReadElementContentAsString();
  260. if (!string.IsNullOrEmpty(text))
  261. {
  262. if (float.TryParse(text, NumberStyles.Any, UsCulture, out var value))
  263. {
  264. item.CriticRating = value;
  265. }
  266. }
  267. break;
  268. }
  269. case "sorttitle":
  270. {
  271. var val = reader.ReadElementContentAsString();
  272. if (!string.IsNullOrWhiteSpace(val))
  273. {
  274. item.ForcedSortName = val;
  275. }
  276. break;
  277. }
  278. case "biography":
  279. case "plot":
  280. case "review":
  281. {
  282. var val = reader.ReadElementContentAsString();
  283. if (!string.IsNullOrWhiteSpace(val))
  284. {
  285. item.Overview = val;
  286. }
  287. break;
  288. }
  289. case "language":
  290. {
  291. var val = reader.ReadElementContentAsString();
  292. item.PreferredMetadataLanguage = val;
  293. break;
  294. }
  295. case "countrycode":
  296. {
  297. var val = reader.ReadElementContentAsString();
  298. item.PreferredMetadataCountryCode = val;
  299. break;
  300. }
  301. case "lockedfields":
  302. {
  303. var val = reader.ReadElementContentAsString();
  304. if (!string.IsNullOrWhiteSpace(val))
  305. {
  306. item.LockedFields = val.Split('|').Select(i =>
  307. {
  308. if (Enum.TryParse(i, true, out MetadataField field))
  309. {
  310. return (MetadataField?)field;
  311. }
  312. return null;
  313. }).OfType<MetadataField>().ToArray();
  314. }
  315. break;
  316. }
  317. case "tagline":
  318. {
  319. var val = reader.ReadElementContentAsString();
  320. if (!string.IsNullOrWhiteSpace(val))
  321. {
  322. item.Tagline = val;
  323. }
  324. break;
  325. }
  326. case "country":
  327. {
  328. var val = reader.ReadElementContentAsString();
  329. if (!string.IsNullOrWhiteSpace(val))
  330. {
  331. item.ProductionLocations = val.Split('/')
  332. .Select(i => i.Trim())
  333. .Where(i => !string.IsNullOrWhiteSpace(i))
  334. .ToArray();
  335. }
  336. break;
  337. }
  338. case "mpaa":
  339. {
  340. var rating = reader.ReadElementContentAsString();
  341. if (!string.IsNullOrWhiteSpace(rating))
  342. {
  343. item.OfficialRating = rating;
  344. }
  345. break;
  346. }
  347. case "customrating":
  348. {
  349. var val = reader.ReadElementContentAsString();
  350. if (!string.IsNullOrWhiteSpace(val))
  351. {
  352. item.CustomRating = val;
  353. }
  354. break;
  355. }
  356. case "runtime":
  357. {
  358. var text = reader.ReadElementContentAsString();
  359. if (!string.IsNullOrWhiteSpace(text))
  360. {
  361. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, UsCulture, out var runtime))
  362. {
  363. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  364. }
  365. }
  366. break;
  367. }
  368. case "aspectratio":
  369. {
  370. var val = reader.ReadElementContentAsString();
  371. if (!string.IsNullOrWhiteSpace(val)
  372. && item is IHasAspectRatio hasAspectRatio)
  373. {
  374. hasAspectRatio.AspectRatio = val;
  375. }
  376. break;
  377. }
  378. case "lockdata":
  379. {
  380. var val = reader.ReadElementContentAsString();
  381. if (!string.IsNullOrWhiteSpace(val))
  382. {
  383. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  384. }
  385. break;
  386. }
  387. case "studio":
  388. {
  389. var val = reader.ReadElementContentAsString();
  390. if (!string.IsNullOrWhiteSpace(val))
  391. {
  392. item.AddStudio(val);
  393. }
  394. break;
  395. }
  396. case "director":
  397. {
  398. var val = reader.ReadElementContentAsString();
  399. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  400. {
  401. if (string.IsNullOrWhiteSpace(p.Name))
  402. {
  403. continue;
  404. }
  405. itemResult.AddPerson(p);
  406. }
  407. break;
  408. }
  409. case "credits":
  410. {
  411. var val = reader.ReadElementContentAsString();
  412. if (!string.IsNullOrWhiteSpace(val))
  413. {
  414. var parts = val.Split('/').Select(i => i.Trim())
  415. .Where(i => !string.IsNullOrEmpty(i));
  416. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  417. {
  418. if (string.IsNullOrWhiteSpace(p.Name))
  419. {
  420. continue;
  421. }
  422. itemResult.AddPerson(p);
  423. }
  424. }
  425. break;
  426. }
  427. case "writer":
  428. {
  429. var val = reader.ReadElementContentAsString();
  430. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  431. {
  432. if (string.IsNullOrWhiteSpace(p.Name))
  433. {
  434. continue;
  435. }
  436. itemResult.AddPerson(p);
  437. }
  438. break;
  439. }
  440. case "actor":
  441. {
  442. if (!reader.IsEmptyElement)
  443. {
  444. using (var subtree = reader.ReadSubtree())
  445. {
  446. var person = GetPersonFromXmlNode(subtree);
  447. if (!string.IsNullOrWhiteSpace(person.Name))
  448. {
  449. itemResult.AddPerson(person);
  450. }
  451. }
  452. }
  453. else
  454. {
  455. reader.Read();
  456. }
  457. break;
  458. }
  459. case "trailer":
  460. {
  461. var val = reader.ReadElementContentAsString();
  462. if (!string.IsNullOrWhiteSpace(val))
  463. {
  464. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", BaseNfoSaver.YouTubeWatchUrl, StringComparison.OrdinalIgnoreCase);
  465. item.AddTrailerUrl(val);
  466. }
  467. break;
  468. }
  469. case "displayorder":
  470. {
  471. var val = reader.ReadElementContentAsString();
  472. var hasDisplayOrder = item as IHasDisplayOrder;
  473. if (hasDisplayOrder != null)
  474. {
  475. if (!string.IsNullOrWhiteSpace(val))
  476. {
  477. hasDisplayOrder.DisplayOrder = val;
  478. }
  479. }
  480. break;
  481. }
  482. case "year":
  483. {
  484. var val = reader.ReadElementContentAsString();
  485. if (!string.IsNullOrWhiteSpace(val))
  486. {
  487. if (int.TryParse(val, out var productionYear) && productionYear > 1850)
  488. {
  489. item.ProductionYear = productionYear;
  490. }
  491. }
  492. break;
  493. }
  494. case "rating":
  495. {
  496. var rating = reader.ReadElementContentAsString();
  497. if (!string.IsNullOrWhiteSpace(rating))
  498. {
  499. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  500. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
  501. {
  502. item.CommunityRating = val;
  503. }
  504. }
  505. break;
  506. }
  507. case "ratings":
  508. {
  509. if (!reader.IsEmptyElement)
  510. {
  511. using var subtree = reader.ReadSubtree();
  512. FetchFromRatingsNode(subtree, item);
  513. }
  514. else
  515. {
  516. reader.Read();
  517. }
  518. break;
  519. }
  520. case "aired":
  521. case "formed":
  522. case "premiered":
  523. case "releasedate":
  524. {
  525. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  526. var val = reader.ReadElementContentAsString();
  527. if (!string.IsNullOrWhiteSpace(val))
  528. {
  529. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
  530. {
  531. item.PremiereDate = date.ToUniversalTime();
  532. item.ProductionYear = date.Year;
  533. }
  534. }
  535. break;
  536. }
  537. case "enddate":
  538. {
  539. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  540. var val = reader.ReadElementContentAsString();
  541. if (!string.IsNullOrWhiteSpace(val))
  542. {
  543. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) && date.Year > 1850)
  544. {
  545. item.EndDate = date.ToUniversalTime();
  546. }
  547. }
  548. break;
  549. }
  550. case "genre":
  551. {
  552. var val = reader.ReadElementContentAsString();
  553. if (!string.IsNullOrWhiteSpace(val))
  554. {
  555. var parts = val.Split('/')
  556. .Select(i => i.Trim())
  557. .Where(i => !string.IsNullOrWhiteSpace(i));
  558. foreach (var p in parts)
  559. {
  560. item.AddGenre(p);
  561. }
  562. }
  563. break;
  564. }
  565. case "style":
  566. case "tag":
  567. {
  568. var val = reader.ReadElementContentAsString();
  569. if (!string.IsNullOrWhiteSpace(val))
  570. {
  571. item.AddTag(val);
  572. }
  573. break;
  574. }
  575. case "fileinfo":
  576. {
  577. if (!reader.IsEmptyElement)
  578. {
  579. using (var subtree = reader.ReadSubtree())
  580. {
  581. FetchFromFileInfoNode(subtree, item);
  582. }
  583. }
  584. else
  585. {
  586. reader.Read();
  587. }
  588. break;
  589. }
  590. default:
  591. string readerName = reader.Name;
  592. if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
  593. {
  594. var id = reader.ReadElementContentAsString();
  595. if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
  596. {
  597. item.SetProviderId(providerIdValue, id);
  598. }
  599. }
  600. else
  601. {
  602. reader.Skip();
  603. }
  604. break;
  605. }
  606. }
  607. private void FetchFromFileInfoNode(XmlReader reader, T item)
  608. {
  609. reader.MoveToContent();
  610. reader.Read();
  611. // Loop through each element
  612. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  613. {
  614. if (reader.NodeType == XmlNodeType.Element)
  615. {
  616. switch (reader.Name)
  617. {
  618. case "streamdetails":
  619. {
  620. if (reader.IsEmptyElement)
  621. {
  622. reader.Read();
  623. continue;
  624. }
  625. using (var subtree = reader.ReadSubtree())
  626. {
  627. FetchFromStreamDetailsNode(subtree, item);
  628. }
  629. break;
  630. }
  631. default:
  632. reader.Skip();
  633. break;
  634. }
  635. }
  636. else
  637. {
  638. reader.Read();
  639. }
  640. }
  641. }
  642. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  643. {
  644. reader.MoveToContent();
  645. reader.Read();
  646. // Loop through each element
  647. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  648. {
  649. if (reader.NodeType == XmlNodeType.Element)
  650. {
  651. switch (reader.Name)
  652. {
  653. case "video":
  654. {
  655. if (reader.IsEmptyElement)
  656. {
  657. reader.Read();
  658. continue;
  659. }
  660. using (var subtree = reader.ReadSubtree())
  661. {
  662. FetchFromVideoNode(subtree, item);
  663. }
  664. break;
  665. }
  666. default:
  667. reader.Skip();
  668. break;
  669. }
  670. }
  671. else
  672. {
  673. reader.Read();
  674. }
  675. }
  676. }
  677. private void FetchFromVideoNode(XmlReader reader, T item)
  678. {
  679. reader.MoveToContent();
  680. reader.Read();
  681. // Loop through each element
  682. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  683. {
  684. if (reader.NodeType == XmlNodeType.Element)
  685. {
  686. switch (reader.Name)
  687. {
  688. case "format3d":
  689. {
  690. var val = reader.ReadElementContentAsString();
  691. var video = item as Video;
  692. if (video != null)
  693. {
  694. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  695. {
  696. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  697. }
  698. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  699. {
  700. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  701. }
  702. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  703. {
  704. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  705. }
  706. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  707. {
  708. video.Video3DFormat = Video3DFormat.FullSideBySide;
  709. }
  710. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  711. {
  712. video.Video3DFormat = Video3DFormat.MVC;
  713. }
  714. }
  715. break;
  716. }
  717. default:
  718. reader.Skip();
  719. break;
  720. }
  721. }
  722. else
  723. {
  724. reader.Read();
  725. }
  726. }
  727. }
  728. private void FetchFromRatingsNode(XmlReader reader, T item)
  729. {
  730. reader.MoveToContent();
  731. reader.Read();
  732. // Loop through each element
  733. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  734. {
  735. if (reader.NodeType == XmlNodeType.Element)
  736. {
  737. switch (reader.Name)
  738. {
  739. case "rating":
  740. {
  741. if (reader.IsEmptyElement)
  742. {
  743. reader.Read();
  744. continue;
  745. }
  746. var ratingName = reader.GetAttribute("name");
  747. using var subtree = reader.ReadSubtree();
  748. FetchFromRatingNode(subtree, item, ratingName);
  749. break;
  750. }
  751. default:
  752. reader.Skip();
  753. break;
  754. }
  755. }
  756. else
  757. {
  758. reader.Read();
  759. }
  760. }
  761. }
  762. private void FetchFromRatingNode(XmlReader reader, T item, string? ratingName)
  763. {
  764. reader.MoveToContent();
  765. reader.Read();
  766. // Loop through each element
  767. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  768. {
  769. if (reader.NodeType == XmlNodeType.Element)
  770. {
  771. switch (reader.Name)
  772. {
  773. case "value":
  774. var val = reader.ReadElementContentAsString();
  775. if (!string.IsNullOrWhiteSpace(val))
  776. {
  777. if (float.TryParse(val.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var ratingValue))
  778. {
  779. // if ratingName contains tomato --> assume critic rating
  780. if (ratingName != null && ratingName.Contains("tomato", StringComparison.InvariantCultureIgnoreCase))
  781. {
  782. item.CriticRating = ratingValue;
  783. }
  784. else
  785. {
  786. item.CommunityRating = ratingValue;
  787. }
  788. }
  789. }
  790. break;
  791. default:
  792. reader.Skip();
  793. break;
  794. }
  795. }
  796. else
  797. {
  798. reader.Read();
  799. }
  800. }
  801. }
  802. /// <summary>
  803. /// Gets the persons from XML node.
  804. /// </summary>
  805. /// <param name="reader">The reader.</param>
  806. /// <returns>IEnumerable{PersonInfo}.</returns>
  807. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  808. {
  809. var name = string.Empty;
  810. var type = PersonType.Actor; // If type is not specified assume actor
  811. var role = string.Empty;
  812. int? sortOrder = null;
  813. reader.MoveToContent();
  814. reader.Read();
  815. // Loop through each element
  816. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  817. {
  818. if (reader.NodeType == XmlNodeType.Element)
  819. {
  820. switch (reader.Name)
  821. {
  822. case "name":
  823. name = reader.ReadElementContentAsString() ?? string.Empty;
  824. break;
  825. case "role":
  826. {
  827. var val = reader.ReadElementContentAsString();
  828. if (!string.IsNullOrWhiteSpace(val))
  829. {
  830. role = val;
  831. }
  832. break;
  833. }
  834. case "sortorder":
  835. {
  836. var val = reader.ReadElementContentAsString();
  837. if (!string.IsNullOrWhiteSpace(val))
  838. {
  839. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  840. {
  841. sortOrder = intVal;
  842. }
  843. }
  844. break;
  845. }
  846. default:
  847. reader.Skip();
  848. break;
  849. }
  850. }
  851. else
  852. {
  853. reader.Read();
  854. }
  855. }
  856. return new PersonInfo
  857. {
  858. Name = name.Trim(),
  859. Role = role,
  860. Type = type,
  861. SortOrder = sortOrder
  862. };
  863. }
  864. internal XmlReaderSettings GetXmlReaderSettings()
  865. => new XmlReaderSettings()
  866. {
  867. ValidationType = ValidationType.None,
  868. CheckCharacters = false,
  869. IgnoreProcessingInstructions = true,
  870. IgnoreComments = true
  871. };
  872. /// <summary>
  873. /// Used to split names of comma or pipe delimeted genres and people.
  874. /// </summary>
  875. /// <param name="value">The value.</param>
  876. /// <returns>IEnumerable{System.String}.</returns>
  877. private IEnumerable<string> SplitNames(string value)
  878. {
  879. value = value ?? string.Empty;
  880. // Only split by comma if there is no pipe in the string
  881. // We have to be careful to not split names like Matthew, Jr.
  882. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  883. ? new[] { ',' }
  884. : new[] { '|', ';' };
  885. value = value.Trim().Trim(separator);
  886. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  887. }
  888. }
  889. }