MusicBrainzAlbumProvider.cs 30 KB

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