BaseNfoParser.cs 43 KB

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