BaseNfoParser.cs 46 KB

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