BaseNfoParser.cs 48 KB

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