AlbumProvider.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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.Net.Http.Headers;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Xml;
  15. using MediaBrowser.Common;
  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. /// The Jellyfin user-agent is unrestricted but source IP must not exceed
  28. /// one request per second, therefore we rate limit to avoid throttling.
  29. /// Be prudent, use a value slightly above the minimun required.
  30. /// https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting
  31. /// </summary>
  32. private readonly long _musicBrainzQueryIntervalMs;
  33. /// <summary>
  34. /// For each single MB lookup/search, this is the maximum number of
  35. /// attempts that shall be made whilst receiving a 503 Server
  36. /// Unavailable (indicating throttled) response.
  37. /// </summary>
  38. private const uint MusicBrainzQueryAttempts = 5u;
  39. internal static MusicBrainzAlbumProvider Current;
  40. private readonly IHttpClientFactory _httpClientFactory;
  41. private readonly IApplicationHost _appHost;
  42. private readonly ILogger<MusicBrainzAlbumProvider> _logger;
  43. private readonly string _musicBrainzBaseUrl;
  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. /// <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);
  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("/ws/2/release/?query=\"{0}\" AND arid:{1}",
  233. WebUtility.UrlEncode(albumName),
  234. artistId);
  235. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  236. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  237. using var oReader = new StreamReader(stream, Encoding.UTF8);
  238. var settings = new XmlReaderSettings
  239. {
  240. ValidationType = ValidationType.None,
  241. CheckCharacters = false,
  242. IgnoreProcessingInstructions = true,
  243. IgnoreComments = true
  244. };
  245. using var reader = XmlReader.Create(oReader, settings);
  246. return ReleaseResult.Parse(reader).FirstOrDefault();
  247. }
  248. private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
  249. {
  250. var url = string.Format(
  251. CultureInfo.InvariantCulture,
  252. "/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
  253. WebUtility.UrlEncode(albumName),
  254. WebUtility.UrlEncode(artistName));
  255. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  256. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  257. using var oReader = new StreamReader(stream, Encoding.UTF8);
  258. var settings = new XmlReaderSettings()
  259. {
  260. ValidationType = ValidationType.None,
  261. CheckCharacters = false,
  262. IgnoreProcessingInstructions = true,
  263. IgnoreComments = true
  264. };
  265. using var reader = XmlReader.Create(oReader, settings);
  266. return ReleaseResult.Parse(reader).FirstOrDefault();
  267. }
  268. private class ReleaseResult
  269. {
  270. public string ReleaseId;
  271. public string ReleaseGroupId;
  272. public string Title;
  273. public string Overview;
  274. public int? Year;
  275. public List<ValueTuple<string, string>> Artists = new List<ValueTuple<string, string>>();
  276. public static IEnumerable<ReleaseResult> Parse(XmlReader reader)
  277. {
  278. reader.MoveToContent();
  279. reader.Read();
  280. // Loop through each element
  281. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  282. {
  283. if (reader.NodeType == XmlNodeType.Element)
  284. {
  285. switch (reader.Name)
  286. {
  287. case "release-list":
  288. {
  289. if (reader.IsEmptyElement)
  290. {
  291. reader.Read();
  292. continue;
  293. }
  294. using (var subReader = reader.ReadSubtree())
  295. {
  296. return ParseReleaseList(subReader).ToList();
  297. }
  298. }
  299. default:
  300. {
  301. reader.Skip();
  302. break;
  303. }
  304. }
  305. }
  306. else
  307. {
  308. reader.Read();
  309. }
  310. }
  311. return Enumerable.Empty<ReleaseResult>();
  312. }
  313. private static IEnumerable<ReleaseResult> ParseReleaseList(XmlReader reader)
  314. {
  315. reader.MoveToContent();
  316. reader.Read();
  317. // Loop through each element
  318. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  319. {
  320. if (reader.NodeType == XmlNodeType.Element)
  321. {
  322. switch (reader.Name)
  323. {
  324. case "release":
  325. {
  326. if (reader.IsEmptyElement)
  327. {
  328. reader.Read();
  329. continue;
  330. }
  331. var releaseId = reader.GetAttribute("id");
  332. using (var subReader = reader.ReadSubtree())
  333. {
  334. var release = ParseRelease(subReader, releaseId);
  335. if (release != null)
  336. {
  337. yield return release;
  338. }
  339. }
  340. break;
  341. }
  342. default:
  343. {
  344. reader.Skip();
  345. break;
  346. }
  347. }
  348. }
  349. else
  350. {
  351. reader.Read();
  352. }
  353. }
  354. }
  355. private static ReleaseResult ParseRelease(XmlReader reader, string releaseId)
  356. {
  357. var result = new ReleaseResult
  358. {
  359. ReleaseId = releaseId
  360. };
  361. reader.MoveToContent();
  362. reader.Read();
  363. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  364. // Loop through each element
  365. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  366. {
  367. if (reader.NodeType == XmlNodeType.Element)
  368. {
  369. switch (reader.Name)
  370. {
  371. case "title":
  372. {
  373. result.Title = reader.ReadElementContentAsString();
  374. break;
  375. }
  376. case "date":
  377. {
  378. var val = reader.ReadElementContentAsString();
  379. if (DateTime.TryParse(val, out var date))
  380. {
  381. result.Year = date.Year;
  382. }
  383. break;
  384. }
  385. case "annotation":
  386. {
  387. result.Overview = reader.ReadElementContentAsString();
  388. break;
  389. }
  390. case "release-group":
  391. {
  392. result.ReleaseGroupId = reader.GetAttribute("id");
  393. reader.Skip();
  394. break;
  395. }
  396. case "artist-credit":
  397. {
  398. using (var subReader = reader.ReadSubtree())
  399. {
  400. var artist = ParseArtistCredit(subReader);
  401. if (!string.IsNullOrEmpty(artist.Item1))
  402. {
  403. result.Artists.Add(artist);
  404. }
  405. }
  406. break;
  407. }
  408. default:
  409. {
  410. reader.Skip();
  411. break;
  412. }
  413. }
  414. }
  415. else
  416. {
  417. reader.Read();
  418. }
  419. }
  420. return result;
  421. }
  422. }
  423. private static ValueTuple<string, string> ParseArtistCredit(XmlReader reader)
  424. {
  425. reader.MoveToContent();
  426. reader.Read();
  427. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  428. // Loop through each element
  429. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  430. {
  431. if (reader.NodeType == XmlNodeType.Element)
  432. {
  433. switch (reader.Name)
  434. {
  435. case "name-credit":
  436. {
  437. using (var subReader = reader.ReadSubtree())
  438. {
  439. return ParseArtistNameCredit(subReader);
  440. }
  441. }
  442. default:
  443. {
  444. reader.Skip();
  445. break;
  446. }
  447. }
  448. }
  449. else
  450. {
  451. reader.Read();
  452. }
  453. }
  454. return new ValueTuple<string, string>();
  455. }
  456. private static (string, string) ParseArtistNameCredit(XmlReader reader)
  457. {
  458. reader.MoveToContent();
  459. reader.Read();
  460. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  461. // Loop through each element
  462. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  463. {
  464. if (reader.NodeType == XmlNodeType.Element)
  465. {
  466. switch (reader.Name)
  467. {
  468. case "artist":
  469. {
  470. var id = reader.GetAttribute("id");
  471. using (var subReader = reader.ReadSubtree())
  472. {
  473. return ParseArtistArtistCredit(subReader, id);
  474. }
  475. }
  476. default:
  477. {
  478. reader.Skip();
  479. break;
  480. }
  481. }
  482. }
  483. else
  484. {
  485. reader.Read();
  486. }
  487. }
  488. return (null, null);
  489. }
  490. private static (string name, string id) ParseArtistArtistCredit(XmlReader reader, string artistId)
  491. {
  492. reader.MoveToContent();
  493. reader.Read();
  494. string name = null;
  495. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  496. // Loop through each element
  497. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  498. {
  499. if (reader.NodeType == XmlNodeType.Element)
  500. {
  501. switch (reader.Name)
  502. {
  503. case "name":
  504. {
  505. name = reader.ReadElementContentAsString();
  506. break;
  507. }
  508. default:
  509. {
  510. reader.Skip();
  511. break;
  512. }
  513. }
  514. }
  515. else
  516. {
  517. reader.Read();
  518. }
  519. }
  520. return (name, artistId);
  521. }
  522. private async Task<string> GetReleaseIdFromReleaseGroupId(string releaseGroupId, CancellationToken cancellationToken)
  523. {
  524. var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
  525. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  526. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  527. using var oReader = new StreamReader(stream, Encoding.UTF8);
  528. var settings = new XmlReaderSettings
  529. {
  530. ValidationType = ValidationType.None,
  531. CheckCharacters = false,
  532. IgnoreProcessingInstructions = true,
  533. IgnoreComments = true
  534. };
  535. using var reader = XmlReader.Create(oReader, settings);
  536. var result = ReleaseResult.Parse(reader).FirstOrDefault();
  537. return result?.ReleaseId;
  538. }
  539. /// <summary>
  540. /// Gets the release group id internal.
  541. /// </summary>
  542. /// <param name="releaseEntryId">The release entry id.</param>
  543. /// <param name="cancellationToken">The cancellation token.</param>
  544. /// <returns>Task{System.String}.</returns>
  545. private async Task<string> GetReleaseGroupFromReleaseId(string releaseEntryId, CancellationToken cancellationToken)
  546. {
  547. var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture);
  548. using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  549. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  550. using var oReader = new StreamReader(stream, Encoding.UTF8);
  551. var settings = new XmlReaderSettings
  552. {
  553. ValidationType = ValidationType.None,
  554. CheckCharacters = false,
  555. IgnoreProcessingInstructions = true,
  556. IgnoreComments = true
  557. };
  558. using (var reader = XmlReader.Create(oReader, settings))
  559. {
  560. reader.MoveToContent();
  561. reader.Read();
  562. // Loop through each element
  563. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  564. {
  565. if (reader.NodeType == XmlNodeType.Element)
  566. {
  567. switch (reader.Name)
  568. {
  569. case "release-group-list":
  570. {
  571. if (reader.IsEmptyElement)
  572. {
  573. reader.Read();
  574. continue;
  575. }
  576. using (var subReader = reader.ReadSubtree())
  577. {
  578. return GetFirstReleaseGroupId(subReader);
  579. }
  580. }
  581. default:
  582. {
  583. reader.Skip();
  584. break;
  585. }
  586. }
  587. }
  588. else
  589. {
  590. reader.Read();
  591. }
  592. }
  593. return null;
  594. }
  595. }
  596. private string GetFirstReleaseGroupId(XmlReader reader)
  597. {
  598. reader.MoveToContent();
  599. reader.Read();
  600. // Loop through each element
  601. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  602. {
  603. if (reader.NodeType == XmlNodeType.Element)
  604. {
  605. switch (reader.Name)
  606. {
  607. case "release-group":
  608. {
  609. return reader.GetAttribute("id");
  610. }
  611. default:
  612. {
  613. reader.Skip();
  614. break;
  615. }
  616. }
  617. }
  618. else
  619. {
  620. reader.Read();
  621. }
  622. }
  623. return null;
  624. }
  625. /// <summary>
  626. /// Makes request to MusicBrainz server and awaits a response.
  627. /// A 503 Service Unavailable response indicates throttling to maintain a rate limit.
  628. /// A number of retries shall be made in order to try and satisfy the request before
  629. /// giving up and returning null.
  630. /// </summary>
  631. internal async Task<HttpResponseMessage> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
  632. {
  633. using var options = new HttpRequestMessage(HttpMethod.Get, _musicBrainzBaseUrl.TrimEnd('/') + url);
  634. // MusicBrainz request a contact email address is supplied, as comment, in user agent field:
  635. // https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting#User-Agent
  636. options.Headers.UserAgent.Add(new ProductInfoHeaderValue(string.Format(
  637. CultureInfo.InvariantCulture,
  638. "{0} ( {1} )",
  639. _appHost.ApplicationUserAgent,
  640. _appHost.ApplicationUserAgentAddress)));
  641. HttpResponseMessage response;
  642. var attempts = 0u;
  643. do
  644. {
  645. attempts++;
  646. if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
  647. {
  648. // MusicBrainz is extremely adamant about limiting to one request per second
  649. var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
  650. await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
  651. }
  652. // Write time since last request to debug log as evidence we're meeting rate limit
  653. // requirement, before resetting stopwatch back to zero.
  654. _logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
  655. _stopWatchMusicBrainz.Restart();
  656. response = await _httpClientFactory.CreateClient().SendAsync(options).ConfigureAwait(false);
  657. // We retry a finite number of times, and only whilst MB is indicating 503 (throttling)
  658. }
  659. while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
  660. // Log error if unable to query MB database due to throttling
  661. if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
  662. {
  663. _logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, options.RequestUri);
  664. }
  665. return response;
  666. }
  667. /// <inheritdoc />
  668. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  669. {
  670. throw new NotImplementedException();
  671. }
  672. }
  673. }