BaseNfoParser.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. var providerId = reader.Name;
  810. if (_validProviderIds.ContainsKey(providerId))
  811. {
  812. var id = reader.ReadElementContentAsString();
  813. if (!string.IsNullOrWhiteSpace(id))
  814. {
  815. item.SetProviderId(_validProviderIds[providerId], id);
  816. }
  817. }
  818. else
  819. {
  820. reader.Skip();
  821. }
  822. break;
  823. }
  824. }
  825. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  826. {
  827. return result.GetOrAddUserData(userId);
  828. }
  829. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  830. {
  831. reader.MoveToContent();
  832. reader.Read();
  833. // Loop through each element
  834. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  835. {
  836. if (reader.NodeType == XmlNodeType.Element)
  837. {
  838. switch (reader.Name)
  839. {
  840. case "position":
  841. {
  842. var val = reader.ReadElementContentAsString();
  843. if (!string.IsNullOrWhiteSpace(val))
  844. {
  845. double parsedValue;
  846. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  847. {
  848. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  849. }
  850. }
  851. break;
  852. }
  853. default:
  854. reader.Skip();
  855. break;
  856. }
  857. }
  858. else
  859. {
  860. reader.Read();
  861. }
  862. }
  863. }
  864. private void FetchFromFileInfoNode(XmlReader reader, T item)
  865. {
  866. reader.MoveToContent();
  867. reader.Read();
  868. // Loop through each element
  869. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  870. {
  871. if (reader.NodeType == XmlNodeType.Element)
  872. {
  873. switch (reader.Name)
  874. {
  875. case "streamdetails":
  876. {
  877. if (reader.IsEmptyElement)
  878. {
  879. reader.Read();
  880. continue;
  881. }
  882. using (var subtree = reader.ReadSubtree())
  883. {
  884. FetchFromStreamDetailsNode(subtree, item);
  885. }
  886. break;
  887. }
  888. default:
  889. reader.Skip();
  890. break;
  891. }
  892. }
  893. else
  894. {
  895. reader.Read();
  896. }
  897. }
  898. }
  899. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  900. {
  901. reader.MoveToContent();
  902. reader.Read();
  903. // Loop through each element
  904. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  905. {
  906. if (reader.NodeType == XmlNodeType.Element)
  907. {
  908. switch (reader.Name)
  909. {
  910. case "video":
  911. {
  912. if (reader.IsEmptyElement)
  913. {
  914. reader.Read();
  915. continue;
  916. }
  917. using (var subtree = reader.ReadSubtree())
  918. {
  919. FetchFromVideoNode(subtree, item);
  920. }
  921. break;
  922. }
  923. default:
  924. reader.Skip();
  925. break;
  926. }
  927. }
  928. else
  929. {
  930. reader.Read();
  931. }
  932. }
  933. }
  934. private void FetchFromVideoNode(XmlReader reader, T item)
  935. {
  936. reader.MoveToContent();
  937. reader.Read();
  938. // Loop through each element
  939. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  940. {
  941. if (reader.NodeType == XmlNodeType.Element)
  942. {
  943. switch (reader.Name)
  944. {
  945. case "format3d":
  946. {
  947. var val = reader.ReadElementContentAsString();
  948. var video = item as Video;
  949. if (video != null)
  950. {
  951. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  952. {
  953. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  954. }
  955. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  956. {
  957. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  958. }
  959. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  960. {
  961. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  962. }
  963. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  964. {
  965. video.Video3DFormat = Video3DFormat.FullSideBySide;
  966. }
  967. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  968. {
  969. video.Video3DFormat = Video3DFormat.MVC;
  970. }
  971. }
  972. break;
  973. }
  974. default:
  975. reader.Skip();
  976. break;
  977. }
  978. }
  979. else
  980. {
  981. reader.Read();
  982. }
  983. }
  984. }
  985. /// <summary>
  986. /// Gets the persons from XML node.
  987. /// </summary>
  988. /// <param name="reader">The reader.</param>
  989. /// <returns>IEnumerable{PersonInfo}.</returns>
  990. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  991. {
  992. var name = string.Empty;
  993. var type = PersonType.Actor; // If type is not specified assume actor
  994. var role = string.Empty;
  995. int? sortOrder = null;
  996. reader.MoveToContent();
  997. reader.Read();
  998. // Loop through each element
  999. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  1000. {
  1001. if (reader.NodeType == XmlNodeType.Element)
  1002. {
  1003. switch (reader.Name)
  1004. {
  1005. case "name":
  1006. name = reader.ReadElementContentAsString() ?? string.Empty;
  1007. break;
  1008. case "type":
  1009. {
  1010. var val = reader.ReadElementContentAsString();
  1011. if (!string.IsNullOrWhiteSpace(val))
  1012. {
  1013. type = val;
  1014. }
  1015. break;
  1016. }
  1017. case "role":
  1018. {
  1019. var val = reader.ReadElementContentAsString();
  1020. if (!string.IsNullOrWhiteSpace(val))
  1021. {
  1022. role = val;
  1023. }
  1024. break;
  1025. }
  1026. case "sortorder":
  1027. {
  1028. var val = reader.ReadElementContentAsString();
  1029. if (!string.IsNullOrWhiteSpace(val))
  1030. {
  1031. int intVal;
  1032. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  1033. {
  1034. sortOrder = intVal;
  1035. }
  1036. }
  1037. break;
  1038. }
  1039. default:
  1040. reader.Skip();
  1041. break;
  1042. }
  1043. }
  1044. else
  1045. {
  1046. reader.Read();
  1047. }
  1048. }
  1049. return new PersonInfo
  1050. {
  1051. Name = name.Trim(),
  1052. Role = role,
  1053. Type = type,
  1054. SortOrder = sortOrder
  1055. };
  1056. }
  1057. /// <summary>
  1058. /// Used to split names of comma or pipe delimeted genres and people
  1059. /// </summary>
  1060. /// <param name="value">The value.</param>
  1061. /// <returns>IEnumerable{System.String}.</returns>
  1062. private IEnumerable<string> SplitNames(string value)
  1063. {
  1064. value = value ?? string.Empty;
  1065. // Only split by comma if there is no pipe in the string
  1066. // We have to be careful to not split names like Matthew, Jr.
  1067. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1068. value = value.Trim().Trim(separator);
  1069. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1070. }
  1071. /// <summary>
  1072. /// Provides an additional overload for string.split
  1073. /// </summary>
  1074. /// <param name="val">The val.</param>
  1075. /// <param name="separators">The separators.</param>
  1076. /// <param name="options">The options.</param>
  1077. /// <returns>System.String[][].</returns>
  1078. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1079. {
  1080. return val.Split(separators, options);
  1081. }
  1082. }
  1083. }