BaseNfoParser.cs 45 KB

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