From 2aa8f47bfecef827b9c8057d291b6b5684d6ab76 Mon Sep 17 00:00:00 2001 From: jasonpatrickellykrause Date: Mon, 16 Nov 2026 14:34:29 -0700 Subject: [PATCH 1/2] Refresh the session token once for concurrent callers When the session expired during concurrent downloads, every in-flight call refreshed the token separately, so "retry once" became one deezer.getUserData call per request at the same moment. SetToken now holds a lock and tracks a token version: a caller whose request used an older token reuses a refresh that finished after its request was sent. SetARL forces a refresh so a new ARL always gets its own session. GetTrackUrl also throws InvalidARLException when no ARL is set, instead of a NullReferenceException. Co-Authored-By: Claude Opus 5.5 --- DeezNET.Tests/TokenRefreshTests.cs | 90 ++++++++++++++++++++++++++++++ DeezNET/Core.cs | 3 +- DeezNET/Downloader.cs | 8 ++- DeezNET/GWApi.cs | 42 ++++++++++++-- 4 files changed, 134 insertions(+), 9 deletions(-) create mode 100644 DeezNET.Tests/TokenRefreshTests.cs diff --git a/DeezNET.Tests/TokenRefreshTests.cs b/DeezNET.Tests/TokenRefreshTests.cs new file mode 100644 index 0000000..8ea4f13 --- /dev/null +++ b/DeezNET.Tests/TokenRefreshTests.cs @@ -0,0 +1,90 @@ +using System.Net; +using System.Web; +using Shouldly; + +namespace DeezNET.Tests +{ + public class TokenRefreshTests + { + [Fact] + public async Task ConcurrentStaleRefreshesShareOneRequest() + { + FakeDeezer deezer = new(); + GWApi gw = new(new HttpClient(deezer), "arl"); + + long stale = gw.TokenVersion; + await Task.WhenAll(Enumerable.Range(0, 5).Select(_ => gw.SetToken(staleVersion: stale))); + + deezer.UserDataCalls.ShouldBe(1); + gw._apiToken.ShouldBe("fresh"); + } + + [Fact] + public async Task ForcedRefreshesAlwaysRequest() + { + FakeDeezer deezer = new(); + GWApi gw = new(new HttpClient(deezer), "arl"); + + await gw.SetToken(force: true); + await gw.SetToken(force: true); + + deezer.UserDataCalls.ShouldBe(2); + } + + [Fact] + public async Task RefreshAfterAnotherCallerRefreshedIsSkipped() + { + FakeDeezer deezer = new(); + GWApi gw = new(new HttpClient(deezer), "arl"); + + long stale = gw.TokenVersion; + await gw.SetToken(staleVersion: stale); + // this caller's request used the old token too, but the refresh it needs already happened + await gw.SetToken(staleVersion: stale); + + deezer.UserDataCalls.ShouldBe(1); + } + + [Fact] + public async Task ConcurrentCallsRejectedForAnExpiredTokenRefreshOnce() + { + FakeDeezer deezer = new(); + GWApi gw = new(new HttpClient(deezer), "arl") { _apiToken = "expired" }; + + await Task.WhenAll(Enumerable.Range(0, 3).Select(i => gw.GetTrack(i))); + + deezer.UserDataCalls.ShouldBe(1); + } + + // answers deezer.getUserData with a fresh token, and rejects other methods unless they use it + private sealed class FakeDeezer : HttpMessageHandler + { + private int _userDataCalls; + public int UserDataCalls => _userDataCalls; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var query = HttpUtility.ParseQueryString(request.RequestUri!.Query); + + string body; + if (query["method"] == "deezer.getUserData") + { + Interlocked.Increment(ref _userDataCalls); + // long enough for the other callers to queue up behind the lock + await Task.Delay(100, cancellationToken); + body = """{"error":[],"results":{"checkForm":"fresh","USER":{"USER_ID":1}}}"""; + } + else if (query["api_token"] != "fresh") + { + body = """{"error":{"VALID_TOKEN_REQUIRED":"Invalid CSRF token"},"results":{}}"""; + } + else + { + body = """{"error":[],"results":{"SNG_ID":"1"}}"""; + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }; + } + } + } +} diff --git a/DeezNET/Core.cs b/DeezNET/Core.cs index 4e785c0..d9c4122 100644 --- a/DeezNET/Core.cs +++ b/DeezNET/Core.cs @@ -38,7 +38,8 @@ public async Task SetARL(string arl) _arl = arl; _gwApi._arl = arl; - await _gwApi.SetToken(); + // a new ARL needs its own session even if a refresh for the old one just finished + await _gwApi.SetToken(force: true); } public Downloader Downloader { get => _downloader; } diff --git a/DeezNET/Downloader.cs b/DeezNET/Downloader.cs index f466d3e..4b008df 100644 --- a/DeezNET/Downloader.cs +++ b/DeezNET/Downloader.cs @@ -287,9 +287,13 @@ private async Task GetTrackUrl(string token, Bitrate bitrate, Cancell if (_gw.ActiveUserData == null) await _gw.SetToken(cancelToken); + // SetToken does nothing without an ARL, which used to surface as a NullReferenceException below + JToken userData = _gw.ActiveUserData ?? throw new InvalidARLException("Downloading requires an ARL. Call DeezerClient.SetARL first."); + long tokenVersion = _gw.TokenVersion; + GetUrlRequestBody reqData = new() { - LicenseToken = _gw.ActiveUserData!["USER"]!["OPTIONS"]!["license_token"]!.ToString(), + LicenseToken = userData["USER"]!["OPTIONS"]!["license_token"]!.ToString(), TrackTokens = [token], Media = [ @@ -328,7 +332,7 @@ private async Task GetTrackUrl(string token, Bitrate bitrate, Cancell // the license token lives in the user data and expires; refresh it once before giving up if (!isRetry) { - await _gw.SetToken(cancelToken); + await _gw.SetToken(cancelToken, staleVersion: tokenVersion); return await GetTrackUrl(token, bitrate, cancelToken, true); } diff --git a/DeezNET/GWApi.cs b/DeezNET/GWApi.cs index 51a8e49..93eb936 100644 --- a/DeezNET/GWApi.cs +++ b/DeezNET/GWApi.cs @@ -26,14 +26,42 @@ internal GWApi(HttpClient client, string arl) private const int MAX_TOKEN_RETRIES = 1; private static readonly TimeSpan TOKEN_RETRY_DELAY = TimeSpan.FromSeconds(2); - internal async Task SetToken(CancellationToken token = default) + // one refresh at a time; concurrent downloads that all hit an expired session would otherwise each call + // deezer.getUserData at once, which is the kind of burst that gets an ARL flagged + private readonly SemaphoreSlim _tokenLock = new(1, 1); + private long _tokenVersion; + + // incremented after each successful refresh, so callers can tell whether their token is still the current one + internal long TokenVersion => Interlocked.Read(ref _tokenVersion); + + /// + /// Refreshes the API token and user data. + /// + /// Cancels the operation. + /// Refresh even if another caller already refreshed, such as after the ARL changes. + /// The the caller's failed request used. Defaults to the current version. + internal async Task SetToken(CancellationToken token = default, bool force = false, long? staleVersion = null) { if (string.IsNullOrEmpty(_arl)) return; - JToken userData = await GetUserData(token); - _activeUserData = userData; - _apiToken = userData["checkForm"]!.ToString(); + long versionSeen = staleVersion ?? TokenVersion; + await _tokenLock.WaitAsync(token); + try + { + // a caller refreshing a stale token can reuse a refresh that finished after its request was sent + if (!force && TokenVersion != versionSeen) + return; + + JToken userData = await GetUserData(token); + _activeUserData = userData; + _apiToken = userData["checkForm"]!.ToString(); + Interlocked.Increment(ref _tokenVersion); + } + finally + { + _tokenLock.Release(); + } } public async Task GetUserData(CancellationToken token = default) => await Call(USER_DATA_METHOD, needsArl: true, token: token); @@ -247,6 +275,7 @@ private async Task Call(string method, JObject? args = null, Dictionary< throw new InvalidARLException("A GWApi method is attempting to be called without being provided an ARL."); parameters ??= []; + long tokenVersion = TokenVersion; parameters["api_version"] = "1.0"; parameters["api_token"] = _apiToken; parameters["input"] = "3"; @@ -290,9 +319,10 @@ private async Task Call(string method, JObject? args = null, Dictionary< await Task.Delay(TOKEN_RETRY_DELAY, token); - // SetToken calls deezer.getUserData, so refreshing from inside that call would recurse + // SetToken calls deezer.getUserData, so refreshing from inside that call would recurse (and deadlock on + // the token lock); other calls reuse a refresh that another caller made after this request was sent if (method != USER_DATA_METHOD) - await SetToken(token); + await SetToken(token, staleVersion: tokenVersion); return await Call(method, args, parameters, needsArl, token, tokenRetries + 1); } From 24fb68375847461becdc357e1d2dcaba2d8a67e3 Mon Sep 17 00:00:00 2001 From: jasonpatrickellykrause Date: Mon, 16 Nov 2026 14:35:31 -0700 Subject: [PATCH 2/2] Dispose responses and fix smaller review findings - Dispose HttpResponseMessage in GWApi, PublicApi, GetTrackUrl, LRCLIB, MusicBrainz, and UnshortenURL. - UnshortenURL accepts any 3xx redirect, not only 302. - MusicBrainz lookups and the tagging block no longer swallow cancellation. - EscapeSearch escapes backslashes before quotes. - ApplyMetadataToTrackStream reads all four magic bytes across short reads. - RemoveSongs(s)FromPlaylist pass their cancellation token. - The MusicBrainz user agent reads its version from the assembly. - Bump to 1.2.6. Co-Authored-By: Claude Opus 5.5 --- DeezNET/DeezerURL.cs | 6 ++++-- DeezNET/Directory.Build.props | 2 +- DeezNET/Downloader.cs | 12 ++++++++---- DeezNET/GWApi.cs | 8 ++++---- DeezNET/MusicBrainzLookup.cs | 15 +++++++++------ DeezNET/PublicApi.cs | 2 +- README.md | 12 ++++++++++++ 7 files changed, 39 insertions(+), 18 deletions(-) diff --git a/DeezNET/DeezerURL.cs b/DeezNET/DeezerURL.cs index 71d85af..c35eb02 100644 --- a/DeezNET/DeezerURL.cs +++ b/DeezNET/DeezerURL.cs @@ -117,9 +117,11 @@ public static DeezerURL Parse(string url) public static string UnshortenURL(string url) { HttpRequestMessage req = new(HttpMethod.Get, url); - HttpResponseMessage resp = _httpClient.Send(req); + using HttpResponseMessage resp = _httpClient.Send(req); - string? target = resp.StatusCode == System.Net.HttpStatusCode.Redirect ? resp.Headers.Location?.OriginalString : null; + // any redirect status, not just 302; link shorteners also answer with 301, 303, 307, or 308 + int status = (int)resp.StatusCode; + string? target = status >= 300 && status < 400 ? resp.Headers.Location?.OriginalString : null; return target ?? throw new InvalidURLException($"{url} did not provide a redirect Location header."); } diff --git a/DeezNET/Directory.Build.props b/DeezNET/Directory.Build.props index 46bfe14..ea4b96b 100644 --- a/DeezNET/Directory.Build.props +++ b/DeezNET/Directory.Build.props @@ -1,6 +1,6 @@  - 1.2.5 + 1.2.6 TrevTV Copyright (C) Trevor Jackson latest diff --git a/DeezNET/Downloader.cs b/DeezNET/Downloader.cs index 4b008df..b43bdff 100644 --- a/DeezNET/Downloader.cs +++ b/DeezNET/Downloader.cs @@ -93,8 +93,12 @@ public async Task WriteRawTrackToFile(long trackId, string trackPath, Bitrate bi /// Cancels the operation. public async Task ApplyMetadataToTrackStream(long trackId, Stream trackStream, int coverResolution = 512, string lyrics = "", CancellationToken token = default) { + // a single read can return fewer than 4 bytes, which would misdetect a FLAC as an MP3 byte[] magicBuffer = new byte[4]; - await trackStream.ReadAsync(magicBuffer.AsMemory(0, 4), token); + int magicRead = 0; + int read; + while (magicRead < magicBuffer.Length && (read = await trackStream.ReadAsync(magicBuffer.AsMemory(magicRead), token)) > 0) + magicRead += read; string ext = Enumerable.SequenceEqual(magicBuffer, FLAC_MAGIC) ? ".flac" : ".mp3"; trackStream.Seek(0, SeekOrigin.Begin); @@ -176,7 +180,7 @@ public async Task ApplyMetadataToFile(long trackId, string trackPath, int coverR public async Task<(string plainLyrics, List? syncLyrics)?> FetchLyricsFromLRCLIB(string instance, string trackName, string artistName, string albumName, int duration, CancellationToken token = default) { var requestUrl = $"https://{instance}/api/get?artist_name={Uri.EscapeDataString(artistName)}&track_name={Uri.EscapeDataString(trackName)}&album_name={Uri.EscapeDataString(albumName)}&duration={duration}"; - var response = await _client.GetAsync(requestUrl, token); + using var response = await _client.GetAsync(requestUrl, token); if (response.IsSuccessStatusCode) { @@ -321,7 +325,7 @@ private async Task GetTrackUrl(string token, Bitrate bitrate, Cancell request.Headers.Add("Cookie", "arl=" + _gw._arl); - HttpResponseMessage response = await _client.SendAsync(request, cancelToken); + using HttpResponseMessage response = await _client.SendAsync(request, cancelToken); string resp = await response.Content.ReadAsStringAsync(cancelToken); JObject json = JObject.Parse(resp); @@ -482,7 +486,7 @@ private async Task ApplyMetadataToTagLibFile(TagLib.File track, long trackId, in } } } - catch (Exception) + catch (Exception e) when (e is not OperationCanceledException) { // MusicBrainz lookup is best-effort; don't fail the download if it doesn't work } diff --git a/DeezNET/GWApi.cs b/DeezNET/GWApi.cs index 93eb936..b32f6e7 100644 --- a/DeezNET/GWApi.cs +++ b/DeezNET/GWApi.cs @@ -174,13 +174,13 @@ internal async Task SetToken(CancellationToken token = default, bool force = fal public async Task AddSongToPlaylist(long playlistId, long trackId, int offset = -1, CancellationToken token = default) => await AddSongsToPlaylist(playlistId, [trackId], offset, token); - public async Task RemoveSongsFromPlaylist(long playlistId, long[] trackIds) => await Call("playlist.deleteSongs", new() + public async Task RemoveSongsFromPlaylist(long playlistId, long[] trackIds, CancellationToken token = default) => await Call("playlist.deleteSongs", new() { ["PLAYLIST_ID"] = playlistId, ["songs"] = new JArray(trackIds.Select(t => new JArray(t.ToString(), 0))), - }); + }, token: token); - public async Task RemoveSongFromPlaylist(long playlistId, long trackId, CancellationToken token = default) => await RemoveSongsFromPlaylist(playlistId, [trackId]); + public async Task RemoveSongFromPlaylist(long playlistId, long trackId, CancellationToken token = default) => await RemoveSongsFromPlaylist(playlistId, [trackId], token); public async Task DeletePlaylist(long playlistId, CancellationToken token = default) => await Call("playlist.delete", new() { @@ -303,7 +303,7 @@ private async Task Call(string method, JObject? args = null, Dictionary< if (needsArl) request.Headers.Add("Cookie", "arl=" + _arl); - HttpResponseMessage response = await _client.SendAsync(request, token); + using HttpResponseMessage response = await _client.SendAsync(request, token); string resp = await response.Content.ReadAsStringAsync(token); JObject json = JObject.Parse(resp); diff --git a/DeezNET/MusicBrainzLookup.cs b/DeezNET/MusicBrainzLookup.cs index bab2826..0fdd5ea 100644 --- a/DeezNET/MusicBrainzLookup.cs +++ b/DeezNET/MusicBrainzLookup.cs @@ -14,7 +14,8 @@ public class MusicBrainzLookup public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) { _client = client ?? new HttpClient(); - _userAgent = userAgent ?? "DeezNET/1.2.5 (https://github.com/jasonpatrickellykrause/DeezNET)"; + // from the assembly, so it can't drift from in Directory.Build.props + _userAgent = userAgent ?? $"DeezNET/{typeof(MusicBrainzLookup).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"} (https://github.com/jasonpatrickellykrause/DeezNET)"; } /// @@ -36,7 +37,7 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) try { - var response = await _client.SendAsync(request, token); + using var response = await _client.SendAsync(request, token); if (!response.IsSuccessStatusCode) { return null; @@ -75,7 +76,7 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) return null; } - catch + catch (Exception) when (!token.IsCancellationRequested) { return null; } @@ -95,7 +96,7 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) try { - var response = await _client.SendAsync(request, token); + using var response = await _client.SendAsync(request, token); if (!response.IsSuccessStatusCode) { return null; @@ -112,7 +113,7 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) return recordings[0].GetProperty("id").GetString(); } - catch + catch (Exception) when (!token.IsCancellationRequested) { return null; } @@ -174,7 +175,9 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) private static string EscapeSearch(string input) { - return input.Replace("\"", "\\\""); + // backslashes first, or the ones added for quotes would be escaped again; a trailing backslash would + // otherwise escape the closing quote of the phrase + return input.Replace("\\", "\\\\").Replace("\"", "\\\""); } } diff --git a/DeezNET/PublicApi.cs b/DeezNET/PublicApi.cs index f5e8974..07e564b 100644 --- a/DeezNET/PublicApi.cs +++ b/DeezNET/PublicApi.cs @@ -382,7 +382,7 @@ private async Task Call(string method, Dictionary? param string url = stringBuilder.ToString(); HttpRequestMessage request = new(HttpMethod.Get, url); - HttpResponseMessage response = await _client.SendAsync(request, token); + using HttpResponseMessage response = await _client.SendAsync(request, token); string resp = await response.Content.ReadAsStringAsync(token); JObject json = JObject.Parse(resp); diff --git a/README.md b/README.md index 780c6b3..cc06126 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,18 @@ The main differences from upstream: ## Changelog +### 1.2.6 +**Fixes** +- When the session expires during concurrent requests, the library refreshes the token once and the other requests reuse it. Before, each request refreshed it separately, sending a burst of `deezer.getUserData` calls at once. `SetARL` always refreshes, so a new ARL gets its own session. +- Downloading without an ARL throws `InvalidARLException` instead of a `NullReferenceException`. +- HTTP responses are disposed after use, which returns their connections to the pool sooner. +- `UnshortenURL` follows any redirect status, not only 302. +- Cancelling during the MusicBrainz lookup cancels the operation instead of being treated as a failed lookup. +- MusicBrainz searches escape backslashes in artist and album names. +- `ApplyMetadataToTrackStream` reads all four format bytes even when the stream returns them in parts, so it no longer misdetects a FLAC as an MP3. +- `RemoveSongsFromPlaylist` and `RemoveSongFromPlaylist` pass their cancellation token to the request. +- The MusicBrainz user agent takes its version from the assembly, so it no longer needs updating by hand. + ### 1.2.5 **Fixes** - `PublicApi` retries a quota error (codes 4 and 700) up to three times, then throws `APIException`. Before, it retried every 5 seconds with no limit, so a caller waited until Deezer stopped refusing.