Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions DeezNET.Tests/TokenRefreshTests.cs
Original file line number Diff line number Diff line change
@@ -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<HttpResponseMessage> 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) };
}
}
}
}
3 changes: 2 additions & 1 deletion DeezNET/Core.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
6 changes: 4 additions & 2 deletions DeezNET/DeezerURL.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
}

Expand Down
2 changes: 1 addition & 1 deletion DeezNET/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>1.2.5</Version>
<Version>1.2.6</Version>
<Company>TrevTV</Company>
<Copyright>Copyright (C) Trevor Jackson</Copyright>
<LangVersion>latest</LangVersion>
Expand Down
20 changes: 14 additions & 6 deletions DeezNET/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,12 @@ public async Task WriteRawTrackToFile(long trackId, string trackPath, Bitrate bi
/// <param name="token">Cancels the operation.</param>
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);
Expand Down Expand Up @@ -176,7 +180,7 @@ public async Task ApplyMetadataToFile(long trackId, string trackPath, int coverR
public async Task<(string plainLyrics, List<SyncLyrics>? 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)
{
Expand Down Expand Up @@ -287,9 +291,13 @@ private async Task<TrackUrls> 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 =
[
Expand Down Expand Up @@ -317,7 +325,7 @@ private async Task<TrackUrls> 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);
Expand All @@ -328,7 +336,7 @@ private async Task<TrackUrls> 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);
}

Expand Down Expand Up @@ -478,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
}
Expand Down
50 changes: 40 additions & 10 deletions DeezNET/GWApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/// <summary>
/// Refreshes the API token and user data.
/// </summary>
/// <param name="token">Cancels the operation.</param>
/// <param name="force">Refresh even if another caller already refreshed, such as after the ARL changes.</param>
/// <param name="staleVersion">The <see cref="TokenVersion"/> the caller's failed request used. Defaults to the current version.</param>
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<JToken> GetUserData(CancellationToken token = default) => await Call(USER_DATA_METHOD, needsArl: true, token: token);
Expand Down Expand Up @@ -146,13 +174,13 @@ internal async Task SetToken(CancellationToken token = default)

public async Task<JToken> AddSongToPlaylist(long playlistId, long trackId, int offset = -1, CancellationToken token = default) => await AddSongsToPlaylist(playlistId, [trackId], offset, token);

public async Task<JToken> RemoveSongsFromPlaylist(long playlistId, long[] trackIds) => await Call("playlist.deleteSongs", new()
public async Task<JToken> 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<JToken> RemoveSongFromPlaylist(long playlistId, long trackId, CancellationToken token = default) => await RemoveSongsFromPlaylist(playlistId, [trackId]);
public async Task<JToken> RemoveSongFromPlaylist(long playlistId, long trackId, CancellationToken token = default) => await RemoveSongsFromPlaylist(playlistId, [trackId], token);

public async Task<JToken> DeletePlaylist(long playlistId, CancellationToken token = default) => await Call("playlist.delete", new()
{
Expand Down Expand Up @@ -247,6 +275,7 @@ private async Task<JToken> 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";
Expand Down Expand Up @@ -274,7 +303,7 @@ private async Task<JToken> 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);
Expand All @@ -290,9 +319,10 @@ private async Task<JToken> 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);
}
Expand Down
15 changes: 9 additions & 6 deletions DeezNET/MusicBrainzLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <Version> in Directory.Build.props
_userAgent = userAgent ?? $"DeezNET/{typeof(MusicBrainzLookup).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"} (https://github.com/jasonpatrickellykrause/DeezNET)";
}

/// <summary>
Expand All @@ -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;
Expand Down Expand Up @@ -75,7 +76,7 @@ public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null)

return null;
}
catch
catch (Exception) when (!token.IsCancellationRequested)
{
return null;
}
Expand All @@ -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;
Expand All @@ -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;
}
Expand Down Expand Up @@ -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("\"", "\\\"");
}
}

Expand Down
2 changes: 1 addition & 1 deletion DeezNET/PublicApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ private async Task<JToken> Call(string method, Dictionary<string, string>? 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);
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down