MusicBrainzAlbumProvider.cs 30 KB

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