diff --git a/DeezNET.Tests/DecryptionTests.cs b/DeezNET.Tests/DecryptionTests.cs index 386f4cc..0971717 100644 --- a/DeezNET.Tests/DecryptionTests.cs +++ b/DeezNET.Tests/DecryptionTests.cs @@ -94,6 +94,52 @@ public void DecodeTrackStreamShortReadTest() outStream.ToArray().ShouldBe(track); } + [Theory] + [InlineData(6144 * 2)] + [InlineData(6144 * 2 + 100)] + [InlineData(6144 + 3000)] + [InlineData(1000)] + public async Task DecodeTrackStreamAsyncRoundTripTest(int length) + { + byte[] track = Track(length); + using MemoryStream stream = new(Encrypt(track, Key)); + using MemoryStream outStream = new(); + await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5)); + + outStream.ToArray().ShouldBe(track); + } + + [Fact] + public async Task DecodeTrackStreamAsyncShortReadTest() + { + byte[] track = Track(6144 * 3 + 500); + using ShortReadStream stream = new(Encrypt(track, Key)); + using MemoryStream outStream = new(); + await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5)); + + outStream.ToArray().ShouldBe(track); + } + + [Fact] + public async Task DecodeTrackStreamAsyncStallTimesOutTest() + { + using StalledStream stream = new(); + using MemoryStream outStream = new(); + + await Should.ThrowAsync(() => Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromMilliseconds(200))); + } + + [Fact] + public async Task DecodeTrackStreamAsyncCancellationIsNotATimeoutTest() + { + using StalledStream stream = new(); + using MemoryStream outStream = new(); + using CancellationTokenSource cts = new(TimeSpan.FromMilliseconds(200)); + + // a TaskCanceledException is fine too; what matters is that it isn't reported as a timeout + await Assert.ThrowsAnyAsync(() => Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(30), cts.Token)); + } + private const string Key = "fii;ih'61)r4l36c"; private static byte[] Track(int length) @@ -125,6 +171,18 @@ private static byte[] Encrypt(byte[] track, string key) private sealed class ShortReadStream(byte[] data) : MemoryStream(data) { public override int Read(byte[] buffer, int offset, int count) => base.Read(buffer, offset, Math.Min(count, 1000)); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) => base.ReadAsync(buffer[..Math.Min(buffer.Length, 1000)], cancellationToken); + } + + // a connection that stays open but never sends anything + private sealed class StalledStream : MemoryStream + { + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + return 0; + } } } } \ No newline at end of file diff --git a/DeezNET.Tests/MetadataTests.cs b/DeezNET.Tests/MetadataTests.cs new file mode 100644 index 0000000..0386b6b --- /dev/null +++ b/DeezNET.Tests/MetadataTests.cs @@ -0,0 +1,32 @@ +using Newtonsoft.Json.Linq; +using Shouldly; + +namespace DeezNET.Tests +{ + public class MetadataTests + { + [Theory] + [InlineData("2021-06-04", 2021u)] + [InlineData("1999", 1999u)] + public void ParseYearReadsYear(string date, uint year) + { + Downloader.ParseYear(new JValue(date)).ShouldBe(year); + } + + [Theory] + [InlineData("0000-00-00")] + [InlineData("")] + [InlineData("n/a")] + [InlineData("-123-01-01")] + public void ParseYearTreatsInvalidDatesAsMissing(string date) + { + Downloader.ParseYear(new JValue(date)).ShouldBeNull(); + } + + [Fact] + public void ParseYearTreatsMissingDateAsMissing() + { + Downloader.ParseYear(null).ShouldBeNull(); + } + } +} diff --git a/DeezNET/Decryption.cs b/DeezNET/Decryption.cs index 86f1da8..9310f85 100644 --- a/DeezNET/Decryption.cs +++ b/DeezNET/Decryption.cs @@ -10,36 +10,69 @@ namespace DeezNET; internal static class Decryption { + private const int BLOCK_SIZE = 2048 * 3; + public static void DecodeTrackStream(Stream input, Stream output, bool isCrypted, string blowfishKey) { bool isStart = true; int bytesRead; - byte[] buffer = new byte[2048 * 3]; + byte[] buffer = new byte[BLOCK_SIZE]; while ((bytesRead = ReadBlock(input, buffer)) > 0) { - if (isCrypted && bytesRead >= 2048) - { - DecryptChunk(blowfishKey, buffer.AsSpan(0, 2048)).CopyTo(buffer, 0); - } + int offset = DecodeBlock(buffer, bytesRead, isCrypted, blowfishKey, isStart); + isStart = false; - int offset = 0; - if (isStart && bytesRead >= 8 && buffer[0] == 0 && !Encoding.UTF8.GetString(buffer, 4, 4).Equals("ftyp")) - { - while (offset < bytesRead && buffer[offset] == 0) - offset++; + // Only the bytes read this pass; the rest of the buffer still holds the previous block. + output.Write(buffer, offset, bytesRead - offset); + } + } - if (offset == bytesRead) - offset = 0; - } + /// + /// Decodes a track stream without blocking, so a slow or stalled download can be cancelled. + /// + /// The encrypted track data. + /// The stream to write the decoded track to. + /// Whether the track data is encrypted. + /// The track's Blowfish key. + /// The longest to wait for more data before giving up with a . Null waits indefinitely. + /// Cancels the operation. + public static async Task DecodeTrackStreamAsync(Stream input, Stream output, bool isCrypted, string blowfishKey, TimeSpan? readTimeout = null, CancellationToken token = default) + { + bool isStart = true; + int bytesRead; + byte[] buffer = new byte[BLOCK_SIZE]; + while ((bytesRead = await ReadBlockAsync(input, buffer, readTimeout, token)) > 0) + { + int offset = DecodeBlock(buffer, bytesRead, isCrypted, blowfishKey, isStart); isStart = false; - // Only the bytes read this pass; the rest of the buffer still holds the previous block. - output.Write(buffer, offset, bytesRead - offset); + await output.WriteAsync(buffer.AsMemory(offset, bytesRead - offset), token); } } + // Decrypts the block in place and returns where its audio starts. + private static int DecodeBlock(byte[] buffer, int bytesRead, bool isCrypted, string blowfishKey, bool isStart) + { + if (isCrypted && bytesRead >= 2048) + { + DecryptChunk(blowfishKey, buffer.AsSpan(0, 2048)).CopyTo(buffer, 0); + } + + int offset = 0; + if (isStart && bytesRead >= 8 && buffer[0] == 0 && !Encoding.UTF8.GetString(buffer, 4, 4).Equals("ftyp")) + { + while (offset < bytesRead && buffer[offset] == 0) + offset++; + + if (offset == bytesRead) + offset = 0; + } + + return offset; + } + // Fills the buffer unless the stream ends, so every block keeps the 6144-byte stripe alignment. private static int ReadBlock(Stream input, byte[] buffer) { @@ -51,6 +84,37 @@ private static int ReadBlock(Stream input, byte[] buffer) return total; } + private static async Task ReadBlockAsync(Stream input, byte[] buffer, TimeSpan? readTimeout, CancellationToken token) + { + using CancellationTokenSource readCts = CancellationTokenSource.CreateLinkedTokenSource(token); + + int total = 0; + while (total < buffer.Length) + { + // restarted for every read, so it limits how long the connection can stall, not how long the whole track takes + if (readTimeout != null) + readCts.CancelAfter(readTimeout.Value); + + int read; + try + { + read = await input.ReadAsync(buffer.AsMemory(total, buffer.Length - total), readCts.Token); + } + catch (OperationCanceledException) when (!token.IsCancellationRequested) + { + // a timeout rather than a cancellation, so callers that ignore cancellations still see a failure + throw new TimeoutException($"No data was received for {readTimeout!.Value.TotalSeconds} seconds."); + } + + if (read == 0) + break; + + total += read; + } + + return total; + } + public static string GenerateBlowfishKey(string trackId) { const string SECRET = "g4el58wc0zvf9na1"; diff --git a/DeezNET/Directory.Build.props b/DeezNET/Directory.Build.props index ebb380c..9a6f9f9 100644 --- a/DeezNET/Directory.Build.props +++ b/DeezNET/Directory.Build.props @@ -1,6 +1,6 @@  - 1.2.3 + 1.2.4 TrevTV Copyright (C) Trevor Jackson latest diff --git a/DeezNET/Downloader.cs b/DeezNET/Downloader.cs index ae90c82..6ddc58a 100644 --- a/DeezNET/Downloader.cs +++ b/DeezNET/Downloader.cs @@ -23,6 +23,12 @@ internal Downloader(HttpClient client, GWApi gw, PublicApi publicApi) internal const string CDN_TEMPLATE = "https://e-cdn-images.dzcdn.net/images/cover/{0}/{1}x{1}-000000-80-0-0.jpg"; private readonly byte[] FLAC_MAGIC = "fLaC"u8.ToArray(); + /// + /// How long a track download can go without receiving data before it fails with a . + /// This limits stalls, not the length of the download. Null waits indefinitely. + /// + public TimeSpan? ReadTimeout { get; set; } = TimeSpan.FromSeconds(60); + /// /// Downloads and decrypts track data for a given ID and bitrate. /// @@ -36,9 +42,8 @@ public async Task GetRawTrackStream(long trackId, Bitrate bitrate, Bitra MemoryStream outStream = new(); var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); - Decryption.DecodeTrackStream(stream, outStream, isCrypted, blowfishKey); - - stream.Dispose(); + using (stream) + await Decryption.DecodeTrackStreamAsync(stream, outStream, isCrypted, blowfishKey, ReadTimeout, token); outStream.Seek(0, SeekOrigin.Begin); return outStream; @@ -71,10 +76,11 @@ public async Task WriteRawTrackToFile(long trackId, string trackPath, Bitrate bi // fetch first so a failed request doesn't leave an empty file behind var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); - using FileStream fileStream = File.Open(trackPath, FileMode.Create); - Decryption.DecodeTrackStream(stream, fileStream, isCrypted, blowfishKey); - - stream.Dispose(); + using (stream) + { + using FileStream fileStream = new(trackPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); + await Decryption.DecodeTrackStreamAsync(stream, fileStream, isCrypted, blowfishKey, ReadTimeout, token); + } } /// @@ -192,12 +198,18 @@ public async Task ApplyMetadataToFile(long trackId, string trackPath, int coverR /// Occurs when the given art ID or resolution is unavailable. public async Task GetArtBytes(string id, int resolution, CancellationToken token = default) { + // tracks without art have an empty picture ID, which would request a malformed CDN path + if (string.IsNullOrWhiteSpace(id)) + throw new UnavailableArtException("No art ID was provided."); + HttpRequestMessage message = new(HttpMethod.Get, GetCDNUrl(id, resolution)); - HttpResponseMessage response = await _client.SendAsync(message, token); + using HttpResponseMessage response = await _client.SendAsync(message, token); - if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) + // the CDN answers a missing size with 401 or 403 and other failures with an error page; any of those would + // otherwise be embedded in the track as its cover + if (!response.IsSuccessStatusCode) { - throw new UnavailableArtException($"The art with {id} with resolution {resolution} is unavailable."); + throw new UnavailableArtException($"The art with {id} with resolution {resolution} is unavailable. The CDN returned {(int)response.StatusCode} {response.ReasonPhrase}."); } return await response.Content.ReadAsByteArrayAsync(token); @@ -248,8 +260,11 @@ public static string GetCDNUrl(string id, int resolution) throw new NoSourcesAvailableException($"Track ID {trackId} has no available media sources for bitrate {bitrate}.{reason}"); } + // stream the body instead of buffering it; with the default option HttpClient.Timeout (100 seconds) covers the + // whole download, so large FLACs on slow connections time out, and the track is held in memory twice. + // Stalls are caught by ReadTimeout while decoding instead. HttpRequestMessage message = new(HttpMethod.Get, encryptedUri); - HttpResponseMessage response = await _client.SendAsync(message, token); + HttpResponseMessage response = await _client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token); // an error page from the CDN would otherwise be "decrypted" and saved as audio if (!response.IsSuccessStatusCode) @@ -337,10 +352,31 @@ private async Task ApplyMetadataToTagLibFile(TagLib.File track, long trackId, in track.Tag.Album = page["DATA"]!["ALB_TITLE"]!.ToString(); track.Tag.Performers = page["DATA"]!["ARTISTS"]!.Select(a => a["ART_NAME"]!.ToString()).ToArray(); track.Tag.AlbumArtists = albumPage["DATA"]!["ARTISTS"]!.Select(a => a["ART_NAME"]!.ToString()).ToArray(); - DateTime releaseDate = DateTime.Parse(page["DATA"]!["PHYSICAL_RELEASE_DATE"]!.ToString()); - track.Tag.Year = (uint)releaseDate.Year; + // deezer sends 0000-00-00 for some releases; skip the year rather than fail the whole tag write + uint? year = ParseYear(page["DATA"]?["PHYSICAL_RELEASE_DATE"]) + ?? ParseYear(albumPage["DATA"]?["PHYSICAL_RELEASE_DATE"]) + ?? ParseYear(albumPage["DATA"]?["ORIGINAL_RELEASE_DATE"]); + if (year != null) + track.Tag.Year = year.Value; + + // TRACK_NUMBER restarts on each disc, so without the disc number tracks on different discs get identical tags track.Tag.Track = uint.Parse(page["DATA"]!["TRACK_NUMBER"]!.ToString()); - track.Tag.TrackCount = uint.Parse(albumPage["SONGS"]!["total"]!.ToString()); + uint disc = ParsePositive(page["DATA"]?["DISK_NUMBER"]) ?? 1; + track.Tag.Disc = disc; + + uint albumTrackCount = uint.Parse(albumPage["SONGS"]!["total"]!.ToString()); + uint[]? songDiscs = (albumPage["SONGS"]?["data"] as JArray)?.Select(s => ParsePositive(s["DISK_NUMBER"]) ?? 1).ToArray(); + uint discTrackCount = songDiscs != null && songDiscs.Length == albumTrackCount ? (uint)songDiscs.Count(d => d == disc) : 0; + if (discTrackCount > 0) + { + track.Tag.TrackCount = discTrackCount; + track.Tag.DiscCount = songDiscs!.Max(); + } + else + { + // the song list is incomplete or has no disc numbers, so per-disc counts can't be trusted; keep the album total + track.Tag.TrackCount = albumTrackCount; + } // i have yet to find an album without a genre attached, but this may still break at some point track.Tag.Genres = publicAlbum["genres"]!["data"]!.Select(a => a["name"]!.ToString()).ToArray(); @@ -442,6 +478,21 @@ private async Task ApplyMetadataToTagLibFile(TagLib.File track, long trackId, in track.Save(); } + // reads the year from a yyyy-MM-dd date, treating 0000 and anything unparseable as missing + internal static uint? ParseYear(JToken? date) + { + string? value = date?.ToString(); + if (value == null || value.Length < 4) + return null; + + return uint.TryParse(value.AsSpan(0, 4), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out uint year) && year > 0 ? year : null; + } + + private static uint? ParsePositive(JToken? number) + { + return uint.TryParse(number?.ToString(), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out uint value) && value > 0 ? value : null; + } + private List ParseSyncedLyrics(string syncedLyrics) { var lyrics = new List(); diff --git a/DeezNET/MusicBrainzLookup.cs b/DeezNET/MusicBrainzLookup.cs index 9c3c746..b0a27eb 100644 --- a/DeezNET/MusicBrainzLookup.cs +++ b/DeezNET/MusicBrainzLookup.cs @@ -14,7 +14,7 @@ public class MusicBrainzLookup public MusicBrainzLookup(HttpClient? client = null, string? userAgent = null) { _client = client ?? new HttpClient(); - _userAgent = userAgent ?? "DeezNET/1.2.3 (https://github.com/jasonpatrickellykrause/DeezNET)"; + _userAgent = userAgent ?? "DeezNET/1.2.4 (https://github.com/jasonpatrickellykrause/DeezNET)"; } /// diff --git a/README.md b/README.md index 57f5201..db43852 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,22 @@ The main differences from upstream: ## Changelog +### 1.2.4 +**Fixes** +- Track downloads stream from the CDN instead of loading the whole file before decrypting it. Before, `HttpClient`'s 100-second timeout covered the entire download, so large FLACs on slow connections failed, and `GetRawTrackStream` held the track in memory twice. A stalled connection now fails with `TimeoutException` after `Downloader.ReadTimeout` (60 seconds by default) without data. +- `GetArtBytes` throws `UnavailableArtException` for any unsuccessful CDN response and for an empty art ID. Before, only a 401 threw, and other error pages were embedded in tracks as cover art. +- A release date of `0000-00-00` no longer stops a track from being tagged. The year falls back to the album's release dates, and is left out if none are valid. +- Tracks are tagged with their disc number. On multi-disc albums, the track count and disc count are per disc when Deezer returns the full track list. Before, tracks with the same number on different discs got identical tags. + +**New** +- `Decryption.DecodeTrackStreamAsync` decodes without blocking and supports cancellation and a read timeout. + +**Maintenance** +- Pull requests and pushes to `main` build the solution and run the tests. Tests tagged `Live` call Deezer and only run locally. +- CodeQL scans the C# code and the workflows on every pull request and weekly. +- Pull requests fail if they add a dependency with a high or critical advisory. +- Dependabot also updates the pinned GitHub Actions, and groups test package updates into one pull request. + ### 1.2.3 **Fixes** - `DecodeTrackStream` wrote the whole 6144-byte buffer on every pass, so most tracks ended with up to 6143 stale bytes. It now writes only the bytes it read and keeps the stripe alignment when the stream returns short reads. From [TrevTV/DeezNET#4](https://github.com/TrevTV/DeezNET/pull/4).