BaseNfoParser.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Extensions;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.XbmcMetadata.Configuration;
  8. using MediaBrowser.XbmcMetadata.Savers;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Text.RegularExpressions;
  16. using System.Threading;
  17. using System.Xml;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Xml;
  20. namespace MediaBrowser.XbmcMetadata.Parsers
  21. {
  22. public class BaseNfoParser<T>
  23. where T : BaseItem
  24. {
  25. /// <summary>
  26. /// The logger
  27. /// </summary>
  28. protected ILogger Logger { get; private set; }
  29. protected IFileSystem FileSystem { get; private set; }
  30. protected IProviderManager ProviderManager { get; private set; }
  31. protected IXmlReaderSettingsFactory XmlReaderSettingsFactory { get; private set; }
  32. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  33. private readonly IConfigurationManager _config;
  34. private Dictionary<string, string> _validProviderIds;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
  37. /// </summary>
  38. public BaseNfoParser(ILogger logger, IConfigurationManager config, IProviderManager providerManager, IFileSystem fileSystem, IXmlReaderSettingsFactory xmlReaderSettingsFactory)
  39. {
  40. Logger = logger;
  41. _config = config;
  42. ProviderManager = providerManager;
  43. FileSystem = fileSystem;
  44. XmlReaderSettingsFactory = xmlReaderSettingsFactory;
  45. }
  46. /// <summary>
  47. /// Fetches metadata for an item from one xml file
  48. /// </summary>
  49. /// <param name="item">The item.</param>
  50. /// <param name="metadataFile">The metadata file.</param>
  51. /// <param name="cancellationToken">The cancellation token.</param>
  52. /// <exception cref="System.ArgumentNullException">
  53. /// </exception>
  54. public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
  55. {
  56. if (item == null)
  57. {
  58. throw new ArgumentNullException();
  59. }
  60. if (string.IsNullOrEmpty(metadataFile))
  61. {
  62. throw new ArgumentNullException();
  63. }
  64. var settings = XmlReaderSettingsFactory.Create(false);
  65. settings.CheckCharacters = false;
  66. settings.IgnoreProcessingInstructions = true;
  67. settings.IgnoreComments = true;
  68. _validProviderIds = _validProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  69. var idInfos = ProviderManager.GetExternalIdInfos(item.Item);
  70. foreach (var info in idInfos)
  71. {
  72. var id = info.Key + "Id";
  73. if (!_validProviderIds.ContainsKey(id))
  74. {
  75. _validProviderIds.Add(id, info.Key);
  76. }
  77. }
  78. //Additional Mappings
  79. _validProviderIds.Add("collectionnumber", "TmdbCollection");
  80. _validProviderIds.Add("tmdbcolid", "TmdbCollection");
  81. _validProviderIds.Add("imdb_id", "Imdb");
  82. Fetch(item, metadataFile, settings, cancellationToken);
  83. }
  84. protected virtual bool SupportsUrlAfterClosingXmlTag
  85. {
  86. get { return false; }
  87. }
  88. /// <summary>
  89. /// Fetches the specified item.
  90. /// </summary>
  91. /// <param name="item">The item.</param>
  92. /// <param name="metadataFile">The metadata file.</param>
  93. /// <param name="settings">The settings.</param>
  94. /// <param name="cancellationToken">The cancellation token.</param>
  95. private void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
  96. {
  97. if (!SupportsUrlAfterClosingXmlTag)
  98. {
  99. using (var fileStream = FileSystem.OpenRead(metadataFile))
  100. {
  101. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  102. {
  103. // Use XmlReader for best performance
  104. using (var reader = XmlReader.Create(streamReader, settings))
  105. {
  106. item.ResetPeople();
  107. reader.MoveToContent();
  108. reader.Read();
  109. // Loop through each element
  110. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  111. {
  112. cancellationToken.ThrowIfCancellationRequested();
  113. if (reader.NodeType == XmlNodeType.Element)
  114. {
  115. FetchDataFromXmlNode(reader, item);
  116. }
  117. else
  118. {
  119. reader.Read();
  120. }
  121. }
  122. }
  123. }
  124. }
  125. return;
  126. }
  127. using (var fileStream = FileSystem.OpenRead(metadataFile))
  128. {
  129. using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
  130. {
  131. item.ResetPeople();
  132. // Need to handle a url after the xml data
  133. // http://kodi.wiki/view/NFO_files/movies
  134. var xml = streamReader.ReadToEnd();
  135. // Find last closing Tag
  136. // Need to do this in two steps to account for random > characters after the closing xml
  137. var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
  138. // If closing tag exists, move to end of Tag
  139. if (index != -1)
  140. {
  141. index = xml.IndexOf('>', index);
  142. }
  143. if (index != -1)
  144. {
  145. var endingXml = xml.Substring(index);
  146. ParseProviderLinks(item.Item, endingXml);
  147. // If the file is just an imdb url, don't go any further
  148. if (index == 0)
  149. {
  150. return;
  151. }
  152. xml = xml.Substring(0, index + 1);
  153. }
  154. else
  155. {
  156. // If the file is just an Imdb url, handle that
  157. ParseProviderLinks(item.Item, xml);
  158. return;
  159. }
  160. using (var ms = new MemoryStream())
  161. {
  162. var bytes = Encoding.UTF8.GetBytes(xml);
  163. ms.Write(bytes, 0, bytes.Length);
  164. ms.Position = 0;
  165. // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
  166. try
  167. {
  168. // Use XmlReader for best performance
  169. using (var reader = XmlReader.Create(ms, settings))
  170. {
  171. reader.MoveToContent();
  172. reader.Read();
  173. // Loop through each element
  174. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  175. {
  176. cancellationToken.ThrowIfCancellationRequested();
  177. if (reader.NodeType == XmlNodeType.Element)
  178. {
  179. FetchDataFromXmlNode(reader, item);
  180. }
  181. else
  182. {
  183. reader.Read();
  184. }
  185. }
  186. }
  187. }
  188. catch (XmlException)
  189. {
  190. }
  191. }
  192. }
  193. }
  194. }
  195. private void ParseProviderLinks(T item, string xml)
  196. {
  197. //Look for a match for the Regex pattern "tt" followed by 7 digits
  198. Match m = Regex.Match(xml, @"tt([0-9]{7})", RegexOptions.IgnoreCase);
  199. if (m.Success)
  200. {
  201. item.SetProviderId(MetadataProviders.Imdb, m.Value);
  202. }
  203. // Support Tmdb
  204. // http://www.themoviedb.org/movie/36557
  205. var srch = "themoviedb.org/movie/";
  206. var index = xml.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  207. if (index != -1)
  208. {
  209. var tmdbId = xml.Substring(index + srch.Length).TrimEnd('/');
  210. int value;
  211. if (!string.IsNullOrWhiteSpace(tmdbId) && int.TryParse(tmdbId, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
  212. {
  213. item.SetProviderId(MetadataProviders.Tmdb, tmdbId);
  214. }
  215. }
  216. }
  217. protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
  218. {
  219. var item = itemResult.Item;
  220. var userDataUserId = _config.GetNfoConfiguration().UserId;
  221. switch (reader.Name)
  222. {
  223. // DateCreated
  224. case "dateadded":
  225. {
  226. var val = reader.ReadElementContentAsString();
  227. if (!string.IsNullOrWhiteSpace(val))
  228. {
  229. DateTime added;
  230. if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  231. {
  232. item.DateCreated = added.ToUniversalTime();
  233. }
  234. else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  235. {
  236. item.DateCreated = added.ToUniversalTime();
  237. }
  238. else
  239. {
  240. Logger.Warn("Invalid Added value found: " + val);
  241. }
  242. }
  243. break;
  244. }
  245. case "originaltitle":
  246. {
  247. var val = reader.ReadElementContentAsString();
  248. if (!string.IsNullOrEmpty(val))
  249. {
  250. item.OriginalTitle = val;
  251. }
  252. break;
  253. }
  254. case "type":
  255. item.DisplayMediaType = reader.ReadElementContentAsString();
  256. break;
  257. case "title":
  258. case "localtitle":
  259. item.Name = reader.ReadElementContentAsString();
  260. break;
  261. case "criticrating":
  262. {
  263. var text = reader.ReadElementContentAsString();
  264. if (!string.IsNullOrEmpty(text))
  265. {
  266. float value;
  267. if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
  268. {
  269. item.CriticRating = value;
  270. }
  271. }
  272. break;
  273. }
  274. case "budget":
  275. {
  276. var text = reader.ReadElementContentAsString();
  277. var hasBudget = item as IHasBudget;
  278. if (hasBudget != null)
  279. {
  280. double value;
  281. if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
  282. {
  283. hasBudget.Budget = value;
  284. }
  285. }
  286. break;
  287. }
  288. case "revenue":
  289. {
  290. var text = reader.ReadElementContentAsString();
  291. var hasBudget = item as IHasBudget;
  292. if (hasBudget != null)
  293. {
  294. double value;
  295. if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
  296. {
  297. hasBudget.Revenue = value;
  298. }
  299. }
  300. break;
  301. }
  302. case "metascore":
  303. {
  304. var text = reader.ReadElementContentAsString();
  305. var hasMetascore = item as IHasMetascore;
  306. if (hasMetascore != null)
  307. {
  308. float value;
  309. if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
  310. {
  311. hasMetascore.Metascore = value;
  312. }
  313. }
  314. break;
  315. }
  316. case "awardsummary":
  317. {
  318. var text = reader.ReadElementContentAsString();
  319. var hasAwards = item as IHasAwards;
  320. if (hasAwards != null)
  321. {
  322. if (!string.IsNullOrWhiteSpace(text))
  323. {
  324. hasAwards.AwardSummary = text;
  325. }
  326. }
  327. break;
  328. }
  329. case "sorttitle":
  330. {
  331. var val = reader.ReadElementContentAsString();
  332. if (!string.IsNullOrWhiteSpace(val))
  333. {
  334. item.ForcedSortName = val;
  335. }
  336. break;
  337. }
  338. case "outline":
  339. {
  340. var val = reader.ReadElementContentAsString();
  341. if (!string.IsNullOrWhiteSpace(val))
  342. {
  343. item.ShortOverview = val;
  344. }
  345. break;
  346. }
  347. case "biography":
  348. case "plot":
  349. case "review":
  350. {
  351. var val = reader.ReadElementContentAsString();
  352. if (!string.IsNullOrWhiteSpace(val))
  353. {
  354. item.Overview = val;
  355. }
  356. break;
  357. }
  358. case "criticratingsummary":
  359. {
  360. var val = reader.ReadElementContentAsString();
  361. if (!string.IsNullOrWhiteSpace(val))
  362. {
  363. item.CriticRatingSummary = val;
  364. }
  365. break;
  366. }
  367. case "language":
  368. {
  369. var val = reader.ReadElementContentAsString();
  370. item.PreferredMetadataLanguage = val;
  371. break;
  372. }
  373. case "countrycode":
  374. {
  375. var val = reader.ReadElementContentAsString();
  376. item.PreferredMetadataCountryCode = val;
  377. break;
  378. }
  379. case "website":
  380. {
  381. var val = reader.ReadElementContentAsString();
  382. if (!string.IsNullOrWhiteSpace(val))
  383. {
  384. item.HomePageUrl = val;
  385. }
  386. break;
  387. }
  388. case "lockedfields":
  389. {
  390. var fields = new List<MetadataFields>();
  391. var val = reader.ReadElementContentAsString();
  392. if (!string.IsNullOrWhiteSpace(val))
  393. {
  394. var list = val.Split('|').Select(i =>
  395. {
  396. MetadataFields field;
  397. if (Enum.TryParse<MetadataFields>(i, true, out field))
  398. {
  399. return (MetadataFields?)field;
  400. }
  401. return null;
  402. }).Where(i => i.HasValue).Select(i => i.Value);
  403. fields.AddRange(list);
  404. }
  405. item.LockedFields = fields;
  406. break;
  407. }
  408. case "tagline":
  409. {
  410. var val = reader.ReadElementContentAsString();
  411. if (!string.IsNullOrWhiteSpace(val))
  412. {
  413. item.Tagline = val;
  414. }
  415. break;
  416. }
  417. case "country":
  418. {
  419. var val = reader.ReadElementContentAsString();
  420. if (!string.IsNullOrWhiteSpace(val))
  421. {
  422. item.ProductionLocations = val.Split('/')
  423. .Select(i => i.Trim())
  424. .Where(i => !string.IsNullOrWhiteSpace(i))
  425. .ToList();
  426. }
  427. break;
  428. }
  429. case "mpaa":
  430. {
  431. var rating = reader.ReadElementContentAsString();
  432. if (!string.IsNullOrWhiteSpace(rating))
  433. {
  434. item.OfficialRating = rating;
  435. }
  436. break;
  437. }
  438. case "mpaadescription":
  439. {
  440. var rating = reader.ReadElementContentAsString();
  441. if (!string.IsNullOrWhiteSpace(rating))
  442. {
  443. item.OfficialRatingDescription = rating;
  444. }
  445. break;
  446. }
  447. case "customrating":
  448. {
  449. var val = reader.ReadElementContentAsString();
  450. if (!string.IsNullOrWhiteSpace(val))
  451. {
  452. item.CustomRating = val;
  453. }
  454. break;
  455. }
  456. case "runtime":
  457. {
  458. var text = reader.ReadElementContentAsString();
  459. if (!string.IsNullOrWhiteSpace(text))
  460. {
  461. int runtime;
  462. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out runtime))
  463. {
  464. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  465. }
  466. }
  467. break;
  468. }
  469. case "aspectratio":
  470. {
  471. var val = reader.ReadElementContentAsString();
  472. var hasAspectRatio = item as IHasAspectRatio;
  473. if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
  474. {
  475. hasAspectRatio.AspectRatio = val;
  476. }
  477. break;
  478. }
  479. case "lockdata":
  480. {
  481. var val = reader.ReadElementContentAsString();
  482. if (!string.IsNullOrWhiteSpace(val))
  483. {
  484. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  485. }
  486. break;
  487. }
  488. case "studio":
  489. {
  490. var val = reader.ReadElementContentAsString();
  491. if (!string.IsNullOrWhiteSpace(val))
  492. {
  493. //var parts = val.Split('/')
  494. // .Select(i => i.Trim())
  495. // .Where(i => !string.IsNullOrWhiteSpace(i));
  496. //foreach (var p in parts)
  497. //{
  498. // item.AddStudio(p);
  499. //}
  500. item.AddStudio(val);
  501. }
  502. break;
  503. }
  504. case "director":
  505. {
  506. var val = reader.ReadElementContentAsString();
  507. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  508. {
  509. if (string.IsNullOrWhiteSpace(p.Name))
  510. {
  511. continue;
  512. }
  513. itemResult.AddPerson(p);
  514. }
  515. break;
  516. }
  517. case "credits":
  518. {
  519. var val = reader.ReadElementContentAsString();
  520. if (!string.IsNullOrWhiteSpace(val))
  521. {
  522. var parts = val.Split('/').Select(i => i.Trim())
  523. .Where(i => !string.IsNullOrEmpty(i));
  524. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  525. {
  526. if (string.IsNullOrWhiteSpace(p.Name))
  527. {
  528. continue;
  529. }
  530. itemResult.AddPerson(p);
  531. }
  532. }
  533. break;
  534. }
  535. case "writer":
  536. {
  537. var val = reader.ReadElementContentAsString();
  538. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  539. {
  540. if (string.IsNullOrWhiteSpace(p.Name))
  541. {
  542. continue;
  543. }
  544. itemResult.AddPerson(p);
  545. }
  546. break;
  547. }
  548. case "actor":
  549. {
  550. if (!reader.IsEmptyElement)
  551. {
  552. using (var subtree = reader.ReadSubtree())
  553. {
  554. var person = GetPersonFromXmlNode(subtree);
  555. if (!string.IsNullOrWhiteSpace(person.Name))
  556. {
  557. itemResult.AddPerson(person);
  558. }
  559. }
  560. }
  561. else
  562. {
  563. reader.Read();
  564. }
  565. break;
  566. }
  567. case "trailer":
  568. {
  569. var val = reader.ReadElementContentAsString();
  570. var hasTrailer = item as IHasTrailers;
  571. if (hasTrailer != null)
  572. {
  573. if (!string.IsNullOrWhiteSpace(val))
  574. {
  575. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "https://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  576. hasTrailer.AddTrailerUrl(val, false);
  577. }
  578. }
  579. break;
  580. }
  581. case "displayorder":
  582. {
  583. var val = reader.ReadElementContentAsString();
  584. var hasDisplayOrder = item as IHasDisplayOrder;
  585. if (hasDisplayOrder != null)
  586. {
  587. if (!string.IsNullOrWhiteSpace(val))
  588. {
  589. hasDisplayOrder.DisplayOrder = val;
  590. }
  591. }
  592. break;
  593. }
  594. case "year":
  595. {
  596. var val = reader.ReadElementContentAsString();
  597. if (!string.IsNullOrWhiteSpace(val))
  598. {
  599. int productionYear;
  600. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  601. {
  602. item.ProductionYear = productionYear;
  603. }
  604. }
  605. break;
  606. }
  607. case "rating":
  608. {
  609. var rating = reader.ReadElementContentAsString();
  610. if (!string.IsNullOrWhiteSpace(rating))
  611. {
  612. float val;
  613. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  614. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  615. {
  616. item.CommunityRating = val;
  617. }
  618. }
  619. break;
  620. }
  621. case "aired":
  622. case "formed":
  623. case "premiered":
  624. case "releasedate":
  625. {
  626. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  627. var val = reader.ReadElementContentAsString();
  628. if (!string.IsNullOrWhiteSpace(val))
  629. {
  630. DateTime date;
  631. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  632. {
  633. item.PremiereDate = date.ToUniversalTime();
  634. item.ProductionYear = date.Year;
  635. }
  636. }
  637. break;
  638. }
  639. case "enddate":
  640. {
  641. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  642. var val = reader.ReadElementContentAsString();
  643. if (!string.IsNullOrWhiteSpace(val))
  644. {
  645. DateTime date;
  646. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  647. {
  648. item.EndDate = date.ToUniversalTime();
  649. }
  650. }
  651. break;
  652. }
  653. case "votes":
  654. {
  655. var val = reader.ReadElementContentAsString();
  656. if (!string.IsNullOrWhiteSpace(val))
  657. {
  658. int num;
  659. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  660. {
  661. item.VoteCount = num;
  662. }
  663. }
  664. break;
  665. }
  666. case "genre":
  667. {
  668. var val = reader.ReadElementContentAsString();
  669. if (!string.IsNullOrWhiteSpace(val))
  670. {
  671. var parts = val.Split('/')
  672. .Select(i => i.Trim())
  673. .Where(i => !string.IsNullOrWhiteSpace(i));
  674. foreach (var p in parts)
  675. {
  676. item.AddGenre(p);
  677. }
  678. }
  679. break;
  680. }
  681. case "style":
  682. case "tag":
  683. {
  684. var val = reader.ReadElementContentAsString();
  685. if (!string.IsNullOrWhiteSpace(val))
  686. {
  687. item.AddTag(val);
  688. }
  689. break;
  690. }
  691. case "plotkeyword":
  692. {
  693. var val = reader.ReadElementContentAsString();
  694. if (!string.IsNullOrWhiteSpace(val))
  695. {
  696. item.AddKeyword(val);
  697. }
  698. break;
  699. }
  700. case "fileinfo":
  701. {
  702. if (!reader.IsEmptyElement)
  703. {
  704. using (var subtree = reader.ReadSubtree())
  705. {
  706. FetchFromFileInfoNode(subtree, item);
  707. }
  708. }
  709. else
  710. {
  711. reader.Read();
  712. }
  713. break;
  714. }
  715. case "watched":
  716. {
  717. var val = reader.ReadElementContentAsString();
  718. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  719. {
  720. bool parsedValue;
  721. if (bool.TryParse(val, out parsedValue))
  722. {
  723. var userData = GetOrAdd(itemResult, userDataUserId);
  724. userData.Played = parsedValue;
  725. }
  726. }
  727. break;
  728. }
  729. case "playcount":
  730. {
  731. var val = reader.ReadElementContentAsString();
  732. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  733. {
  734. int parsedValue;
  735. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  736. {
  737. var userData = GetOrAdd(itemResult, userDataUserId);
  738. userData.PlayCount = parsedValue;
  739. if (parsedValue > 0)
  740. {
  741. userData.Played = true;
  742. }
  743. }
  744. }
  745. break;
  746. }
  747. case "lastplayed":
  748. {
  749. var val = reader.ReadElementContentAsString();
  750. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  751. {
  752. DateTime parsedValue;
  753. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  754. {
  755. var userData = GetOrAdd(itemResult, userDataUserId);
  756. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  757. }
  758. }
  759. break;
  760. }
  761. case "resume":
  762. {
  763. if (!reader.IsEmptyElement)
  764. {
  765. using (var subtree = reader.ReadSubtree())
  766. {
  767. if (!string.IsNullOrWhiteSpace(userDataUserId))
  768. {
  769. var userData = GetOrAdd(itemResult, userDataUserId);
  770. FetchFromResumeNode(subtree, item, userData);
  771. }
  772. }
  773. }
  774. else
  775. {
  776. reader.Read();
  777. }
  778. break;
  779. }
  780. case "isuserfavorite":
  781. {
  782. var val = reader.ReadElementContentAsString();
  783. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  784. {
  785. bool parsedValue;
  786. if (bool.TryParse(val, out parsedValue))
  787. {
  788. var userData = GetOrAdd(itemResult, userDataUserId);
  789. userData.IsFavorite = parsedValue;
  790. }
  791. }
  792. break;
  793. }
  794. case "userrating":
  795. {
  796. var val = reader.ReadElementContentAsString();
  797. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  798. {
  799. double parsedValue;
  800. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  801. {
  802. var userData = GetOrAdd(itemResult, userDataUserId);
  803. userData.Rating = parsedValue;
  804. }
  805. }
  806. break;
  807. }
  808. default:
  809. string readerName = reader.Name;
  810. string providerIdValue;
  811. if (_validProviderIds.TryGetValue(readerName, out providerIdValue))
  812. {
  813. var id = reader.ReadElementContentAsString();
  814. if (!string.IsNullOrWhiteSpace(id))
  815. {
  816. item.SetProviderId(providerIdValue, id);
  817. }
  818. }
  819. else
  820. {
  821. reader.Skip();
  822. }
  823. break;
  824. }
  825. }
  826. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  827. {
  828. return result.GetOrAddUserData(userId);
  829. }
  830. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  831. {
  832. reader.MoveToContent();
  833. reader.Read();
  834. // Loop through each element
  835. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  836. {
  837. if (reader.NodeType == XmlNodeType.Element)
  838. {
  839. switch (reader.Name)
  840. {
  841. case "position":
  842. {
  843. var val = reader.ReadElementContentAsString();
  844. if (!string.IsNullOrWhiteSpace(val))
  845. {
  846. double parsedValue;
  847. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  848. {
  849. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  850. }
  851. }
  852. break;
  853. }
  854. default:
  855. reader.Skip();
  856. break;
  857. }
  858. }
  859. else
  860. {
  861. reader.Read();
  862. }
  863. }
  864. }
  865. private void FetchFromFileInfoNode(XmlReader reader, T item)
  866. {
  867. reader.MoveToContent();
  868. reader.Read();
  869. // Loop through each element
  870. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  871. {
  872. if (reader.NodeType == XmlNodeType.Element)
  873. {
  874. switch (reader.Name)
  875. {
  876. case "streamdetails":
  877. {
  878. if (reader.IsEmptyElement)
  879. {
  880. reader.Read();
  881. continue;
  882. }
  883. using (var subtree = reader.ReadSubtree())
  884. {
  885. FetchFromStreamDetailsNode(subtree, item);
  886. }
  887. break;
  888. }
  889. default:
  890. reader.Skip();
  891. break;
  892. }
  893. }
  894. else
  895. {
  896. reader.Read();
  897. }
  898. }
  899. }
  900. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  901. {
  902. reader.MoveToContent();
  903. reader.Read();
  904. // Loop through each element
  905. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  906. {
  907. if (reader.NodeType == XmlNodeType.Element)
  908. {
  909. switch (reader.Name)
  910. {
  911. case "video":
  912. {
  913. if (reader.IsEmptyElement)
  914. {
  915. reader.Read();
  916. continue;
  917. }
  918. using (var subtree = reader.ReadSubtree())
  919. {
  920. FetchFromVideoNode(subtree, item);
  921. }
  922. break;
  923. }
  924. default:
  925. reader.Skip();
  926. break;
  927. }
  928. }
  929. else
  930. {
  931. reader.Read();
  932. }
  933. }
  934. }
  935. private void FetchFromVideoNode(XmlReader reader, T item)
  936. {
  937. reader.MoveToContent();
  938. reader.Read();
  939. // Loop through each element
  940. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  941. {
  942. if (reader.NodeType == XmlNodeType.Element)
  943. {
  944. switch (reader.Name)
  945. {
  946. case "format3d":
  947. {
  948. var val = reader.ReadElementContentAsString();
  949. var video = item as Video;
  950. if (video != null)
  951. {
  952. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  953. {
  954. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  955. }
  956. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  957. {
  958. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  959. }
  960. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  961. {
  962. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  963. }
  964. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  965. {
  966. video.Video3DFormat = Video3DFormat.FullSideBySide;
  967. }
  968. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  969. {
  970. video.Video3DFormat = Video3DFormat.MVC;
  971. }
  972. }
  973. break;
  974. }
  975. default:
  976. reader.Skip();
  977. break;
  978. }
  979. }
  980. else
  981. {
  982. reader.Read();
  983. }
  984. }
  985. }
  986. /// <summary>
  987. /// Gets the persons from XML node.
  988. /// </summary>
  989. /// <param name="reader">The reader.</param>
  990. /// <returns>IEnumerable{PersonInfo}.</returns>
  991. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  992. {
  993. var name = string.Empty;
  994. var type = PersonType.Actor; // If type is not specified assume actor
  995. var role = string.Empty;
  996. int? sortOrder = null;
  997. reader.MoveToContent();
  998. reader.Read();
  999. // Loop through each element
  1000. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  1001. {
  1002. if (reader.NodeType == XmlNodeType.Element)
  1003. {
  1004. switch (reader.Name)
  1005. {
  1006. case "name":
  1007. name = reader.ReadElementContentAsString() ?? string.Empty;
  1008. break;
  1009. case "type":
  1010. {
  1011. var val = reader.ReadElementContentAsString();
  1012. if (!string.IsNullOrWhiteSpace(val))
  1013. {
  1014. type = val;
  1015. }
  1016. break;
  1017. }
  1018. case "role":
  1019. {
  1020. var val = reader.ReadElementContentAsString();
  1021. if (!string.IsNullOrWhiteSpace(val))
  1022. {
  1023. role = val;
  1024. }
  1025. break;
  1026. }
  1027. case "sortorder":
  1028. {
  1029. var val = reader.ReadElementContentAsString();
  1030. if (!string.IsNullOrWhiteSpace(val))
  1031. {
  1032. int intVal;
  1033. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  1034. {
  1035. sortOrder = intVal;
  1036. }
  1037. }
  1038. break;
  1039. }
  1040. default:
  1041. reader.Skip();
  1042. break;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. reader.Read();
  1048. }
  1049. }
  1050. return new PersonInfo
  1051. {
  1052. Name = name.Trim(),
  1053. Role = role,
  1054. Type = type,
  1055. SortOrder = sortOrder
  1056. };
  1057. }
  1058. /// <summary>
  1059. /// Used to split names of comma or pipe delimeted genres and people
  1060. /// </summary>
  1061. /// <param name="value">The value.</param>
  1062. /// <returns>IEnumerable{System.String}.</returns>
  1063. private IEnumerable<string> SplitNames(string value)
  1064. {
  1065. value = value ?? string.Empty;
  1066. // Only split by comma if there is no pipe in the string
  1067. // We have to be careful to not split names like Matthew, Jr.
  1068. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1069. value = value.Trim().Trim(separator);
  1070. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1071. }
  1072. /// <summary>
  1073. /// Provides an additional overload for string.split
  1074. /// </summary>
  1075. /// <param name="val">The val.</param>
  1076. /// <param name="separators">The separators.</param>
  1077. /// <param name="options">The options.</param>
  1078. /// <returns>System.String[][].</returns>
  1079. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1080. {
  1081. return val.Split(separators, options);
  1082. }
  1083. }
  1084. }