MusicBrainzAlbumProvider.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. #pragma warning disable CS1591, SA1401
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Xml;
  14. using MediaBrowser.Common;
  15. using MediaBrowser.Common.Net;
  16. using MediaBrowser.Controller.Entities.Audio;
  17. using MediaBrowser.Controller.Providers;
  18. using MediaBrowser.Model.Entities;
  19. using MediaBrowser.Model.Providers;
  20. using MediaBrowser.Providers.Plugins.MusicBrainz;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.Providers.Music
  23. {
  24. public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder, IDisposable
  25. {
  26. /// <summary>
  27. /// For each single MB lookup/search, this is the maximum number of
  28. /// attempts that shall be made whilst receiving a 503 Server
  29. /// Unavailable (indicating throttled) response.
  30. /// </summary>
  31. private const uint MusicBrainzQueryAttempts = 5u;
  32. /// <summary>
  33. /// The Jellyfin user-agent is unrestricted but source IP must not exceed
  34. /// one request per second, therefore we rate limit to avoid throttling.
  35. /// Be prudent, use a value slightly above the minimun required.
  36. /// https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting.
  37. /// </summary>
  38. private readonly long _musicBrainzQueryIntervalMs;
  39. private readonly IHttpClientFactory _httpClientFactory;
  40. private readonly ILogger<MusicBrainzAlbumProvider> _logger;
  41. private readonly string _musicBrainzBaseUrl;
  42. private SemaphoreSlim _apiRequestLock = new SemaphoreSlim(1, 1);
  43. private Stopwatch _stopWatchMusicBrainz = new Stopwatch();
  44. public MusicBrainzAlbumProvider(
  45. IHttpClientFactory httpClientFactory,
  46. ILogger<MusicBrainzAlbumProvider> logger)
  47. {
  48. _httpClientFactory = httpClientFactory;
  49. _logger = logger;
  50. _musicBrainzBaseUrl = Plugin.Instance.Configuration.Server;
  51. _musicBrainzQueryIntervalMs = Plugin.Instance.Configuration.RateLimit;
  52. // Use a stopwatch to ensure we don't exceed the MusicBrainz rate limit
  53. _stopWatchMusicBrainz.Start();
  54. Current = this;
  55. }
  56. internal static MusicBrainzAlbumProvider Current { get; private set; }
  57. /// <inheritdoc />
  58. public string Name => "MusicBrainz";
  59. /// <inheritdoc />
  60. public int Order => 0;
  61. /// <inheritdoc />
  62. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
  63. {
  64. var releaseId = searchInfo.GetReleaseId();
  65. var releaseGroupId = searchInfo.GetReleaseGroupId();
  66. string url;
  67. if (!string.IsNullOrEmpty(releaseId))
  68. {
  69. url = "/ws/2/release/?query=reid:" + releaseId.ToString(CultureInfo.InvariantCulture);
  70. }
  71. else if (!string.IsNullOrEmpty(releaseGroupId))
  72. {
  73. url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
  74. }
  75. else
  76. {
  77. var artistMusicBrainzId = searchInfo.GetMusicBrainzArtistId();
  78. if (!string.IsNullOrWhiteSpace(artistMusicBrainzId))
  79. {
  80. url = string.Format(
  81. CultureInfo.InvariantCulture,
  82. "/ws/2/release/?query=\"{0}\" AND arid:{1}",
  83. WebUtility.UrlEncode(searchInfo.Name),
  84. artistMusicBrainzId);
  85. }
  86. else
  87. {
  88. // I'm sure there is a better way but for now it resolves search for 12" Mixes
  89. var queryName = searchInfo.Name.Replace("\"", string.Empty, StringComparison.Ordinal);
  90. url = string.Format(
  91. CultureInfo.InvariantCulture,
  92. "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
  93. WebUtility.UrlEncode(queryName),
  94. WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
  95. }
  96. }
  97. if (!string.IsNullOrWhiteSpace(url))
  98. {
  99. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  100. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  101. return GetResultsFromResponse(stream);
  102. }
  103. return Enumerable.Empty<RemoteSearchResult>();
  104. }
  105. private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream)
  106. {
  107. using var oReader = new StreamReader(stream, Encoding.UTF8);
  108. var settings = new XmlReaderSettings()
  109. {
  110. ValidationType = ValidationType.None,
  111. CheckCharacters = false,
  112. IgnoreProcessingInstructions = true,
  113. IgnoreComments = true
  114. };
  115. using var reader = XmlReader.Create(oReader, settings);
  116. var results = ReleaseResult.Parse(reader);
  117. return results.Select(i =>
  118. {
  119. var result = new RemoteSearchResult
  120. {
  121. Name = i.Title,
  122. ProductionYear = i.Year
  123. };
  124. if (i.Artists.Count > 0)
  125. {
  126. result.AlbumArtist = new RemoteSearchResult
  127. {
  128. SearchProviderName = Name,
  129. Name = i.Artists[0].Item1
  130. };
  131. result.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, i.Artists[0].Item2);
  132. }
  133. if (!string.IsNullOrWhiteSpace(i.ReleaseId))
  134. {
  135. result.SetProviderId(MetadataProvider.MusicBrainzAlbum, i.ReleaseId);
  136. }
  137. if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId))
  138. {
  139. result.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, i.ReleaseGroupId);
  140. }
  141. return result;
  142. });
  143. }
  144. /// <inheritdoc />
  145. public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
  146. {
  147. var releaseId = info.GetReleaseId();
  148. var releaseGroupId = info.GetReleaseGroupId();
  149. var result = new MetadataResult<MusicAlbum>
  150. {
  151. Item = new MusicAlbum()
  152. };
  153. // If we have a release group Id but not a release Id...
  154. if (string.IsNullOrWhiteSpace(releaseId) && !string.IsNullOrWhiteSpace(releaseGroupId))
  155. {
  156. releaseId = await GetReleaseIdFromReleaseGroupId(releaseGroupId, cancellationToken).ConfigureAwait(false);
  157. result.HasMetadata = true;
  158. }
  159. if (string.IsNullOrWhiteSpace(releaseId))
  160. {
  161. var artistMusicBrainzId = info.GetMusicBrainzArtistId();
  162. var releaseResult = await GetReleaseResult(artistMusicBrainzId, info.GetAlbumArtist(), info.Name, cancellationToken).ConfigureAwait(false);
  163. if (releaseResult != null)
  164. {
  165. if (!string.IsNullOrWhiteSpace(releaseResult.ReleaseId))
  166. {
  167. releaseId = releaseResult.ReleaseId;
  168. result.HasMetadata = true;
  169. }
  170. if (!string.IsNullOrWhiteSpace(releaseResult.ReleaseGroupId))
  171. {
  172. releaseGroupId = releaseResult.ReleaseGroupId;
  173. result.HasMetadata = true;
  174. }
  175. result.Item.ProductionYear = releaseResult.Year;
  176. result.Item.Overview = releaseResult.Overview;
  177. }
  178. }
  179. // If we have a release Id but not a release group Id...
  180. if (!string.IsNullOrWhiteSpace(releaseId) && string.IsNullOrWhiteSpace(releaseGroupId))
  181. {
  182. releaseGroupId = await GetReleaseGroupFromReleaseId(releaseId, cancellationToken).ConfigureAwait(false);
  183. result.HasMetadata = true;
  184. }
  185. if (!string.IsNullOrWhiteSpace(releaseId) || !string.IsNullOrWhiteSpace(releaseGroupId))
  186. {
  187. result.HasMetadata = true;
  188. }
  189. if (result.HasMetadata)
  190. {
  191. if (!string.IsNullOrEmpty(releaseId))
  192. {
  193. result.Item.SetProviderId(MetadataProvider.MusicBrainzAlbum, releaseId);
  194. }
  195. if (!string.IsNullOrEmpty(releaseGroupId))
  196. {
  197. result.Item.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, releaseGroupId);
  198. }
  199. }
  200. return result;
  201. }
  202. private Task<ReleaseResult> GetReleaseResult(string artistMusicBrainId, string artistName, string albumName, CancellationToken cancellationToken)
  203. {
  204. if (!string.IsNullOrEmpty(artistMusicBrainId))
  205. {
  206. return GetReleaseResult(albumName, artistMusicBrainId, cancellationToken);
  207. }
  208. if (string.IsNullOrWhiteSpace(artistName))
  209. {
  210. return Task.FromResult(new ReleaseResult());
  211. }
  212. return GetReleaseResultByArtistName(albumName, artistName, cancellationToken);
  213. }
  214. private async Task<ReleaseResult> GetReleaseResult(string albumName, string artistId, CancellationToken cancellationToken)
  215. {
  216. var url = string.Format(
  217. CultureInfo.InvariantCulture,
  218. "/ws/2/release/?query=\"{0}\" AND arid:{1}",
  219. WebUtility.UrlEncode(albumName),
  220. artistId);
  221. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  222. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  223. using var oReader = new StreamReader(stream, Encoding.UTF8);
  224. var settings = new XmlReaderSettings
  225. {
  226. ValidationType = ValidationType.None,
  227. CheckCharacters = false,
  228. IgnoreProcessingInstructions = true,
  229. IgnoreComments = true
  230. };
  231. using var reader = XmlReader.Create(oReader, settings);
  232. return ReleaseResult.Parse(reader).FirstOrDefault();
  233. }
  234. private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
  235. {
  236. var url = string.Format(
  237. CultureInfo.InvariantCulture,
  238. "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
  239. WebUtility.UrlEncode(albumName),
  240. WebUtility.UrlEncode(artistName));
  241. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  242. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  243. using var oReader = new StreamReader(stream, Encoding.UTF8);
  244. var settings = new XmlReaderSettings()
  245. {
  246. ValidationType = ValidationType.None,
  247. CheckCharacters = false,
  248. IgnoreProcessingInstructions = true,
  249. IgnoreComments = true
  250. };
  251. using var reader = XmlReader.Create(oReader, settings);
  252. return ReleaseResult.Parse(reader).FirstOrDefault();
  253. }
  254. private static (string, string) ParseArtistCredit(XmlReader reader)
  255. {
  256. reader.MoveToContent();
  257. reader.Read();
  258. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  259. // Loop through each element
  260. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  261. {
  262. if (reader.NodeType == XmlNodeType.Element)
  263. {
  264. switch (reader.Name)
  265. {
  266. case "name-credit":
  267. {
  268. using var subReader = reader.ReadSubtree();
  269. return ParseArtistNameCredit(subReader);
  270. }
  271. default:
  272. {
  273. reader.Skip();
  274. break;
  275. }
  276. }
  277. }
  278. else
  279. {
  280. reader.Read();
  281. }
  282. }
  283. return default;
  284. }
  285. private static (string, string) ParseArtistNameCredit(XmlReader reader)
  286. {
  287. reader.MoveToContent();
  288. reader.Read();
  289. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  290. // Loop through each element
  291. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  292. {
  293. if (reader.NodeType == XmlNodeType.Element)
  294. {
  295. switch (reader.Name)
  296. {
  297. case "artist":
  298. {
  299. var id = reader.GetAttribute("id");
  300. using var subReader = reader.ReadSubtree();
  301. return ParseArtistArtistCredit(subReader, id);
  302. }
  303. default:
  304. {
  305. reader.Skip();
  306. break;
  307. }
  308. }
  309. }
  310. else
  311. {
  312. reader.Read();
  313. }
  314. }
  315. return (null, null);
  316. }
  317. private static (string name, string id) ParseArtistArtistCredit(XmlReader reader, string artistId)
  318. {
  319. reader.MoveToContent();
  320. reader.Read();
  321. string name = null;
  322. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  323. // Loop through each element
  324. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  325. {
  326. if (reader.NodeType == XmlNodeType.Element)
  327. {
  328. switch (reader.Name)
  329. {
  330. case "name":
  331. {
  332. name = reader.ReadElementContentAsString();
  333. break;
  334. }
  335. default:
  336. {
  337. reader.Skip();
  338. break;
  339. }
  340. }
  341. }
  342. else
  343. {
  344. reader.Read();
  345. }
  346. }
  347. return (name, artistId);
  348. }
  349. private async Task<string> GetReleaseIdFromReleaseGroupId(string releaseGroupId, CancellationToken cancellationToken)
  350. {
  351. var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
  352. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  353. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  354. using var oReader = new StreamReader(stream, Encoding.UTF8);
  355. var settings = new XmlReaderSettings
  356. {
  357. ValidationType = ValidationType.None,
  358. CheckCharacters = false,
  359. IgnoreProcessingInstructions = true,
  360. IgnoreComments = true
  361. };
  362. using var reader = XmlReader.Create(oReader, settings);
  363. var result = ReleaseResult.Parse(reader).FirstOrDefault();
  364. return result?.ReleaseId;
  365. }
  366. /// <summary>
  367. /// Gets the release group id internal.
  368. /// </summary>
  369. /// <param name="releaseEntryId">The release entry id.</param>
  370. /// <param name="cancellationToken">The cancellation token.</param>
  371. /// <returns>Task{System.String}.</returns>
  372. private async Task<string> GetReleaseGroupFromReleaseId(string releaseEntryId, CancellationToken cancellationToken)
  373. {
  374. var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture);
  375. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  376. await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  377. using var oReader = new StreamReader(stream, Encoding.UTF8);
  378. var settings = new XmlReaderSettings
  379. {
  380. ValidationType = ValidationType.None,
  381. CheckCharacters = false,
  382. IgnoreProcessingInstructions = true,
  383. IgnoreComments = true
  384. };
  385. using var reader = XmlReader.Create(oReader, settings);
  386. reader.MoveToContent();
  387. reader.Read();
  388. // Loop through each element
  389. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  390. {
  391. if (reader.NodeType == XmlNodeType.Element)
  392. {
  393. switch (reader.Name)
  394. {
  395. case "release-group-list":
  396. {
  397. if (reader.IsEmptyElement)
  398. {
  399. reader.Read();
  400. continue;
  401. }
  402. using var subReader = reader.ReadSubtree();
  403. return GetFirstReleaseGroupId(subReader);
  404. }
  405. default:
  406. {
  407. reader.Skip();
  408. break;
  409. }
  410. }
  411. }
  412. else
  413. {
  414. reader.Read();
  415. }
  416. }
  417. return null;
  418. }
  419. private string GetFirstReleaseGroupId(XmlReader reader)
  420. {
  421. reader.MoveToContent();
  422. reader.Read();
  423. // Loop through each element
  424. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  425. {
  426. if (reader.NodeType == XmlNodeType.Element)
  427. {
  428. switch (reader.Name)
  429. {
  430. case "release-group":
  431. {
  432. return reader.GetAttribute("id");
  433. }
  434. default:
  435. {
  436. reader.Skip();
  437. break;
  438. }
  439. }
  440. }
  441. else
  442. {
  443. reader.Read();
  444. }
  445. }
  446. return null;
  447. }
  448. /// <summary>
  449. /// Makes request to MusicBrainz server and awaits a response.
  450. /// A 503 Service Unavailable response indicates throttling to maintain a rate limit.
  451. /// A number of retries shall be made in order to try and satisfy the request before
  452. /// giving up and returning null.
  453. /// </summary>
  454. /// <param name="url">Address of MusicBrainz server.</param>
  455. /// <param name="cancellationToken">CancellationToken to use for method.</param>
  456. /// <returns>Returns response from MusicBrainz service.</returns>
  457. internal async Task<HttpResponseMessage> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
  458. {
  459. await _apiRequestLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  460. try
  461. {
  462. HttpResponseMessage response;
  463. var attempts = 0u;
  464. var requestUrl = _musicBrainzBaseUrl.TrimEnd('/') + url;
  465. do
  466. {
  467. attempts++;
  468. if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
  469. {
  470. // MusicBrainz is extremely adamant about limiting to one request per second.
  471. var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
  472. await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
  473. }
  474. // Write time since last request to debug log as evidence we're meeting rate limit
  475. // requirement, before resetting stopwatch back to zero.
  476. _logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
  477. _stopWatchMusicBrainz.Restart();
  478. using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
  479. response = await _httpClientFactory
  480. .CreateClient(NamedClient.MusicBrainz)
  481. .SendAsync(request, cancellationToken)
  482. .ConfigureAwait(false);
  483. // We retry a finite number of times, and only whilst MB is indicating 503 (throttling).
  484. }
  485. while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
  486. // Log error if unable to query MB database due to throttling.
  487. if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
  488. {
  489. _logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, requestUrl);
  490. }
  491. return response;
  492. }
  493. finally
  494. {
  495. _apiRequestLock.Release();
  496. }
  497. }
  498. /// <inheritdoc />
  499. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  500. {
  501. throw new NotImplementedException();
  502. }
  503. protected virtual void Dispose(bool disposing)
  504. {
  505. if (disposing)
  506. {
  507. _apiRequestLock?.Dispose();
  508. }
  509. }
  510. /// <inheritdoc />
  511. public void Dispose()
  512. {
  513. Dispose(true);
  514. GC.SuppressFinalize(this);
  515. }
  516. private class ReleaseResult
  517. {
  518. public string ReleaseId;
  519. public string ReleaseGroupId;
  520. public string Title;
  521. public string Overview;
  522. public int? Year;
  523. public List<ValueTuple<string, string>> Artists = new List<ValueTuple<string, string>>();
  524. public static IEnumerable<ReleaseResult> Parse(XmlReader reader)
  525. {
  526. reader.MoveToContent();
  527. reader.Read();
  528. // Loop through each element
  529. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  530. {
  531. if (reader.NodeType == XmlNodeType.Element)
  532. {
  533. switch (reader.Name)
  534. {
  535. case "release-list":
  536. {
  537. if (reader.IsEmptyElement)
  538. {
  539. reader.Read();
  540. continue;
  541. }
  542. using var subReader = reader.ReadSubtree();
  543. return ParseReleaseList(subReader).ToList();
  544. }
  545. default:
  546. {
  547. reader.Skip();
  548. break;
  549. }
  550. }
  551. }
  552. else
  553. {
  554. reader.Read();
  555. }
  556. }
  557. return Enumerable.Empty<ReleaseResult>();
  558. }
  559. private static IEnumerable<ReleaseResult> ParseReleaseList(XmlReader reader)
  560. {
  561. reader.MoveToContent();
  562. reader.Read();
  563. // Loop through each element
  564. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  565. {
  566. if (reader.NodeType == XmlNodeType.Element)
  567. {
  568. switch (reader.Name)
  569. {
  570. case "release":
  571. {
  572. if (reader.IsEmptyElement)
  573. {
  574. reader.Read();
  575. continue;
  576. }
  577. var releaseId = reader.GetAttribute("id");
  578. using var subReader = reader.ReadSubtree();
  579. var release = ParseRelease(subReader, releaseId);
  580. if (release != null)
  581. {
  582. yield return release;
  583. }
  584. break;
  585. }
  586. default:
  587. {
  588. reader.Skip();
  589. break;
  590. }
  591. }
  592. }
  593. else
  594. {
  595. reader.Read();
  596. }
  597. }
  598. }
  599. private static ReleaseResult ParseRelease(XmlReader reader, string releaseId)
  600. {
  601. var result = new ReleaseResult
  602. {
  603. ReleaseId = releaseId
  604. };
  605. reader.MoveToContent();
  606. reader.Read();
  607. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  608. // Loop through each element
  609. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  610. {
  611. if (reader.NodeType == XmlNodeType.Element)
  612. {
  613. switch (reader.Name)
  614. {
  615. case "title":
  616. {
  617. result.Title = reader.ReadElementContentAsString();
  618. break;
  619. }
  620. case "date":
  621. {
  622. var val = reader.ReadElementContentAsString();
  623. if (DateTime.TryParse(val, out var date))
  624. {
  625. result.Year = date.Year;
  626. }
  627. break;
  628. }
  629. case "annotation":
  630. {
  631. result.Overview = reader.ReadElementContentAsString();
  632. break;
  633. }
  634. case "release-group":
  635. {
  636. result.ReleaseGroupId = reader.GetAttribute("id");
  637. reader.Skip();
  638. break;
  639. }
  640. case "artist-credit":
  641. {
  642. using var subReader = reader.ReadSubtree();
  643. var artist = ParseArtistCredit(subReader);
  644. if (!string.IsNullOrEmpty(artist.Item1))
  645. {
  646. result.Artists.Add(artist);
  647. }
  648. break;
  649. }
  650. default:
  651. {
  652. reader.Skip();
  653. break;
  654. }
  655. }
  656. }
  657. else
  658. {
  659. reader.Read();
  660. }
  661. }
  662. return result;
  663. }
  664. }
  665. }
  666. }