BaseNfoParser.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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.DateCreated = 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 "tvmazeid":
  699. {
  700. var id = reader.ReadElementContentAsString();
  701. if (!string.IsNullOrWhiteSpace(id))
  702. {
  703. item.SetProviderId(MetadataProviders.TvMaze, id);
  704. }
  705. break;
  706. }
  707. case "audiodbartistid":
  708. {
  709. var id = reader.ReadElementContentAsString();
  710. if (!string.IsNullOrWhiteSpace(id))
  711. {
  712. item.SetProviderId(MetadataProviders.AudioDbArtist, id);
  713. }
  714. break;
  715. }
  716. case "audiodbalbumid":
  717. {
  718. var id = reader.ReadElementContentAsString();
  719. if (!string.IsNullOrWhiteSpace(id))
  720. {
  721. item.SetProviderId(MetadataProviders.AudioDbAlbum, id);
  722. }
  723. break;
  724. }
  725. case "rottentomatoesid":
  726. var rtId = reader.ReadElementContentAsString();
  727. if (!string.IsNullOrWhiteSpace(rtId))
  728. {
  729. item.SetProviderId(MetadataProviders.RottenTomatoes, rtId);
  730. }
  731. break;
  732. case "tmdbid":
  733. var tmdb = reader.ReadElementContentAsString();
  734. if (!string.IsNullOrWhiteSpace(tmdb))
  735. {
  736. item.SetProviderId(MetadataProviders.Tmdb, tmdb);
  737. }
  738. break;
  739. case "collectionnumber":
  740. case "tmdbcolid":
  741. var tmdbCollection = reader.ReadElementContentAsString();
  742. if (!string.IsNullOrWhiteSpace(tmdbCollection))
  743. {
  744. item.SetProviderId(MetadataProviders.TmdbCollection, tmdbCollection);
  745. }
  746. break;
  747. case "tvcomid":
  748. var TVcomId = reader.ReadElementContentAsString();
  749. if (!string.IsNullOrWhiteSpace(TVcomId))
  750. {
  751. item.SetProviderId(MetadataProviders.Tvcom, TVcomId);
  752. }
  753. break;
  754. case "zap2itid":
  755. var zap2ItId = reader.ReadElementContentAsString();
  756. if (!string.IsNullOrWhiteSpace(zap2ItId))
  757. {
  758. item.SetProviderId(MetadataProviders.Zap2It, zap2ItId);
  759. }
  760. break;
  761. case "imdb_id":
  762. case "imdbid":
  763. var imDbId = reader.ReadElementContentAsString();
  764. if (!string.IsNullOrWhiteSpace(imDbId))
  765. {
  766. item.SetProviderId(MetadataProviders.Imdb, imDbId);
  767. }
  768. break;
  769. case "genre":
  770. {
  771. var val = reader.ReadElementContentAsString();
  772. if (!string.IsNullOrWhiteSpace(val))
  773. {
  774. var parts = val.Split('/')
  775. .Select(i => i.Trim())
  776. .Where(i => !string.IsNullOrWhiteSpace(i));
  777. foreach (var p in parts)
  778. {
  779. item.AddGenre(p);
  780. }
  781. }
  782. break;
  783. }
  784. case "style":
  785. case "tag":
  786. {
  787. var val = reader.ReadElementContentAsString();
  788. if (!string.IsNullOrWhiteSpace(val))
  789. {
  790. item.AddTag(val);
  791. }
  792. break;
  793. }
  794. case "plotkeyword":
  795. {
  796. var val = reader.ReadElementContentAsString();
  797. if (!string.IsNullOrWhiteSpace(val))
  798. {
  799. item.AddKeyword(val);
  800. }
  801. break;
  802. }
  803. case "fileinfo":
  804. {
  805. using (var subtree = reader.ReadSubtree())
  806. {
  807. FetchFromFileInfoNode(subtree, item);
  808. }
  809. break;
  810. }
  811. case "watched":
  812. {
  813. var val = reader.ReadElementContentAsString();
  814. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  815. {
  816. bool parsedValue;
  817. if (bool.TryParse(val, out parsedValue))
  818. {
  819. var userData = GetOrAdd(itemResult, userDataUserId);
  820. userData.Played = parsedValue;
  821. }
  822. }
  823. break;
  824. }
  825. case "playcount":
  826. {
  827. var val = reader.ReadElementContentAsString();
  828. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  829. {
  830. int parsedValue;
  831. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out parsedValue))
  832. {
  833. var userData = GetOrAdd(itemResult, userDataUserId);
  834. userData.PlayCount = parsedValue;
  835. if (parsedValue > 0)
  836. {
  837. userData.Played = true;
  838. }
  839. }
  840. }
  841. break;
  842. }
  843. case "lastplayed":
  844. {
  845. var val = reader.ReadElementContentAsString();
  846. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  847. {
  848. DateTime parsedValue;
  849. if (DateTime.TryParseExact(val, "yyyy-MM-dd HH:mm:ss", _usCulture, DateTimeStyles.AssumeLocal, out parsedValue))
  850. {
  851. var userData = GetOrAdd(itemResult, userDataUserId);
  852. userData.LastPlayedDate = parsedValue.ToUniversalTime();
  853. }
  854. }
  855. break;
  856. }
  857. case "resume":
  858. {
  859. using (var subtree = reader.ReadSubtree())
  860. {
  861. if (!string.IsNullOrWhiteSpace(userDataUserId))
  862. {
  863. var userData = GetOrAdd(itemResult, userDataUserId);
  864. FetchFromResumeNode(subtree, item, userData);
  865. }
  866. }
  867. break;
  868. }
  869. case "isuserfavorite":
  870. {
  871. var val = reader.ReadElementContentAsString();
  872. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  873. {
  874. bool parsedValue;
  875. if (bool.TryParse(val, out parsedValue))
  876. {
  877. var userData = GetOrAdd(itemResult, userDataUserId);
  878. userData.IsFavorite = parsedValue;
  879. }
  880. }
  881. break;
  882. }
  883. case "userrating":
  884. {
  885. var val = reader.ReadElementContentAsString();
  886. if (!string.IsNullOrWhiteSpace(val) && !string.IsNullOrWhiteSpace(userDataUserId))
  887. {
  888. double parsedValue;
  889. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  890. {
  891. var userData = GetOrAdd(itemResult, userDataUserId);
  892. userData.Rating = parsedValue;
  893. }
  894. }
  895. break;
  896. }
  897. default:
  898. reader.Skip();
  899. break;
  900. }
  901. }
  902. private UserItemData GetOrAdd(MetadataResult<T> result, string userId)
  903. {
  904. return result.GetOrAddUserData(userId);
  905. }
  906. private void FetchFromResumeNode(XmlReader reader, T item, UserItemData userData)
  907. {
  908. reader.MoveToContent();
  909. while (reader.Read())
  910. {
  911. if (reader.NodeType == XmlNodeType.Element)
  912. {
  913. switch (reader.Name)
  914. {
  915. case "position":
  916. {
  917. var val = reader.ReadElementContentAsString();
  918. if (!string.IsNullOrWhiteSpace(val))
  919. {
  920. double parsedValue;
  921. if (double.TryParse(val, NumberStyles.Any, _usCulture, out parsedValue))
  922. {
  923. userData.PlaybackPositionTicks = TimeSpan.FromSeconds(parsedValue).Ticks;
  924. }
  925. }
  926. break;
  927. }
  928. default:
  929. reader.Skip();
  930. break;
  931. }
  932. }
  933. }
  934. }
  935. private void FetchFromFileInfoNode(XmlReader reader, T item)
  936. {
  937. reader.MoveToContent();
  938. while (reader.Read())
  939. {
  940. if (reader.NodeType == XmlNodeType.Element)
  941. {
  942. switch (reader.Name)
  943. {
  944. case "streamdetails":
  945. {
  946. using (var subtree = reader.ReadSubtree())
  947. {
  948. FetchFromStreamDetailsNode(subtree, item);
  949. }
  950. break;
  951. }
  952. default:
  953. reader.Skip();
  954. break;
  955. }
  956. }
  957. }
  958. }
  959. private void FetchFromStreamDetailsNode(XmlReader reader, T item)
  960. {
  961. reader.MoveToContent();
  962. while (reader.Read())
  963. {
  964. if (reader.NodeType == XmlNodeType.Element)
  965. {
  966. switch (reader.Name)
  967. {
  968. case "video":
  969. {
  970. using (var subtree = reader.ReadSubtree())
  971. {
  972. FetchFromVideoNode(subtree, item);
  973. }
  974. break;
  975. }
  976. default:
  977. reader.Skip();
  978. break;
  979. }
  980. }
  981. }
  982. }
  983. private void FetchFromVideoNode(XmlReader reader, T item)
  984. {
  985. reader.MoveToContent();
  986. while (reader.Read())
  987. {
  988. if (reader.NodeType == XmlNodeType.Element)
  989. {
  990. switch (reader.Name)
  991. {
  992. case "format3d":
  993. {
  994. var video = item as Video;
  995. if (video != null)
  996. {
  997. var val = reader.ReadElementContentAsString();
  998. if (string.Equals("HSBS", val, StringComparison.OrdinalIgnoreCase))
  999. {
  1000. video.Video3DFormat = Video3DFormat.HalfSideBySide;
  1001. }
  1002. else if (string.Equals("HTAB", val, StringComparison.OrdinalIgnoreCase))
  1003. {
  1004. video.Video3DFormat = Video3DFormat.HalfTopAndBottom;
  1005. }
  1006. else if (string.Equals("FTAB", val, StringComparison.OrdinalIgnoreCase))
  1007. {
  1008. video.Video3DFormat = Video3DFormat.FullTopAndBottom;
  1009. }
  1010. else if (string.Equals("FSBS", val, StringComparison.OrdinalIgnoreCase))
  1011. {
  1012. video.Video3DFormat = Video3DFormat.FullSideBySide;
  1013. }
  1014. else if (string.Equals("MVC", val, StringComparison.OrdinalIgnoreCase))
  1015. {
  1016. video.Video3DFormat = Video3DFormat.MVC;
  1017. }
  1018. }
  1019. break;
  1020. }
  1021. default:
  1022. reader.Skip();
  1023. break;
  1024. }
  1025. }
  1026. }
  1027. }
  1028. /// <summary>
  1029. /// Gets the persons from XML node.
  1030. /// </summary>
  1031. /// <param name="reader">The reader.</param>
  1032. /// <returns>IEnumerable{PersonInfo}.</returns>
  1033. private PersonInfo GetPersonFromXmlNode(XmlReader reader)
  1034. {
  1035. var name = string.Empty;
  1036. var type = PersonType.Actor; // If type is not specified assume actor
  1037. var role = string.Empty;
  1038. int? sortOrder = null;
  1039. reader.MoveToContent();
  1040. while (reader.Read())
  1041. {
  1042. if (reader.NodeType == XmlNodeType.Element)
  1043. {
  1044. switch (reader.Name)
  1045. {
  1046. case "name":
  1047. name = reader.ReadElementContentAsString() ?? string.Empty;
  1048. break;
  1049. case "type":
  1050. {
  1051. var val = reader.ReadElementContentAsString();
  1052. if (!string.IsNullOrWhiteSpace(val))
  1053. {
  1054. type = val;
  1055. }
  1056. break;
  1057. }
  1058. case "role":
  1059. {
  1060. var val = reader.ReadElementContentAsString();
  1061. if (!string.IsNullOrWhiteSpace(val))
  1062. {
  1063. role = val;
  1064. }
  1065. break;
  1066. }
  1067. case "sortorder":
  1068. {
  1069. var val = reader.ReadElementContentAsString();
  1070. if (!string.IsNullOrWhiteSpace(val))
  1071. {
  1072. int intVal;
  1073. if (int.TryParse(val, NumberStyles.Integer, _usCulture, out intVal))
  1074. {
  1075. sortOrder = intVal;
  1076. }
  1077. }
  1078. break;
  1079. }
  1080. default:
  1081. reader.Skip();
  1082. break;
  1083. }
  1084. }
  1085. }
  1086. return new PersonInfo
  1087. {
  1088. Name = name.Trim(),
  1089. Role = role,
  1090. Type = type,
  1091. SortOrder = sortOrder
  1092. };
  1093. }
  1094. /// <summary>
  1095. /// Used to split names of comma or pipe delimeted genres and people
  1096. /// </summary>
  1097. /// <param name="value">The value.</param>
  1098. /// <returns>IEnumerable{System.String}.</returns>
  1099. private IEnumerable<string> SplitNames(string value)
  1100. {
  1101. value = value ?? string.Empty;
  1102. // Only split by comma if there is no pipe in the string
  1103. // We have to be careful to not split names like Matthew, Jr.
  1104. var separator = value.IndexOf('|') == -1 && value.IndexOf(';') == -1 ? new[] { ',' } : new[] { '|', ';' };
  1105. value = value.Trim().Trim(separator);
  1106. return string.IsNullOrWhiteSpace(value) ? new string[] { } : Split(value, separator, StringSplitOptions.RemoveEmptyEntries);
  1107. }
  1108. /// <summary>
  1109. /// Provides an additional overload for string.split
  1110. /// </summary>
  1111. /// <param name="val">The val.</param>
  1112. /// <param name="separators">The separators.</param>
  1113. /// <param name="options">The options.</param>
  1114. /// <returns>System.String[][].</returns>
  1115. private static string[] Split(string val, char[] separators, StringSplitOptions options)
  1116. {
  1117. return val.Split(separators, options);
  1118. }
  1119. }
  1120. }