BaseNfoParser.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  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 "awardsummary":
  275. {
  276. var text = reader.ReadElementContentAsString();
  277. var hasAwards = item as IHasAwards;
  278. if (hasAwards != null)
  279. {
  280. if (!string.IsNullOrWhiteSpace(text))
  281. {
  282. hasAwards.AwardSummary = text;
  283. }
  284. }
  285. break;
  286. }
  287. case "sorttitle":
  288. {
  289. var val = reader.ReadElementContentAsString();
  290. if (!string.IsNullOrWhiteSpace(val))
  291. {
  292. item.ForcedSortName = val;
  293. }
  294. break;
  295. }
  296. case "biography":
  297. case "plot":
  298. case "review":
  299. {
  300. var val = reader.ReadElementContentAsString();
  301. if (!string.IsNullOrWhiteSpace(val))
  302. {
  303. item.Overview = val;
  304. }
  305. break;
  306. }
  307. case "criticratingsummary":
  308. {
  309. var val = reader.ReadElementContentAsString();
  310. if (!string.IsNullOrWhiteSpace(val))
  311. {
  312. item.CriticRatingSummary = val;
  313. }
  314. break;
  315. }
  316. case "language":
  317. {
  318. var val = reader.ReadElementContentAsString();
  319. item.PreferredMetadataLanguage = val;
  320. break;
  321. }
  322. case "countrycode":
  323. {
  324. var val = reader.ReadElementContentAsString();
  325. item.PreferredMetadataCountryCode = val;
  326. break;
  327. }
  328. case "website":
  329. {
  330. var val = reader.ReadElementContentAsString();
  331. if (!string.IsNullOrWhiteSpace(val))
  332. {
  333. item.HomePageUrl = val;
  334. }
  335. break;
  336. }
  337. case "lockedfields":
  338. {
  339. var fields = new List<MetadataFields>();
  340. var val = reader.ReadElementContentAsString();
  341. if (!string.IsNullOrWhiteSpace(val))
  342. {
  343. var list = val.Split('|').Select(i =>
  344. {
  345. MetadataFields field;
  346. if (Enum.TryParse<MetadataFields>(i, true, out field))
  347. {
  348. return (MetadataFields?)field;
  349. }
  350. return null;
  351. }).Where(i => i.HasValue).Select(i => i.Value);
  352. fields.AddRange(list);
  353. }
  354. item.LockedFields = fields;
  355. break;
  356. }
  357. case "tagline":
  358. {
  359. var val = reader.ReadElementContentAsString();
  360. if (!string.IsNullOrWhiteSpace(val))
  361. {
  362. item.Tagline = val;
  363. }
  364. break;
  365. }
  366. case "country":
  367. {
  368. var val = reader.ReadElementContentAsString();
  369. if (!string.IsNullOrWhiteSpace(val))
  370. {
  371. item.ProductionLocations.AddRange(val.Split('/')
  372. .Select(i => i.Trim())
  373. .Where(i => !string.IsNullOrWhiteSpace(i)));
  374. }
  375. break;
  376. }
  377. case "mpaa":
  378. {
  379. var rating = reader.ReadElementContentAsString();
  380. if (!string.IsNullOrWhiteSpace(rating))
  381. {
  382. item.OfficialRating = rating;
  383. }
  384. break;
  385. }
  386. case "mpaadescription":
  387. {
  388. var rating = reader.ReadElementContentAsString();
  389. if (!string.IsNullOrWhiteSpace(rating))
  390. {
  391. item.OfficialRatingDescription = rating;
  392. }
  393. break;
  394. }
  395. case "customrating":
  396. {
  397. var val = reader.ReadElementContentAsString();
  398. if (!string.IsNullOrWhiteSpace(val))
  399. {
  400. item.CustomRating = val;
  401. }
  402. break;
  403. }
  404. case "runtime":
  405. {
  406. var text = reader.ReadElementContentAsString();
  407. if (!string.IsNullOrWhiteSpace(text))
  408. {
  409. int runtime;
  410. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out runtime))
  411. {
  412. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  413. }
  414. }
  415. break;
  416. }
  417. case "aspectratio":
  418. {
  419. var val = reader.ReadElementContentAsString();
  420. var hasAspectRatio = item as IHasAspectRatio;
  421. if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
  422. {
  423. hasAspectRatio.AspectRatio = val;
  424. }
  425. break;
  426. }
  427. case "lockdata":
  428. {
  429. var val = reader.ReadElementContentAsString();
  430. if (!string.IsNullOrWhiteSpace(val))
  431. {
  432. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  433. }
  434. break;
  435. }
  436. case "studio":
  437. {
  438. var val = reader.ReadElementContentAsString();
  439. if (!string.IsNullOrWhiteSpace(val))
  440. {
  441. //var parts = val.Split('/')
  442. // .Select(i => i.Trim())
  443. // .Where(i => !string.IsNullOrWhiteSpace(i));
  444. //foreach (var p in parts)
  445. //{
  446. // item.AddStudio(p);
  447. //}
  448. item.AddStudio(val);
  449. }
  450. break;
  451. }
  452. case "director":
  453. {
  454. var val = reader.ReadElementContentAsString();
  455. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  456. {
  457. if (string.IsNullOrWhiteSpace(p.Name))
  458. {
  459. continue;
  460. }
  461. itemResult.AddPerson(p);
  462. }
  463. break;
  464. }
  465. case "credits":
  466. {
  467. var val = reader.ReadElementContentAsString();
  468. if (!string.IsNullOrWhiteSpace(val))
  469. {
  470. var parts = val.Split('/').Select(i => i.Trim())
  471. .Where(i => !string.IsNullOrEmpty(i));
  472. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  473. {
  474. if (string.IsNullOrWhiteSpace(p.Name))
  475. {
  476. continue;
  477. }
  478. itemResult.AddPerson(p);
  479. }
  480. }
  481. break;
  482. }
  483. case "writer":
  484. {
  485. var val = reader.ReadElementContentAsString();
  486. foreach (var p in SplitNames(val).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  487. {
  488. if (string.IsNullOrWhiteSpace(p.Name))
  489. {
  490. continue;
  491. }
  492. itemResult.AddPerson(p);
  493. }
  494. break;
  495. }
  496. case "actor":
  497. {
  498. if (!reader.IsEmptyElement)
  499. {
  500. using (var subtree = reader.ReadSubtree())
  501. {
  502. var person = GetPersonFromXmlNode(subtree);
  503. if (!string.IsNullOrWhiteSpace(person.Name))
  504. {
  505. itemResult.AddPerson(person);
  506. }
  507. }
  508. }
  509. else
  510. {
  511. reader.Read();
  512. }
  513. break;
  514. }
  515. case "trailer":
  516. {
  517. var val = reader.ReadElementContentAsString();
  518. var hasTrailer = item as IHasTrailers;
  519. if (hasTrailer != null)
  520. {
  521. if (!string.IsNullOrWhiteSpace(val))
  522. {
  523. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "https://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  524. hasTrailer.AddTrailerUrl(val, false);
  525. }
  526. }
  527. break;
  528. }
  529. case "displayorder":
  530. {
  531. var val = reader.ReadElementContentAsString();
  532. var hasDisplayOrder = item as IHasDisplayOrder;
  533. if (hasDisplayOrder != null)
  534. {
  535. if (!string.IsNullOrWhiteSpace(val))
  536. {
  537. hasDisplayOrder.DisplayOrder = val;
  538. }
  539. }
  540. break;
  541. }
  542. case "year":
  543. {
  544. var val = reader.ReadElementContentAsString();
  545. if (!string.IsNullOrWhiteSpace(val))
  546. {
  547. int productionYear;
  548. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  549. {
  550. item.ProductionYear = productionYear;
  551. }
  552. }
  553. break;
  554. }
  555. case "rating":
  556. {
  557. var rating = reader.ReadElementContentAsString();
  558. if (!string.IsNullOrWhiteSpace(rating))
  559. {
  560. float val;
  561. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  562. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  563. {
  564. item.CommunityRating = val;
  565. }
  566. }
  567. break;
  568. }
  569. case "aired":
  570. case "formed":
  571. case "premiered":
  572. case "releasedate":
  573. {
  574. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  575. var val = reader.ReadElementContentAsString();
  576. if (!string.IsNullOrWhiteSpace(val))
  577. {
  578. DateTime date;
  579. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  580. {
  581. item.PremiereDate = date.ToUniversalTime();
  582. item.ProductionYear = date.Year;
  583. }
  584. }
  585. break;
  586. }
  587. case "enddate":
  588. {
  589. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  590. var val = reader.ReadElementContentAsString();
  591. if (!string.IsNullOrWhiteSpace(val))
  592. {
  593. DateTime date;
  594. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  595. {
  596. item.EndDate = date.ToUniversalTime();
  597. }
  598. }
  599. break;
  600. }
  601. case "votes":
  602. {
  603. var val = reader.ReadElementContentAsString();
  604. if (!string.IsNullOrWhiteSpace(val))
  605. {
  606. int num;
  607. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  608. {
  609. item.VoteCount = num;
  610. }
  611. }
  612. break;
  613. }
  614. case "genre":
  615. {
  616. var val = reader.ReadElementContentAsString();
  617. if (!string.IsNullOrWhiteSpace(val))
  618. {
  619. var parts = val.Split('/')
  620. .Select(i => i.Trim())
  621. .Where(i => !string.IsNullOrWhiteSpace(i));
  622. foreach (var p in parts)
  623. {
  624. item.AddGenre(p);
  625. }
  626. }
  627. break;
  628. }
  629. case "style":
  630. case "tag":
  631. {
  632. var val = reader.ReadElementContentAsString();
  633. if (!string.IsNullOrWhiteSpace(val))
  634. {
  635. item.AddTag(val);
  636. }
  637. break;
  638. }
  639. case "plotkeyword":
  640. {
  641. var val = reader.ReadElementContentAsString();
  642. if (!string.IsNullOrWhiteSpace(val))
  643. {
  644. item.AddKeyword(val);
  645. }
  646. break;
  647. }
  648. case "fileinfo":
  649. {
  650. if (!reader.IsEmptyElement)
  651. {
  652. using (var subtree = reader.ReadSubtree())
  653. {
  654. FetchFromFileInfoNode(subtree, item);
  655. }
  656. }
  657. else
  658. {
  659. reader.Read();
  660. }
  661. break;
  662. }
  663. case "watched":
  664. {
  665. var val = reader.ReadElementContentAsString();
  666. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  667. {
  668. bool parsedValue;
  669. if (bool.TryParse(val, out parsedValue))
  670. {
  671. var userData = GetOrAdd(itemResult, userDataUserId);
  672. userData.Played = parsedValue;
  673. }
  674. }
  675. break;
  676. }
  677. case "playcount":
  678. {
  679. var val = reader.ReadElementContentAsString();
  680. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  681. {
  682. int parsedValue;
  683. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  684. {
  685. var userData = GetOrAdd(itemResult, userDataUserId);
  686. userData.PlayCount = parsedValue;
  687. if (parsedValue > 0)
  688. {
  689. userData.Played = true;
  690. }
  691. }
  692. }
  693. break;
  694. }
  695. case "lastplayed":
  696. {
  697. var val = reader.ReadElementContentAsString();
  698. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  699. {
  700. DateTime parsedValue;
  701. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  702. {
  703. var userData = GetOrAdd(itemResult, userDataUserId);
  704. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  705. }
  706. }
  707. break;
  708. }
  709. case "resume":
  710. {
  711. if (!reader.IsEmptyElement)
  712. {
  713. using (var subtree = reader.ReadSubtree())
  714. {
  715. if (!string.IsNullOrWhiteSpace(userDataUserId))
  716. {
  717. var userData = GetOrAdd(itemResult, userDataUserId);
  718. FetchFromResumeNode(subtree, item, userData);
  719. }
  720. }
  721. }
  722. else
  723. {
  724. reader.Read();
  725. }
  726. break;
  727. }
  728. case "isuserfavorite":
  729. {
  730. var val = reader.ReadElementContentAsString();
  731. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  732. {
  733. bool parsedValue;
  734. if (bool.TryParse(val, out parsedValue))
  735. {
  736. var userData = GetOrAdd(itemResult, userDataUserId);
  737. userData.IsFavorite = parsedValue;
  738. }
  739. }
  740. break;
  741. }
  742. case "userrating":
  743. {
  744. var val = reader.ReadElementContentAsString();
  745. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  746. {
  747. double parsedValue;
  748. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  749. {
  750. var userData = GetOrAdd(itemResult, userDataUserId);
  751. userData.Rating = parsedValue;
  752. }
  753. }
  754. break;
  755. }
  756. default:
  757. string readerName = reader.Name;
  758. string providerIdValue;
  759. if (_validProviderIds.TryGetValue(readerName, out providerIdValue))
  760. {
  761. var id = reader.ReadElementContentAsString();
  762. if (!string.IsNullOrWhiteSpace(id))
  763. {
  764. item.SetProviderId(providerIdValue, id);
  765. }
  766. }
  767. else
  768. {
  769. reader.Skip();
  770. }
  771. break;
  772. }
  773. }
  774. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  775. {
  776. return result.GetOrAddUserData(userId);
  777. }
  778. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  779. {
  780. reader.MoveToContent();
  781. reader.Read();
  782. // Loop through each element
  783. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  784. {
  785. if (reader.NodeType == XmlNodeType.Element)
  786. {
  787. switch (reader.Name)
  788. {
  789. case "position":
  790. {
  791. var val = reader.ReadElementContentAsString();
  792. if (!string.IsNullOrWhiteSpace(val))
  793. {
  794. double parsedValue;
  795. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  796. {
  797. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  798. }
  799. }
  800. break;
  801. }
  802. default:
  803. reader.Skip();
  804. break;
  805. }
  806. }
  807. else
  808. {
  809. reader.Read();
  810. }
  811. }
  812. }
  813. private void FetchFromFileInfoNode(XmlReader reader, T item)
  814. {
  815. reader.MoveToContent();
  816. reader.Read();
  817. // Loop through each element
  818. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  819. {
  820. if (reader.NodeType == XmlNodeType.Element)
  821. {
  822. switch (reader.Name)
  823. {
  824. case "streamdetails":
  825. {
  826. if (reader.IsEmptyElement)
  827. {
  828. reader.Read();
  829. continue;
  830. }
  831. using (var subtree = reader.ReadSubtree())
  832. {
  833. FetchFromStreamDetailsNode(subtree, item);
  834. }
  835. break;
  836. }
  837. default:
  838. reader.Skip();
  839. break;
  840. }
  841. }
  842. else
  843. {
  844. reader.Read();
  845. }
  846. }
  847. }
  848. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  849. {
  850. reader.MoveToContent();
  851. reader.Read();
  852. // Loop through each element
  853. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  854. {
  855. if (reader.NodeType == XmlNodeType.Element)
  856. {
  857. switch (reader.Name)
  858. {
  859. case "video":
  860. {
  861. if (reader.IsEmptyElement)
  862. {
  863. reader.Read();
  864. continue;
  865. }
  866. using (var subtree = reader.ReadSubtree())
  867. {
  868. FetchFromVideoNode(subtree, item);
  869. }
  870. break;
  871. }
  872. default:
  873. reader.Skip();
  874. break;
  875. }
  876. }
  877. else
  878. {
  879. reader.Read();
  880. }
  881. }
  882. }
  883. private void FetchFromVideoNode(XmlReader reader, T item)
  884. {
  885. reader.MoveToContent();
  886. reader.Read();
  887. // Loop through each element
  888. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  889. {
  890. if (reader.NodeType == XmlNodeType.Element)
  891. {
  892. switch (reader.Name)
  893. {
  894. case "format3d":
  895. {
  896. var val = reader.ReadElementContentAsString();
  897. var video = item as Video;
  898. if (video != null)
  899. {
  900. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  901. {
  902. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  903. }
  904. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  905. {
  906. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  907. }
  908. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  909. {
  910. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  911. }
  912. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  913. {
  914. video.Video3DFormat = Video3DFormat.FullSideBySide;
  915. }
  916. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  917. {
  918. video.Video3DFormat = Video3DFormat.MVC;
  919. }
  920. }
  921. break;
  922. }
  923. default:
  924. reader.Skip();
  925. break;
  926. }
  927. }
  928. else
  929. {
  930. reader.Read();
  931. }
  932. }
  933. }
  934. /// <summary>
  935. /// Gets the persons from XML node.
  936. /// </summary>
  937. /// <param name="reader">The reader.</param>
  938. /// <returns>IEnumerable{PersonInfo}.</returns>
  939. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  940. {
  941. var name = string.Empty;
  942. var type = PersonType.Actor; // If type is not specified assume actor
  943. var role = string.Empty;
  944. int? sortOrder = null;
  945. reader.MoveToContent();
  946. reader.Read();
  947. // Loop through each element
  948. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  949. {
  950. if (reader.NodeType == XmlNodeType.Element)
  951. {
  952. switch (reader.Name)
  953. {
  954. case "name":
  955. name = reader.ReadElementContentAsString() ?? string.Empty;
  956. break;
  957. case "type":
  958. {
  959. var val = reader.ReadElementContentAsString();
  960. if (!string.IsNullOrWhiteSpace(val))
  961. {
  962. type = val;
  963. }
  964. break;
  965. }
  966. case "role":
  967. {
  968. var val = reader.ReadElementContentAsString();
  969. if (!string.IsNullOrWhiteSpace(val))
  970. {
  971. role = val;
  972. }
  973. break;
  974. }
  975. case "sortorder":
  976. {
  977. var val = reader.ReadElementContentAsString();
  978. if (!string.IsNullOrWhiteSpace(val))
  979. {
  980. int intVal;
  981. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  982. {
  983. sortOrder = intVal;
  984. }
  985. }
  986. break;
  987. }
  988. default:
  989. reader.Skip();
  990. break;
  991. }
  992. }
  993. else
  994. {
  995. reader.Read();
  996. }
  997. }
  998. return new PersonInfo
  999. {
  1000. Name = name.Trim(),
  1001. Role = role,
  1002. Type = type,
  1003. SortOrder = sortOrder
  1004. };
  1005. }
  1006. /// <summary>
  1007. /// Used to split names of comma or pipe delimeted genres and people
  1008. /// </summary>
  1009. /// <param name="value">The value.</param>
  1010. /// <returns>IEnumerable{System.String}.</returns>
  1011. private IEnumerable<string> SplitNames(string value)
  1012. {
  1013. value = value ?? string.Empty;
  1014. // Only split by comma if there is no pipe in the string
  1015. // We have to be careful to not split names like Matthew, Jr.
  1016. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1017. value = value.Trim().Trim(separator);
  1018. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1019. }
  1020. /// <summary>
  1021. /// Provides an additional overload for string.split
  1022. /// </summary>
  1023. /// <param name="val">The val.</param>
  1024. /// <param name="separators">The separators.</param>
  1025. /// <param name="options">The options.</param>
  1026. /// <returns>System.String[][].</returns>
  1027. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1028. {
  1029. return val.Split(separators, options);
  1030. }
  1031. }
  1032. }