AlbumProvider.cs 30 KB

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