MusicBrainzAlbumProvider.cs 30 KB

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