BaseNfoParser.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298
  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. namespace MediaBrowser.XbmcMetadata.Parsers
  19. {
  20. public class BaseNfoParser<T>
  21. where T : BaseItem
  22. {
  23. /// <summary>
  24. /// The logger
  25. /// </summary>
  26. protected ILogger Logger { get; private set; }
  27. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  28. private readonly IConfigurationManager _config;
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="BaseNfoParser{T}" /> class.
  31. /// </summary>
  32. /// <param name="logger">The logger.</param>
  33. /// <param name="config">The configuration.</param>
  34. public BaseNfoParser(ILogger logger, IConfigurationManager config)
  35. {
  36. Logger = logger;
  37. _config = config;
  38. }
  39. /// <summary>
  40. /// Fetches metadata for an item from one xml file
  41. /// </summary>
  42. /// <param name="item">The item.</param>
  43. /// <param name="metadataFile">The metadata file.</param>
  44. /// <param name="cancellationToken">The cancellation token.</param>
  45. /// <exception cref="System.ArgumentNullException">
  46. /// </exception>
  47. public void Fetch(MetadataResult<T> item, string metadataFile, CancellationToken cancellationToken)
  48. {
  49. if (item == null)
  50. {
  51. throw new ArgumentNullException();
  52. }
  53. if (string.IsNullOrEmpty(metadataFile))
  54. {
  55. throw new ArgumentNullException();
  56. }
  57. var settings = new XmlReaderSettings
  58. {
  59. CheckCharacters = false,
  60. IgnoreProcessingInstructions = true,
  61. IgnoreComments = true,
  62. ValidationType = ValidationType.None
  63. };
  64. Fetch(item, metadataFile, settings, cancellationToken);
  65. }
  66. protected virtual bool SupportsUrlAfterClosingXmlTag
  67. {
  68. get { return false; }
  69. }
  70. /// <summary>
  71. /// Fetches the specified item.
  72. /// </summary>
  73. /// <param name="item">The item.</param>
  74. /// <param name="metadataFile">The metadata file.</param>
  75. /// <param name="settings">The settings.</param>
  76. /// <param name="cancellationToken">The cancellation token.</param>
  77. private void Fetch(MetadataResult<T> item, string metadataFile, XmlReaderSettings settings, CancellationToken cancellationToken)
  78. {
  79. item.ResetPeople();
  80. if (!SupportsUrlAfterClosingXmlTag)
  81. {
  82. using (var streamReader = BaseNfoSaver.GetStreamReader(metadataFile))
  83. {
  84. // Use XmlReader for best performance
  85. using (var reader = XmlReader.Create(streamReader, settings))
  86. {
  87. reader.MoveToContent();
  88. // Loop through each element
  89. while (reader.Read())
  90. {
  91. cancellationToken.ThrowIfCancellationRequested();
  92. if (reader.NodeType == XmlNodeType.Element)
  93. {
  94. FetchDataFromXmlNode(reader, item);
  95. }
  96. }
  97. }
  98. }
  99. return;
  100. }
  101. using (var streamReader = BaseNfoSaver.GetStreamReader(metadataFile))
  102. {
  103. // Need to handle a url after the xml data
  104. // http://kodi.wiki/view/NFO_files/movies
  105. var xml = streamReader.ReadToEnd();
  106. // Find last closing Tag
  107. // Need to do this in two steps to account for random > characters after the closing xml
  108. var index = xml.LastIndexOf(@"</", StringComparison.Ordinal);
  109. // If closing tag exists, move to end of Tag
  110. if (index != -1)
  111. {
  112. index = xml.IndexOf('>', index);
  113. }
  114. if (index != -1)
  115. {
  116. var endingXml = xml.Substring(index);
  117. ParseProviderLinks(item.Item, endingXml);
  118. // If the file is just an imdb url, don't go any further
  119. if (index == 0)
  120. {
  121. return;
  122. }
  123. xml = xml.Substring(0, index + 1);
  124. }
  125. else
  126. {
  127. // If the file is just an Imdb url, handle that
  128. ParseProviderLinks(item.Item, xml);
  129. return;
  130. }
  131. using (var ms = new MemoryStream())
  132. {
  133. var bytes = Encoding.UTF8.GetBytes(xml);
  134. ms.Write(bytes, 0, bytes.Length);
  135. ms.Position = 0;
  136. // These are not going to be valid xml so no sense in causing the provider to fail and spamming the log with exceptions
  137. try
  138. {
  139. // Use XmlReader for best performance
  140. using (var reader = XmlReader.Create(ms, settings))
  141. {
  142. reader.MoveToContent();
  143. // Loop through each element
  144. while (reader.Read())
  145. {
  146. cancellationToken.ThrowIfCancellationRequested();
  147. if (reader.NodeType == XmlNodeType.Element)
  148. {
  149. FetchDataFromXmlNode(reader, item);
  150. }
  151. }
  152. }
  153. }
  154. catch (XmlException)
  155. {
  156. }
  157. }
  158. }
  159. }
  160. private void ParseProviderLinks(T item, string xml)
  161. {
  162. //Look for a match for the Regex pattern "tt" followed by 7 digits
  163. Match m = Regex.Match(xml, @"tt([0-9]{7})", RegexOptions.IgnoreCase);
  164. if (m.Success)
  165. {
  166. item.SetProviderId(MetadataProviders.Imdb, m.Value);
  167. }
  168. // TODO: Support Tmdb
  169. // http://www.themoviedb.org/movie/36557
  170. }
  171. protected virtual void FetchDataFromXmlNode(XmlReader reader, MetadataResult<T> itemResult)
  172. {
  173. var item = itemResult.Item;
  174. var userDataUserId = _config.GetNfoConfiguration().UserId;
  175. switch (reader.Name)
  176. {
  177. // DateCreated
  178. case "dateadded":
  179. {
  180. var val = reader.ReadElementContentAsString();
  181. if (!string.IsNullOrWhiteSpace(val))
  182. {
  183. DateTime added;
  184. if (DateTime.TryParseExact(val, BaseNfoSaver.DateAddedFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  185. {
  186. item.EndDate = added.ToUniversalTime();
  187. }
  188. else if (DateTime.TryParse(val, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out added))
  189. {
  190. item.DateCreated = added.ToUniversalTime();
  191. }
  192. else
  193. {
  194. Logger.Warn("Invalid Added value found: " + val);
  195. }
  196. }
  197. break;
  198. }
  199. case "originaltitle":
  200. {
  201. var val = reader.ReadElementContentAsString();
  202. var hasOriginalTitle = item as IHasOriginalTitle;
  203. if (hasOriginalTitle != null)
  204. {
  205. if (!string.IsNullOrEmpty(hasOriginalTitle.OriginalTitle))
  206. {
  207. hasOriginalTitle.OriginalTitle = val;
  208. }
  209. }
  210. break;
  211. }
  212. case "type":
  213. item.DisplayMediaType = reader.ReadElementContentAsString();
  214. break;
  215. case "title":
  216. case "localtitle":
  217. item.Name = reader.ReadElementContentAsString();
  218. break;
  219. case "criticrating":
  220. {
  221. var text = reader.ReadElementContentAsString();
  222. var hasCriticRating = item as IHasCriticRating;
  223. if (hasCriticRating != null && !string.IsNullOrEmpty(text))
  224. {
  225. float value;
  226. if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
  227. {
  228. hasCriticRating.CriticRating = value;
  229. }
  230. }
  231. break;
  232. }
  233. case "budget":
  234. {
  235. var text = reader.ReadElementContentAsString();
  236. var hasBudget = item as IHasBudget;
  237. if (hasBudget != null)
  238. {
  239. double value;
  240. if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
  241. {
  242. hasBudget.Budget = value;
  243. }
  244. }
  245. break;
  246. }
  247. case "revenue":
  248. {
  249. var text = reader.ReadElementContentAsString();
  250. var hasBudget = item as IHasBudget;
  251. if (hasBudget != null)
  252. {
  253. double value;
  254. if (double.TryParse(text, NumberStyles.Any, _usCulture, out value))
  255. {
  256. hasBudget.Revenue = value;
  257. }
  258. }
  259. break;
  260. }
  261. case "metascore":
  262. {
  263. var text = reader.ReadElementContentAsString();
  264. var hasMetascore = item as IHasMetascore;
  265. if (hasMetascore != null)
  266. {
  267. float value;
  268. if (float.TryParse(text, NumberStyles.Any, _usCulture, out value))
  269. {
  270. hasMetascore.Metascore = value;
  271. }
  272. }
  273. break;
  274. }
  275. case "awardsummary":
  276. {
  277. var text = reader.ReadElementContentAsString();
  278. var hasAwards = item as IHasAwards;
  279. if (hasAwards != null)
  280. {
  281. if (!string.IsNullOrWhiteSpace(text))
  282. {
  283. hasAwards.AwardSummary = text;
  284. }
  285. }
  286. break;
  287. }
  288. case "sorttitle":
  289. {
  290. var val = reader.ReadElementContentAsString();
  291. if (!string.IsNullOrWhiteSpace(val))
  292. {
  293. item.ForcedSortName = val;
  294. }
  295. break;
  296. }
  297. case "outline":
  298. {
  299. var val = reader.ReadElementContentAsString();
  300. if (!string.IsNullOrWhiteSpace(val))
  301. {
  302. var hasShortOverview = item as IHasShortOverview;
  303. if (hasShortOverview != null)
  304. {
  305. hasShortOverview.ShortOverview = val;
  306. }
  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. var hasCriticRating = item as IHasCriticRating;
  327. if (hasCriticRating != null)
  328. {
  329. hasCriticRating.CriticRatingSummary = val;
  330. }
  331. }
  332. break;
  333. }
  334. case "language":
  335. {
  336. var val = reader.ReadElementContentAsString();
  337. item.PreferredMetadataLanguage = val;
  338. break;
  339. }
  340. case "countrycode":
  341. {
  342. var val = reader.ReadElementContentAsString();
  343. item.PreferredMetadataCountryCode = val;
  344. break;
  345. }
  346. case "website":
  347. {
  348. var val = reader.ReadElementContentAsString();
  349. if (!string.IsNullOrWhiteSpace(val))
  350. {
  351. item.HomePageUrl = val;
  352. }
  353. break;
  354. }
  355. case "lockedfields":
  356. {
  357. var fields = new List<MetadataFields>();
  358. var val = reader.ReadElementContentAsString();
  359. if (!string.IsNullOrWhiteSpace(val))
  360. {
  361. var list = val.Split('|').Select(i =>
  362. {
  363. MetadataFields field;
  364. if (Enum.TryParse<MetadataFields>(i, true, out field))
  365. {
  366. return (MetadataFields?)field;
  367. }
  368. return null;
  369. }).Where(i => i.HasValue).Select(i => i.Value);
  370. fields.AddRange(list);
  371. }
  372. item.LockedFields = fields;
  373. break;
  374. }
  375. case "tagline":
  376. {
  377. var val = reader.ReadElementContentAsString();
  378. var hasTagline = item as IHasTaglines;
  379. if (hasTagline != null)
  380. {
  381. if (!string.IsNullOrWhiteSpace(val))
  382. {
  383. hasTagline.AddTagline(val);
  384. }
  385. }
  386. break;
  387. }
  388. case "country":
  389. {
  390. var val = reader.ReadElementContentAsString();
  391. var hasProductionLocations = item as IHasProductionLocations;
  392. if (hasProductionLocations != null)
  393. {
  394. if (!string.IsNullOrWhiteSpace(val))
  395. {
  396. var parts = val.Split('/')
  397. .Select(i => i.Trim())
  398. .Where(i => !string.IsNullOrWhiteSpace(i));
  399. foreach (var p in parts)
  400. {
  401. hasProductionLocations.AddProductionLocation(p);
  402. }
  403. }
  404. }
  405. break;
  406. }
  407. case "mpaa":
  408. {
  409. var rating = reader.ReadElementContentAsString();
  410. if (!string.IsNullOrWhiteSpace(rating))
  411. {
  412. item.OfficialRating = rating;
  413. }
  414. break;
  415. }
  416. case "mpaadescription":
  417. {
  418. var rating = reader.ReadElementContentAsString();
  419. if (!string.IsNullOrWhiteSpace(rating))
  420. {
  421. item.OfficialRatingDescription = rating;
  422. }
  423. break;
  424. }
  425. case "customrating":
  426. {
  427. var val = reader.ReadElementContentAsString();
  428. if (!string.IsNullOrWhiteSpace(val))
  429. {
  430. item.CustomRating = val;
  431. }
  432. break;
  433. }
  434. case "runtime":
  435. {
  436. var text = reader.ReadElementContentAsString();
  437. if (!string.IsNullOrWhiteSpace(text))
  438. {
  439. int runtime;
  440. if (int.TryParse(text.Split(' ')[0], NumberStyles.Integer, _usCulture, out runtime))
  441. {
  442. item.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
  443. }
  444. }
  445. break;
  446. }
  447. case "aspectratio":
  448. {
  449. var val = reader.ReadElementContentAsString();
  450. var hasAspectRatio = item as IHasAspectRatio;
  451. if (!string.IsNullOrWhiteSpace(val) && hasAspectRatio != null)
  452. {
  453. hasAspectRatio.AspectRatio = val;
  454. }
  455. break;
  456. }
  457. case "lockdata":
  458. {
  459. var val = reader.ReadElementContentAsString();
  460. if (!string.IsNullOrWhiteSpace(val))
  461. {
  462. item.IsLocked = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  463. }
  464. break;
  465. }
  466. case "studio":
  467. {
  468. var val = reader.ReadElementContentAsString();
  469. if (!string.IsNullOrWhiteSpace(val))
  470. {
  471. var parts = val.Split('/')
  472. .Select(i => i.Trim())
  473. .Where(i => !string.IsNullOrWhiteSpace(i));
  474. foreach (var p in parts)
  475. {
  476. item.AddStudio(p);
  477. }
  478. }
  479. break;
  480. }
  481. case "director":
  482. {
  483. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Director }))
  484. {
  485. if (string.IsNullOrWhiteSpace(p.Name))
  486. {
  487. continue;
  488. }
  489. itemResult.AddPerson(p);
  490. }
  491. break;
  492. }
  493. case "credits":
  494. {
  495. var val = reader.ReadElementContentAsString();
  496. if (!string.IsNullOrWhiteSpace(val))
  497. {
  498. var parts = val.Split('/').Select(i => i.Trim())
  499. .Where(i => !string.IsNullOrEmpty(i));
  500. foreach (var p in parts.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. }
  509. break;
  510. }
  511. case "writer":
  512. {
  513. foreach (var p in SplitNames(reader.ReadElementContentAsString()).Select(v => new PersonInfo { Name = v.Trim(), Type = PersonType.Writer }))
  514. {
  515. if (string.IsNullOrWhiteSpace(p.Name))
  516. {
  517. continue;
  518. }
  519. itemResult.AddPerson(p);
  520. }
  521. break;
  522. }
  523. case "actor":
  524. {
  525. using (var subtree = reader.ReadSubtree())
  526. {
  527. var person = GetPersonFromXmlNode(subtree);
  528. if (!string.IsNullOrWhiteSpace(person.Name))
  529. {
  530. itemResult.AddPerson(person);
  531. }
  532. }
  533. break;
  534. }
  535. case "trailer":
  536. {
  537. var val = reader.ReadElementContentAsString();
  538. var hasTrailer = item as IHasTrailers;
  539. if (hasTrailer != null)
  540. {
  541. if (!string.IsNullOrWhiteSpace(val))
  542. {
  543. val = val.Replace("plugin://plugin.video.youtube/?action=play_video&videoid=", "http://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase);
  544. hasTrailer.AddTrailerUrl(val, false);
  545. }
  546. }
  547. break;
  548. }
  549. case "displayorder":
  550. {
  551. var val = reader.ReadElementContentAsString();
  552. var hasDisplayOrder = item as IHasDisplayOrder;
  553. if (hasDisplayOrder != null)
  554. {
  555. if (!string.IsNullOrWhiteSpace(val))
  556. {
  557. hasDisplayOrder.DisplayOrder = val;
  558. }
  559. }
  560. break;
  561. }
  562. case "year":
  563. {
  564. var val = reader.ReadElementContentAsString();
  565. if (!string.IsNullOrWhiteSpace(val))
  566. {
  567. int productionYear;
  568. if (int.TryParse(val, out productionYear) && productionYear > 1850)
  569. {
  570. item.ProductionYear = productionYear;
  571. }
  572. }
  573. break;
  574. }
  575. case "rating":
  576. {
  577. var rating = reader.ReadElementContentAsString();
  578. if (!string.IsNullOrWhiteSpace(rating))
  579. {
  580. float val;
  581. // All external meta is saving this as '.' for decimal I believe...but just to be sure
  582. if (float.TryParse(rating.Replace(',', '.'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out val))
  583. {
  584. item.CommunityRating = val;
  585. }
  586. }
  587. break;
  588. }
  589. case "aired":
  590. case "formed":
  591. case "premiered":
  592. case "releasedate":
  593. {
  594. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  595. var val = reader.ReadElementContentAsString();
  596. if (!string.IsNullOrWhiteSpace(val))
  597. {
  598. DateTime date;
  599. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  600. {
  601. item.PremiereDate = date.ToUniversalTime();
  602. item.ProductionYear = date.Year;
  603. }
  604. }
  605. break;
  606. }
  607. case "enddate":
  608. {
  609. var formatString = _config.GetNfoConfiguration().ReleaseDateFormat;
  610. var val = reader.ReadElementContentAsString();
  611. if (!string.IsNullOrWhiteSpace(val))
  612. {
  613. DateTime date;
  614. if (DateTime.TryParseExact(val, formatString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date) && date.Year > 1850)
  615. {
  616. item.EndDate = date.ToUniversalTime();
  617. }
  618. }
  619. break;
  620. }
  621. case "tvdbid":
  622. var tvdbId = reader.ReadElementContentAsString();
  623. if (!string.IsNullOrWhiteSpace(tvdbId))
  624. {
  625. item.SetProviderId(MetadataProviders.Tvdb, tvdbId);
  626. }
  627. break;
  628. case "votes":
  629. {
  630. var val = reader.ReadElementContentAsString();
  631. if (!string.IsNullOrWhiteSpace(val))
  632. {
  633. int num;
  634. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out num))
  635. {
  636. item.VoteCount = num;
  637. }
  638. }
  639. break;
  640. }
  641. case "musicbrainzalbumid":
  642. {
  643. var mbz = reader.ReadElementContentAsString();
  644. if (!string.IsNullOrWhiteSpace(mbz))
  645. {
  646. item.SetProviderId(MetadataProviders.MusicBrainzAlbum, mbz);
  647. }
  648. break;
  649. }
  650. case "musicbrainzalbumartistid":
  651. {
  652. var mbz = reader.ReadElementContentAsString();
  653. if (!string.IsNullOrWhiteSpace(mbz))
  654. {
  655. item.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mbz);
  656. }
  657. break;
  658. }
  659. case "musicbrainzartistid":
  660. {
  661. var mbz = reader.ReadElementContentAsString();
  662. if (!string.IsNullOrWhiteSpace(mbz))
  663. {
  664. item.SetProviderId(MetadataProviders.MusicBrainzArtist, mbz);
  665. }
  666. break;
  667. }
  668. case "musicbrainzreleasegroupid":
  669. {
  670. var mbz = reader.ReadElementContentAsString();
  671. if (!string.IsNullOrWhiteSpace(mbz))
  672. {
  673. item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mbz);
  674. }
  675. break;
  676. }
  677. case "tvrageid":
  678. {
  679. var id = reader.ReadElementContentAsString();
  680. if (!string.IsNullOrWhiteSpace(id))
  681. {
  682. item.SetProviderId(MetadataProviders.TvRage, id);
  683. }
  684. break;
  685. }
  686. case "audiodbartistid":
  687. {
  688. var id = reader.ReadElementContentAsString();
  689. if (!string.IsNullOrWhiteSpace(id))
  690. {
  691. item.SetProviderId(MetadataProviders.AudioDbArtist, id);
  692. }
  693. break;
  694. }
  695. case "audiodbalbumid":
  696. {
  697. var id = reader.ReadElementContentAsString();
  698. if (!string.IsNullOrWhiteSpace(id))
  699. {
  700. item.SetProviderId(MetadataProviders.AudioDbAlbum, id);
  701. }
  702. break;
  703. }
  704. case "rottentomatoesid":
  705. var rtId = reader.ReadElementContentAsString();
  706. if (!string.IsNullOrWhiteSpace(rtId))
  707. {
  708. item.SetProviderId(MetadataProviders.RottenTomatoes, rtId);
  709. }
  710. break;
  711. case "tmdbid":
  712. var tmdb = reader.ReadElementContentAsString();
  713. if (!string.IsNullOrWhiteSpace(tmdb))
  714. {
  715. item.SetProviderId(MetadataProviders.Tmdb, tmdb);
  716. }
  717. break;
  718. case "collectionnumber":
  719. var tmdbCollection = reader.ReadElementContentAsString();
  720. if (!string.IsNullOrWhiteSpace(tmdbCollection))
  721. {
  722. item.SetProviderId(MetadataProviders.TmdbCollection, tmdbCollection);
  723. }
  724. break;
  725. case "tvcomid":
  726. var TVcomId = reader.ReadElementContentAsString();
  727. if (!string.IsNullOrWhiteSpace(TVcomId))
  728. {
  729. item.SetProviderId(MetadataProviders.Tvcom, TVcomId);
  730. }
  731. break;
  732. case "zap2itid":
  733. var zap2ItId = reader.ReadElementContentAsString();
  734. if (!string.IsNullOrWhiteSpace(zap2ItId))
  735. {
  736. item.SetProviderId(MetadataProviders.Zap2It, zap2ItId);
  737. }
  738. break;
  739. case "imdb_id":
  740. case "imdbid":
  741. var imDbId = reader.ReadElementContentAsString();
  742. if (!string.IsNullOrWhiteSpace(imDbId))
  743. {
  744. item.SetProviderId(MetadataProviders.Imdb, imDbId);
  745. }
  746. break;
  747. case "genre":
  748. {
  749. var val = reader.ReadElementContentAsString();
  750. if (!string.IsNullOrWhiteSpace(val))
  751. {
  752. var parts = val.Split('/')
  753. .Select(i => i.Trim())
  754. .Where(i => !string.IsNullOrWhiteSpace(i));
  755. foreach (var p in parts)
  756. {
  757. item.AddGenre(p);
  758. }
  759. }
  760. break;
  761. }
  762. case "style":
  763. case "tag":
  764. {
  765. var val = reader.ReadElementContentAsString();
  766. if (!string.IsNullOrWhiteSpace(val))
  767. {
  768. var hasTags = item as IHasTags;
  769. if (hasTags != null)
  770. {
  771. hasTags.AddTag(val);
  772. }
  773. }
  774. break;
  775. }
  776. case "plotkeyword":
  777. {
  778. var val = reader.ReadElementContentAsString();
  779. var hasKeywords = item as IHasKeywords;
  780. if (hasKeywords != null)
  781. {
  782. if (!string.IsNullOrWhiteSpace(val))
  783. {
  784. hasKeywords.AddKeyword(val);
  785. }
  786. }
  787. break;
  788. }
  789. case "fileinfo":
  790. {
  791. using (var subtree = reader.ReadSubtree())
  792. {
  793. FetchFromFileInfoNode(subtree, item);
  794. }
  795. break;
  796. }
  797. case "watched":
  798. {
  799. var val = reader.ReadElementContentAsString();
  800. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  801. {
  802. bool parsedValue;
  803. if (bool.TryParse(val, out parsedValue))
  804. {
  805. var userData = GetOrAdd(itemResult, userDataUserId);
  806. userData.Played = parsedValue;
  807. }
  808. }
  809. break;
  810. }
  811. case "playcount":
  812. {
  813. var val = reader.ReadElementContentAsString();
  814. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  815. {
  816. int parsedValue;
  817. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  818. {
  819. var userData = GetOrAdd(itemResult, userDataUserId);
  820. userData.PlayCount = parsedValue;
  821. if (parsedValue > 0)
  822. {
  823. userData.Played = true;
  824. }
  825. }
  826. }
  827. break;
  828. }
  829. case "lastplayed":
  830. {
  831. var val = reader.ReadElementContentAsString();
  832. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  833. {
  834. DateTime parsedValue;
  835. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  836. {
  837. var userData = GetOrAdd(itemResult, userDataUserId);
  838. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  839. }
  840. }
  841. break;
  842. }
  843. case "resume":
  844. {
  845. using (var subtree = reader.ReadSubtree())
  846. {
  847. if (!string.IsNullOrWhiteSpace(userDataUserId))
  848. {
  849. var userData = GetOrAdd(itemResult, userDataUserId);
  850. FetchFromResumeNode(subtree, item, userData);
  851. }
  852. }
  853. break;
  854. }
  855. case "isuserfavorite":
  856. {
  857. var val = reader.ReadElementContentAsString();
  858. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  859. {
  860. bool parsedValue;
  861. if (bool.TryParse(val, out parsedValue))
  862. {
  863. var userData = GetOrAdd(itemResult, userDataUserId);
  864. userData.IsFavorite = parsedValue;
  865. }
  866. }
  867. break;
  868. }
  869. case "userrating":
  870. {
  871. var val = reader.ReadElementContentAsString();
  872. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  873. {
  874. double parsedValue;
  875. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  876. {
  877. var userData = GetOrAdd(itemResult, userDataUserId);
  878. userData.Rating = parsedValue;
  879. }
  880. }
  881. break;
  882. }
  883. default:
  884. reader.Skip();
  885. break;
  886. }
  887. }
  888. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  889. {
  890. return result.GetOrAddUserData(userId);
  891. }
  892. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  893. {
  894. reader.MoveToContent();
  895. while (reader.Read())
  896. {
  897. if (reader.NodeType == XmlNodeType.Element)
  898. {
  899. switch (reader.Name)
  900. {
  901. case "position":
  902. {
  903. var val = reader.ReadElementContentAsString();
  904. if (!string.IsNullOrWhiteSpace(val))
  905. {
  906. double parsedValue;
  907. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  908. {
  909. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  910. }
  911. }
  912. break;
  913. }
  914. default:
  915. reader.Skip();
  916. break;
  917. }
  918. }
  919. }
  920. }
  921. private void FetchFromFileInfoNode(XmlReader reader, T item)
  922. {
  923. reader.MoveToContent();
  924. while (reader.Read())
  925. {
  926. if (reader.NodeType == XmlNodeType.Element)
  927. {
  928. switch (reader.Name)
  929. {
  930. case "streamdetails":
  931. {
  932. using (var subtree = reader.ReadSubtree())
  933. {
  934. FetchFromStreamDetailsNode(subtree, item);
  935. }
  936. break;
  937. }
  938. default:
  939. reader.Skip();
  940. break;
  941. }
  942. }
  943. }
  944. }
  945. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  946. {
  947. reader.MoveToContent();
  948. while (reader.Read())
  949. {
  950. if (reader.NodeType == XmlNodeType.Element)
  951. {
  952. switch (reader.Name)
  953. {
  954. case "video":
  955. {
  956. using (var subtree = reader.ReadSubtree())
  957. {
  958. FetchFromVideoNode(subtree, item);
  959. }
  960. break;
  961. }
  962. default:
  963. reader.Skip();
  964. break;
  965. }
  966. }
  967. }
  968. }
  969. private void FetchFromVideoNode(XmlReader reader, T item)
  970. {
  971. reader.MoveToContent();
  972. while (reader.Read())
  973. {
  974. if (reader.NodeType == XmlNodeType.Element)
  975. {
  976. switch (reader.Name)
  977. {
  978. case "format3d":
  979. {
  980. var video = item as Video;
  981. if (video != null)
  982. {
  983. var val = reader.ReadElementContentAsString();
  984. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  985. {
  986. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  987. }
  988. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  989. {
  990. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  991. }
  992. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  993. {
  994. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  995. }
  996. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  997. {
  998. video.Video3DFormat = Video3DFormat.FullSideBySide;
  999. }
  1000. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  1001. {
  1002. video.Video3DFormat = Video3DFormat.MVC;
  1003. }
  1004. }
  1005. break;
  1006. }
  1007. default:
  1008. reader.Skip();
  1009. break;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. /// <summary>
  1015. /// Gets the persons from XML node.
  1016. /// </summary>
  1017. /// <param name="reader">The reader.</param>
  1018. /// <returns>IEnumerable{PersonInfo}.</returns>
  1019. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  1020. {
  1021. var name = string.Empty;
  1022. var type = PersonType.Actor; // If type is not specified assume actor
  1023. var role = string.Empty;
  1024. int? sortOrder = null;
  1025. reader.MoveToContent();
  1026. while (reader.Read())
  1027. {
  1028. if (reader.NodeType == XmlNodeType.Element)
  1029. {
  1030. switch (reader.Name)
  1031. {
  1032. case "name":
  1033. name = reader.ReadElementContentAsString() ?? string.Empty;
  1034. break;
  1035. case "type":
  1036. {
  1037. var val = reader.ReadElementContentAsString();
  1038. if (!string.IsNullOrWhiteSpace(val))
  1039. {
  1040. type = val;
  1041. }
  1042. break;
  1043. }
  1044. case "role":
  1045. {
  1046. var val = reader.ReadElementContentAsString();
  1047. if (!string.IsNullOrWhiteSpace(val))
  1048. {
  1049. role = val;
  1050. }
  1051. break;
  1052. }
  1053. case "sortorder":
  1054. {
  1055. var val = reader.ReadElementContentAsString();
  1056. if (!string.IsNullOrWhiteSpace(val))
  1057. {
  1058. int intVal;
  1059. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  1060. {
  1061. sortOrder = intVal;
  1062. }
  1063. }
  1064. break;
  1065. }
  1066. default:
  1067. reader.Skip();
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. return new PersonInfo
  1073. {
  1074. Name = name.Trim(),
  1075. Role = role,
  1076. Type = type,
  1077. SortOrder = sortOrder
  1078. };
  1079. }
  1080. /// <summary>
  1081. /// Used to split names of comma or pipe delimeted genres and people
  1082. /// </summary>
  1083. /// <param name="value">The value.</param>
  1084. /// <returns>IEnumerable{System.String}.</returns>
  1085. private IEnumerable<string> SplitNames(string value)
  1086. {
  1087. value = value ?? string.Empty;
  1088. // Only split by comma if there is no pipe in the string
  1089. // We have to be careful to not split names like Matthew, Jr.
  1090. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1091. value = value.Trim().Trim(separator);
  1092. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1093. }
  1094. /// <summary>
  1095. /// Provides an additional overload for string.split
  1096. /// </summary>
  1097. /// <param name="val">The val.</param>
  1098. /// <param name="separators">The separators.</param>
  1099. /// <param name="options">The options.</param>
  1100. /// <returns>System.String[][].</returns>
  1101. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1102. {
  1103. return val.Split(separators, options);
  1104. }
  1105. }
  1106. }