BaseNfoParser.cs 48 KB

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