BaseNfoParser.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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)
  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)
  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. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  507. {
  508. if (string.IsNullOrWhiteSpace(p.Name))
  509. {
  510. continue;
  511. }
  512. itemResult.AddPerson(p);
  513. }
  514. break;
  515. }
  516. case "credits":
  517. {
  518. var val = reader.ReadElementContentAsString();
  519. if (!string.IsNullOrWhiteSpace(val))
  520. {
  521. var parts = val.Split('/').Select(i => i.Trim())
  522. .Where(i => !string.IsNullOrEmpty(i));
  523. foreach (var p in parts.Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  524. {
  525. if (string.IsNullOrWhiteSpace(p.Name))
  526. {
  527. continue;
  528. }
  529. itemResult.AddPerson(p);
  530. }
  531. }
  532. break;
  533. }
  534. case "writer":
  535. {
  536. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  537. {
  538. if (string.IsNullOrWhiteSpace(p.Name))
  539. {
  540. continue;
  541. }
  542. itemResult.AddPerson(p);
  543. }
  544. break;
  545. }
  546. case "actor":
  547. {
  548. using (var subtree = reader.ReadSubtree())
  549. {
  550. var person = GetPersonFromXmlNode(subtree);
  551. if (!string.IsNullOrWhiteSpace(person.Name))
  552. {
  553. itemResult.AddPerson(person);
  554. }
  555. }
  556. break;
  557. }
  558. case "trailer":
  559. {
  560. var val = reader.ReadElementContentAsString();
  561. var hasTrailer = item as IHasTrailers;
  562. if (hasTrailer != null)
  563. {
  564. if (!string.IsNullOrWhiteSpace(val))
  565. {
  566. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "https://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  567. hasTrailer.AddTrailerUrl(val, false);
  568. }
  569. }
  570. break;
  571. }
  572. case "displayorder":
  573. {
  574. var val = reader.ReadElementContentAsString();
  575. var hasDisplayOrder = item as IHasDisplayOrder;
  576. if (hasDisplayOrder != null)
  577. {
  578. if (!string.IsNullOrWhiteSpace(val))
  579. {
  580. hasDisplayOrder.DisplayOrder = val;
  581. }
  582. }
  583. break;
  584. }
  585. case "year":
  586. {
  587. var val = reader.ReadElementContentAsString();
  588. if (!string.IsNullOrWhiteSpace(val))
  589. {
  590. int productionYear;
  591. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  592. {
  593. item.ProductionYear = productionYear;
  594. }
  595. }
  596. break;
  597. }
  598. case "rating":
  599. {
  600. var rating = reader.ReadElementContentAsString();
  601. if (!string.IsNullOrWhiteSpace(rating))
  602. {
  603. float val;
  604. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  605. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  606. {
  607. item.CommunityRating = val;
  608. }
  609. }
  610. break;
  611. }
  612. case "aired":
  613. case "formed":
  614. case "premiered":
  615. case "releasedate":
  616. {
  617. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  618. var val = reader.ReadElementContentAsString();
  619. if (!string.IsNullOrWhiteSpace(val))
  620. {
  621. DateTime date;
  622. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  623. {
  624. item.PremiereDate = date.ToUniversalTime();
  625. item.ProductionYear = date.Year;
  626. }
  627. }
  628. break;
  629. }
  630. case "enddate":
  631. {
  632. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  633. var val = reader.ReadElementContentAsString();
  634. if (!string.IsNullOrWhiteSpace(val))
  635. {
  636. DateTime date;
  637. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  638. {
  639. item.EndDate = date.ToUniversalTime();
  640. }
  641. }
  642. break;
  643. }
  644. case "votes":
  645. {
  646. var val = reader.ReadElementContentAsString();
  647. if (!string.IsNullOrWhiteSpace(val))
  648. {
  649. int num;
  650. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  651. {
  652. item.VoteCount = num;
  653. }
  654. }
  655. break;
  656. }
  657. case "genre":
  658. {
  659. var val = reader.ReadElementContentAsString();
  660. if (!string.IsNullOrWhiteSpace(val))
  661. {
  662. var parts = val.Split('/')
  663. .Select(i => i.Trim())
  664. .Where(i => !string.IsNullOrWhiteSpace(i));
  665. foreach (var p in parts)
  666. {
  667. item.AddGenre(p);
  668. }
  669. }
  670. break;
  671. }
  672. case "style":
  673. case "tag":
  674. {
  675. var val = reader.ReadElementContentAsString();
  676. if (!string.IsNullOrWhiteSpace(val))
  677. {
  678. item.AddTag(val);
  679. }
  680. break;
  681. }
  682. case "plotkeyword":
  683. {
  684. var val = reader.ReadElementContentAsString();
  685. if (!string.IsNullOrWhiteSpace(val))
  686. {
  687. item.AddKeyword(val);
  688. }
  689. break;
  690. }
  691. case "fileinfo":
  692. {
  693. using (var subtree = reader.ReadSubtree())
  694. {
  695. FetchFromFileInfoNode(subtree, item);
  696. }
  697. break;
  698. }
  699. case "watched":
  700. {
  701. var val = reader.ReadElementContentAsString();
  702. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  703. {
  704. bool parsedValue;
  705. if (bool.TryParse(val, out parsedValue))
  706. {
  707. var userData = GetOrAdd(itemResult, userDataUserId);
  708. userData.Played = parsedValue;
  709. }
  710. }
  711. break;
  712. }
  713. case "playcount":
  714. {
  715. var val = reader.ReadElementContentAsString();
  716. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  717. {
  718. int parsedValue;
  719. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  720. {
  721. var userData = GetOrAdd(itemResult, userDataUserId);
  722. userData.PlayCount = parsedValue;
  723. if (parsedValue > 0)
  724. {
  725. userData.Played = true;
  726. }
  727. }
  728. }
  729. break;
  730. }
  731. case "lastplayed":
  732. {
  733. var val = reader.ReadElementContentAsString();
  734. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  735. {
  736. DateTime parsedValue;
  737. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  738. {
  739. var userData = GetOrAdd(itemResult, userDataUserId);
  740. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  741. }
  742. }
  743. break;
  744. }
  745. case "resume":
  746. {
  747. using (var subtree = reader.ReadSubtree())
  748. {
  749. if (!string.IsNullOrWhiteSpace(userDataUserId))
  750. {
  751. var userData = GetOrAdd(itemResult, userDataUserId);
  752. FetchFromResumeNode(subtree, item, userData);
  753. }
  754. }
  755. break;
  756. }
  757. case "isuserfavorite":
  758. {
  759. var val = reader.ReadElementContentAsString();
  760. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  761. {
  762. bool parsedValue;
  763. if (bool.TryParse(val, out parsedValue))
  764. {
  765. var userData = GetOrAdd(itemResult, userDataUserId);
  766. userData.IsFavorite = parsedValue;
  767. }
  768. }
  769. break;
  770. }
  771. case "userrating":
  772. {
  773. var val = reader.ReadElementContentAsString();
  774. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  775. {
  776. double parsedValue;
  777. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  778. {
  779. var userData = GetOrAdd(itemResult, userDataUserId);
  780. userData.Rating = parsedValue;
  781. }
  782. }
  783. break;
  784. }
  785. default:
  786. reader.Skip();
  787. break;
  788. }
  789. }
  790. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  791. {
  792. return result.GetOrAddUserData(userId);
  793. }
  794. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  795. {
  796. reader.MoveToContent();
  797. reader.Read();
  798. // Loop through each element
  799. while (!reader.EOF)
  800. {
  801. if (reader.NodeType == XmlNodeType.Element)
  802. {
  803. switch (reader.Name)
  804. {
  805. case "position":
  806. {
  807. var val = reader.ReadElementContentAsString();
  808. if (!string.IsNullOrWhiteSpace(val))
  809. {
  810. double parsedValue;
  811. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  812. {
  813. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  814. }
  815. }
  816. break;
  817. }
  818. default:
  819. reader.Skip();
  820. break;
  821. }
  822. }
  823. else
  824. {
  825. reader.Read();
  826. }
  827. }
  828. }
  829. private void FetchFromFileInfoNode(XmlReader reader, T item)
  830. {
  831. reader.MoveToContent();
  832. reader.Read();
  833. // Loop through each element
  834. while (!reader.EOF)
  835. {
  836. if (reader.NodeType == XmlNodeType.Element)
  837. {
  838. switch (reader.Name)
  839. {
  840. case "streamdetails":
  841. {
  842. using (var subtree = reader.ReadSubtree())
  843. {
  844. FetchFromStreamDetailsNode(subtree, item);
  845. }
  846. break;
  847. }
  848. default:
  849. reader.Skip();
  850. break;
  851. }
  852. }
  853. else
  854. {
  855. reader.Read();
  856. }
  857. }
  858. }
  859. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  860. {
  861. reader.MoveToContent();
  862. reader.Read();
  863. // Loop through each element
  864. while (!reader.EOF)
  865. {
  866. if (reader.NodeType == XmlNodeType.Element)
  867. {
  868. switch (reader.Name)
  869. {
  870. case "video":
  871. {
  872. using (var subtree = reader.ReadSubtree())
  873. {
  874. FetchFromVideoNode(subtree, item);
  875. }
  876. break;
  877. }
  878. default:
  879. reader.Skip();
  880. break;
  881. }
  882. }
  883. else
  884. {
  885. reader.Read();
  886. }
  887. }
  888. }
  889. private void FetchFromVideoNode(XmlReader reader, T item)
  890. {
  891. reader.MoveToContent();
  892. reader.Read();
  893. // Loop through each element
  894. while (!reader.EOF)
  895. {
  896. if (reader.NodeType == XmlNodeType.Element)
  897. {
  898. switch (reader.Name)
  899. {
  900. case "format3d":
  901. {
  902. var val = reader.ReadElementContentAsString();
  903. var video = item as Video;
  904. if (video != null)
  905. {
  906. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  907. {
  908. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  909. }
  910. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  911. {
  912. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  913. }
  914. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  915. {
  916. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  917. }
  918. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  919. {
  920. video.Video3DFormat = Video3DFormat.FullSideBySide;
  921. }
  922. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  923. {
  924. video.Video3DFormat = Video3DFormat.MVC;
  925. }
  926. }
  927. break;
  928. }
  929. default:
  930. reader.Skip();
  931. break;
  932. }
  933. }
  934. else
  935. {
  936. reader.Read();
  937. }
  938. }
  939. }
  940. /// <summary>
  941. /// Gets the persons from XML node.
  942. /// </summary>
  943. /// <param name="reader">The reader.</param>
  944. /// <returns>IEnumerable{PersonInfo}.</returns>
  945. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  946. {
  947. var name = string.Empty;
  948. var type = PersonType.Actor; // If type is not specified assume actor
  949. var role = string.Empty;
  950. int? sortOrder = null;
  951. reader.MoveToContent();
  952. reader.Read();
  953. // Loop through each element
  954. while (!reader.EOF)
  955. {
  956. if (reader.NodeType == XmlNodeType.Element)
  957. {
  958. switch (reader.Name)
  959. {
  960. case "name":
  961. name = reader.ReadElementContentAsString() ?? string.Empty;
  962. break;
  963. case "type":
  964. {
  965. var val = reader.ReadElementContentAsString();
  966. if (!string.IsNullOrWhiteSpace(val))
  967. {
  968. type = val;
  969. }
  970. break;
  971. }
  972. case "role":
  973. {
  974. var val = reader.ReadElementContentAsString();
  975. if (!string.IsNullOrWhiteSpace(val))
  976. {
  977. role = val;
  978. }
  979. break;
  980. }
  981. case "sortorder":
  982. {
  983. var val = reader.ReadElementContentAsString();
  984. if (!string.IsNullOrWhiteSpace(val))
  985. {
  986. int intVal;
  987. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  988. {
  989. sortOrder = intVal;
  990. }
  991. }
  992. break;
  993. }
  994. default:
  995. reader.Skip();
  996. break;
  997. }
  998. }
  999. else
  1000. {
  1001. reader.Read();
  1002. }
  1003. }
  1004. return new PersonInfo
  1005. {
  1006. Name = name.Trim(),
  1007. Role = role,
  1008. Type = type,
  1009. SortOrder = sortOrder
  1010. };
  1011. }
  1012. /// <summary>
  1013. /// Used to split names of comma or pipe delimeted genres and people
  1014. /// </summary>
  1015. /// <param name="value">The value.</param>
  1016. /// <returns>IEnumerable{System.String}.</returns>
  1017. private IEnumerable<string> SplitNames(string value)
  1018. {
  1019. value = value ?? string.Empty;
  1020. // Only split by comma if there is no pipe in the string
  1021. // We have to be careful to not split names like Matthew, Jr.
  1022. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1023. value = value.Trim().Trim(separator);
  1024. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1025. }
  1026. /// <summary>
  1027. /// Provides an additional overload for string.split
  1028. /// </summary>
  1029. /// <param name="val">The val.</param>
  1030. /// <param name="separators">The separators.</param>
  1031. /// <param name="options">The options.</param>
  1032. /// <returns>System.String[][].</returns>
  1033. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1034. {
  1035. return val.Split(separators, options);
  1036. }
  1037. }
  1038. }