BaseNfoParser.cs 45 KB

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