BaseNfoParser.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. type = val switch
  854. {
  855. PersonType.Composer => PersonType.Composer,
  856. PersonType.Conductor => PersonType.Conductor,
  857. PersonType.Director => PersonType.Director,
  858. PersonType.Lyricist => PersonType.Lyricist,
  859. PersonType.Producer => PersonType.Producer,
  860. PersonType.Writer => PersonType.Writer,
  861. PersonType.GuestStar => PersonType.GuestStar,
  862. // unknown type --> actor
  863. _ => PersonType.Actor
  864. };
  865. }
  866. break;
  867. }
  868. case "order":
  869. case "sortorder":
  870. {
  871. var val = reader.ReadElementContentAsString();
  872. if (!string.IsNullOrWhiteSpace(val))
  873. {
  874. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out var intVal))
  875. {
  876. sortOrder = intVal;
  877. }
  878. }
  879. break;
  880. }
  881. case "thumb":
  882. {
  883. var val = reader.ReadElementContentAsString();
  884. if (!string.IsNullOrWhiteSpace(val))
  885. {
  886. imageUrl = val;
  887. }
  888. break;
  889. }
  890. default:
  891. reader.Skip();
  892. break;
  893. }
  894. }
  895. else
  896. {
  897. reader.Read();
  898. }
  899. }
  900. return new PersonInfo
  901. {
  902. Name = name.Trim(),
  903. Role = role,
  904. Type = type,
  905. SortOrder = sortOrder,
  906. ImageUrl = imageUrl
  907. };
  908. }
  909. internal XmlReaderSettings GetXmlReaderSettings()
  910. => new XmlReaderSettings()
  911. {
  912. ValidationType = ValidationType.None,
  913. CheckCharacters = false,
  914. IgnoreProcessingInstructions = true,
  915. IgnoreComments = true
  916. };
  917. /// <summary>
  918. /// Used to split names of comma or pipe delimeted genres and people.
  919. /// </summary>
  920. /// <param name="value">The value.</param>
  921. /// <returns>IEnumerable{System.String}.</returns>
  922. private IEnumerable<string> SplitNames(string value)
  923. {
  924. value = value ?? string.Empty;
  925. // Only split by comma if there is no pipe in the string
  926. // We have to be careful to not split names like Matthew, Jr.
  927. var separator = value.IndexOf('|', StringComparison.Ordinal) == -1 && value.IndexOf(';', StringComparison.Ordinal) == -1
  928. ? new[] { ',' }
  929. : new[] { '|', ';' };
  930. value = value.Trim().Trim(separator);
  931. return string.IsNullOrWhiteSpace(value) ? Array.Empty<string>() : value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
  932. }
  933. }
  934. }