BaseNfoParser.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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.Item == null)
  58. {
  59. throw new ArgumentException("Item can't be null.", nameof(item));
  60. }
  61. if (string.IsNullOrEmpty(metadataFile))
  62. {
  63. throw new ArgumentException("The metadata filepath was empty.", 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.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var added))
  230. {
  231. item.DateCreated = added.ToUniversalTime();
  232. }
  233. else
  234. {
  235. Logger.LogWarning("Invalid Added value found: {Value}", val);
  236. }
  237. }
  238. break;
  239. }
  240. case "originaltitle":
  241. {
  242. var val = reader.ReadElementContentAsString();
  243. if (!string.IsNullOrEmpty(val))
  244. {
  245. item.OriginalTitle = val;
  246. }
  247. break;
  248. }
  249. case "name":
  250. case "title":
  251. case "localtitle":
  252. item.Name = reader.ReadElementContentAsString();
  253. break;
  254. case "sortname":
  255. item.SortName = 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. item.Tagline = reader.ReadElementContentAsString();
  319. break;
  320. case "country":
  321. {
  322. var val = reader.ReadElementContentAsString();
  323. if (!string.IsNullOrWhiteSpace(val))
  324. {
  325. item.ProductionLocations = val.Split('/')
  326. .Select(i => i.Trim())
  327. .Where(i => !string.IsNullOrWhiteSpace(i))
  328. .ToArray();
  329. }
  330. break;
  331. }
  332. case "mpaa":
  333. {
  334. var rating = reader.ReadElementContentAsString();
  335. if (!string.IsNullOrWhiteSpace(rating))
  336. {
  337. item.OfficialRating = rating;
  338. }
  339. break;
  340. }
  341. case "customrating":
  342. {
  343. var val = reader.ReadElementContentAsString();
  344. if (!string.IsNullOrWhiteSpace(val))
  345. {
  346. item.CustomRating = val;
  347. }
  348. break;
  349. }
  350. case "runtime":
  351. {
  352. var text = reader.ReadElementContentAsString();
  353. if (!string.IsNullOrWhiteSpace(text))
  354. {
  355. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, UsCulture, out var runtime))
  356. {
  357. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  358. }
  359. }
  360. break;
  361. }
  362. case "aspectratio":
  363. {
  364. var val = reader.ReadElementContentAsString();
  365. if (!string.IsNullOrWhiteSpace(val)
  366. && item is IHasAspectRatio hasAspectRatio)
  367. {
  368. hasAspectRatio.AspectRatio = val;
  369. }
  370. break;
  371. }
  372. case "lockdata":
  373. {
  374. var val = reader.ReadElementContentAsString();
  375. if (!string.IsNullOrWhiteSpace(val))
  376. {
  377. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  378. }
  379. break;
  380. }
  381. case "studio":
  382. {
  383. var val = reader.ReadElementContentAsString();
  384. if (!string.IsNullOrWhiteSpace(val))
  385. {
  386. item.AddStudio(val);
  387. }
  388. break;
  389. }
  390. case "director":
  391. {
  392. var val = reader.ReadElementContentAsString();
  393. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  394. {
  395. if (string.IsNullOrWhiteSpace(p.Name))
  396. {
  397. continue;
  398. }
  399. itemResult.AddPerson(p);
  400. }
  401. break;
  402. }
  403. case "credits":
  404. {
  405. var val = reader.ReadElementContentAsString();
  406. if (!string.IsNullOrWhiteSpace(val))
  407. {
  408. var parts = val.Split('/').Select(i => i.Trim())
  409. .Where(i => !string.IsNullOrEmpty(i));
  410. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  411. {
  412. if (string.IsNullOrWhiteSpace(p.Name))
  413. {
  414. continue;
  415. }
  416. itemResult.AddPerson(p);
  417. }
  418. }
  419. break;
  420. }
  421. case "writer":
  422. {
  423. var val = reader.ReadElementContentAsString();
  424. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  425. {
  426. if (string.IsNullOrWhiteSpace(p.Name))
  427. {
  428. continue;
  429. }
  430. itemResult.AddPerson(p);
  431. }
  432. break;
  433. }
  434. case "actor":
  435. {
  436. if (!reader.IsEmptyElement)
  437. {
  438. using (var subtree = reader.ReadSubtree())
  439. {
  440. var person = GetPersonFromXmlNode(subtree);
  441. if (!string.IsNullOrWhiteSpace(person.Name))
  442. {
  443. itemResult.AddPerson(person);
  444. }
  445. }
  446. }
  447. else
  448. {
  449. reader.Read();
  450. }
  451. break;
  452. }
  453. case "trailer":
  454. {
  455. var val = reader.ReadElementContentAsString();
  456. if (!string.IsNullOrWhiteSpace(val))
  457. {
  458. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", BaseNfoSaver.YouTubeWatchUrl, StringComparison.OrdinalIgnoreCase);
  459. item.AddTrailerUrl(val);
  460. }
  461. break;
  462. }
  463. case "displayorder":
  464. {
  465. var val = reader.ReadElementContentAsString();
  466. var hasDisplayOrder = item as IHasDisplayOrder;
  467. if (hasDisplayOrder != null)
  468. {
  469. if (!string.IsNullOrWhiteSpace(val))
  470. {
  471. hasDisplayOrder.DisplayOrder = val;
  472. }
  473. }
  474. break;
  475. }
  476. case "year":
  477. {
  478. var val = reader.ReadElementContentAsString();
  479. if (!string.IsNullOrWhiteSpace(val))
  480. {
  481. if (int.TryParse(val, out var productionYear) && productionYear > 1850)
  482. {
  483. item.ProductionYear = productionYear;
  484. }
  485. }
  486. break;
  487. }
  488. case "rating":
  489. {
  490. var rating = reader.ReadElementContentAsString();
  491. if (!string.IsNullOrWhiteSpace(rating))
  492. {
  493. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  494. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var val))
  495. {
  496. item.CommunityRating = val;
  497. }
  498. }
  499. break;
  500. }
  501. case "aired":
  502. case "formed":
  503. case "premiered":
  504. case "releasedate":
  505. {
  506. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  507. var val = reader.ReadElementContentAsString();
  508. if (!string.IsNullOrWhiteSpace(val))
  509. {
  510. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  511. {
  512. item.PremiereDate = date.ToUniversalTime();
  513. item.ProductionYear = date.Year;
  514. }
  515. }
  516. break;
  517. }
  518. case "enddate":
  519. {
  520. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  521. var val = reader.ReadElementContentAsString();
  522. if (!string.IsNullOrWhiteSpace(val))
  523. {
  524. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var date) && date.Year > 1850)
  525. {
  526. item.EndDate = date.ToUniversalTime();
  527. }
  528. }
  529. break;
  530. }
  531. case "genre":
  532. {
  533. var val = reader.ReadElementContentAsString();
  534. if (!string.IsNullOrWhiteSpace(val))
  535. {
  536. var parts = val.Split('/')
  537. .Select(i => i.Trim())
  538. .Where(i => !string.IsNullOrWhiteSpace(i));
  539. foreach (var p in parts)
  540. {
  541. item.AddGenre(p);
  542. }
  543. }
  544. break;
  545. }
  546. case "style":
  547. case "tag":
  548. {
  549. var val = reader.ReadElementContentAsString();
  550. if (!string.IsNullOrWhiteSpace(val))
  551. {
  552. item.AddTag(val);
  553. }
  554. break;
  555. }
  556. case "fileinfo":
  557. {
  558. if (!reader.IsEmptyElement)
  559. {
  560. using (var subtree = reader.ReadSubtree())
  561. {
  562. FetchFromFileInfoNode(subtree, item);
  563. }
  564. }
  565. else
  566. {
  567. reader.Read();
  568. }
  569. break;
  570. }
  571. case "uniqueid":
  572. {
  573. if (reader.IsEmptyElement)
  574. {
  575. reader.Read();
  576. break;
  577. }
  578. var provider = reader.GetAttribute("type");
  579. var id = reader.ReadElementContentAsString();
  580. if (!string.IsNullOrWhiteSpace(provider) && !string.IsNullOrWhiteSpace(id))
  581. {
  582. item.SetProviderId(provider, id);
  583. }
  584. break;
  585. }
  586. case "musicBrainzArtistID":
  587. {
  588. if (reader.IsEmptyElement)
  589. {
  590. reader.Read();
  591. break;
  592. }
  593. var id = reader.ReadElementContentAsString();
  594. item.SetProviderId(MetadataProvider.MusicBrainzArtist.ToString(), id);
  595. break;
  596. }
  597. default:
  598. string readerName = reader.Name;
  599. if (_validProviderIds.TryGetValue(readerName, out string? providerIdValue))
  600. {
  601. var id = reader.ReadElementContentAsString();
  602. if (!string.IsNullOrWhiteSpace(providerIdValue) && !string.IsNullOrWhiteSpace(id))
  603. {
  604. item.SetProviderId(providerIdValue, id);
  605. }
  606. }
  607. else
  608. {
  609. reader.Skip();
  610. }
  611. break;
  612. }
  613. }
  614. private void FetchFromFileInfoNode(XmlReader reader, T item)
  615. {
  616. reader.MoveToContent();
  617. reader.Read();
  618. // Loop through each element
  619. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  620. {
  621. if (reader.NodeType == XmlNodeType.Element)
  622. {
  623. switch (reader.Name)
  624. {
  625. case "streamdetails":
  626. {
  627. if (reader.IsEmptyElement)
  628. {
  629. reader.Read();
  630. continue;
  631. }
  632. using (var subtree = reader.ReadSubtree())
  633. {
  634. FetchFromStreamDetailsNode(subtree, item);
  635. }
  636. break;
  637. }
  638. default:
  639. reader.Skip();
  640. break;
  641. }
  642. }
  643. else
  644. {
  645. reader.Read();
  646. }
  647. }
  648. }
  649. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  650. {
  651. reader.MoveToContent();
  652. reader.Read();
  653. // Loop through each element
  654. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  655. {
  656. if (reader.NodeType == XmlNodeType.Element)
  657. {
  658. switch (reader.Name)
  659. {
  660. case "video":
  661. {
  662. if (reader.IsEmptyElement)
  663. {
  664. reader.Read();
  665. continue;
  666. }
  667. using (var subtree = reader.ReadSubtree())
  668. {
  669. FetchFromVideoNode(subtree, item);
  670. }
  671. break;
  672. }
  673. case "subtitle":
  674. {
  675. if (reader.IsEmptyElement)
  676. {
  677. reader.Read();
  678. continue;
  679. }
  680. using (var subtree = reader.ReadSubtree())
  681. {
  682. FetchFromSubtitleNode(subtree, item);
  683. }
  684. break;
  685. }
  686. default:
  687. reader.Skip();
  688. break;
  689. }
  690. }
  691. else
  692. {
  693. reader.Read();
  694. }
  695. }
  696. }
  697. private void FetchFromVideoNode(XmlReader reader, T item)
  698. {
  699. reader.MoveToContent();
  700. reader.Read();
  701. // Loop through each element
  702. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  703. {
  704. if (reader.NodeType == XmlNodeType.Element)
  705. {
  706. switch (reader.Name)
  707. {
  708. case "format3d":
  709. {
  710. var val = reader.ReadElementContentAsString();
  711. var video = item as Video;
  712. if (video != null)
  713. {
  714. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  715. {
  716. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  717. }
  718. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  719. {
  720. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  721. }
  722. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  723. {
  724. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  725. }
  726. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  727. {
  728. video.Video3DFormat = Video3DFormat.FullSideBySide;
  729. }
  730. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  731. {
  732. video.Video3DFormat = Video3DFormat.MVC;
  733. }
  734. }
  735. break;
  736. }
  737. case "aspect":
  738. {
  739. var val = reader.ReadElementContentAsString();
  740. if (item is Video video)
  741. {
  742. video.AspectRatio = val;
  743. }
  744. break;
  745. }
  746. case "width":
  747. {
  748. var val = reader.ReadElementContentAsInt();
  749. if (item is Video video)
  750. {
  751. video.Width = val;
  752. }
  753. break;
  754. }
  755. case "height":
  756. {
  757. var val = reader.ReadElementContentAsInt();
  758. if (item is Video video)
  759. {
  760. video.Height = val;
  761. }
  762. break;
  763. }
  764. case "durationinseconds":
  765. {
  766. var val = reader.ReadElementContentAsInt();
  767. if (item is Video video)
  768. {
  769. video.RunTimeTicks = new TimeSpan(0, 0, val).Ticks;
  770. }
  771. break;
  772. }
  773. default:
  774. reader.Skip();
  775. break;
  776. }
  777. }
  778. else
  779. {
  780. reader.Read();
  781. }
  782. }
  783. }
  784. private void FetchFromSubtitleNode(XmlReader reader, T item)
  785. {
  786. reader.MoveToContent();
  787. reader.Read();
  788. // Loop through each element
  789. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  790. {
  791. if (reader.NodeType == XmlNodeType.Element)
  792. {
  793. switch (reader.Name)
  794. {
  795. case "language":
  796. {
  797. _ = reader.ReadElementContentAsString();
  798. if (item is Video video)
  799. {
  800. video.HasSubtitles = true;
  801. }
  802. break;
  803. }
  804. default:
  805. reader.Skip();
  806. break;
  807. }
  808. }
  809. else
  810. {
  811. reader.Read();
  812. }
  813. }
  814. }
  815. /// <summary>
  816. /// Gets the persons from XML node.
  817. /// </summary>
  818. /// <param name="reader">The reader.</param>
  819. /// <returns>IEnumerable{PersonInfo}.</returns>
  820. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  821. {
  822. var name = string.Empty;
  823. var type = PersonType.Actor; // If type is not specified assume actor
  824. var role = string.Empty;
  825. int? sortOrder = null;
  826. string? imageUrl = null;
  827. reader.MoveToContent();
  828. reader.Read();
  829. // Loop through each element
  830. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  831. {
  832. if (reader.NodeType == XmlNodeType.Element)
  833. {
  834. switch (reader.Name)
  835. {
  836. case "name":
  837. name = reader.ReadElementContentAsString() ?? string.Empty;
  838. break;
  839. case "role":
  840. {
  841. var val = reader.ReadElementContentAsString();
  842. if (!string.IsNullOrWhiteSpace(val))
  843. {
  844. role = val;
  845. }
  846. break;
  847. }
  848. case "type":
  849. {
  850. var val = reader.ReadElementContentAsString();
  851. if (!string.IsNullOrWhiteSpace(val))
  852. {
  853. switch (val)
  854. {
  855. case PersonType.Composer:
  856. type = PersonType.Composer;
  857. break;
  858. case PersonType.Conductor:
  859. type = PersonType.Conductor;
  860. break;
  861. case PersonType.Director:
  862. type = PersonType.Director;
  863. break;
  864. case PersonType.Lyricist:
  865. type = PersonType.Lyricist;
  866. break;
  867. case PersonType.Producer:
  868. type = PersonType.Producer;
  869. break;
  870. case PersonType.Writer:
  871. type = PersonType.Writer;
  872. break;
  873. case PersonType.GuestStar:
  874. type = PersonType.GuestStar;
  875. break;
  876. // unknown type --> actor
  877. default:
  878. type = PersonType.Actor;
  879. break;
  880. }
  881. }
  882. break;
  883. }
  884. case "order":
  885. case "sortorder":
  886. {
  887. var val = reader.ReadElementContentAsString();
  888. if (!string.IsNullOrWhiteSpace(val))
  889. {
  890. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  891. {
  892. sortOrder = intVal;
  893. }
  894. }
  895. break;
  896. }
  897. case "thumb":
  898. {
  899. var val = reader.ReadElementContentAsString();
  900. if (!string.IsNullOrWhiteSpace(val))
  901. {
  902. imageUrl = val;
  903. }
  904. break;
  905. }
  906. default:
  907. reader.Skip();
  908. break;
  909. }
  910. }
  911. else
  912. {
  913. reader.Read();
  914. }
  915. }
  916. return new PersonInfo
  917. {
  918. Name = name.Trim(),
  919. Role = role,
  920. Type = type,
  921. SortOrder = sortOrder,
  922. ImageUrl = imageUrl
  923. };
  924. }
  925. internal XmlReaderSettings GetXmlReaderSettings()
  926. => new XmlReaderSettings()
  927. {
  928. ValidationType = ValidationType.None,
  929. CheckCharacters = false,
  930. IgnoreProcessingInstructions = true,
  931. IgnoreComments = true
  932. };
  933. /// <summary>
  934. /// Used to split names of comma or pipe delimeted genres and people.
  935. /// </summary>
  936. /// <param name="value">The value.</param>
  937. /// <returns>IEnumerable{System.String}.</returns>
  938. private IEnumerable<string> SplitNames(string value)
  939. {
  940. value = value ?? string.Empty;
  941. // Only split by comma if there is no pipe in the string
  942. // We have to be careful to not split names like Matthew, Jr.
  943. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  944. ? new[] { ',' }
  945. : new[] { '|', ';' };
  946. value = value.Trim().Trim(separator);
  947. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  948. }
  949. }
  950. }