AlbumProvider.cs 30 KB

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