AlbumProvider.cs 30 KB

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