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
58 changes: 58 additions & 0 deletions DeezNET.Tests/DecryptionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TimeoutException>(() => 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<OperationCanceledException>(() => 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)
Expand Down Expand Up @@ -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<int> ReadAsync(Memory<byte> 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<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await Task.Delay(Timeout.Infinite, cancellationToken);
return 0;
}
}
}
}
32 changes: 32 additions & 0 deletions DeezNET.Tests/MetadataTests.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
}
94 changes: 79 additions & 15 deletions DeezNET/Decryption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
/// <summary>
/// Decodes a track stream without blocking, so a slow or stalled download can be cancelled.
/// </summary>
/// <param name="input">The encrypted track data.</param>
/// <param name="output">The stream to write the decoded track to.</param>
/// <param name="isCrypted">Whether the track data is encrypted.</param>
/// <param name="blowfishKey">The track's Blowfish key.</param>
/// <param name="readTimeout">The longest to wait for more data before giving up with a <see cref="TimeoutException"/>. Null waits indefinitely.</param>
/// <param name="token">Cancels the operation.</param>
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)
{
Expand All @@ -51,6 +84,37 @@ private static int ReadBlock(Stream input, byte[] buffer)
return total;
}

private static async Task<int> 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";
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.3</Version>
<Version>1.2.4</Version>
<Company>TrevTV</Company>
<Copyright>Copyright (C) Trevor Jackson</Copyright>
<LangVersion>latest</LangVersion>
Expand Down
79 changes: 65 additions & 14 deletions DeezNET/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();

/// <summary>
/// How long a track download can go without receiving data before it fails with a <see cref="TimeoutException"/>.
/// This limits stalls, not the length of the download. Null waits indefinitely.
/// </summary>
public TimeSpan? ReadTimeout { get; set; } = TimeSpan.FromSeconds(60);

/// <summary>
/// Downloads and decrypts track data for a given ID and bitrate.
/// </summary>
Expand All @@ -36,9 +42,8 @@ public async Task<Stream> 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;
Expand Down Expand Up @@ -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);
}
}

/// <summary>
Expand Down Expand Up @@ -192,12 +198,18 @@ public async Task ApplyMetadataToFile(long trackId, string trackPath, int coverR
/// <exception cref="UnavailableArtException">Occurs when the given art ID or resolution is unavailable.</exception>
public async Task<byte[]> 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);
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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<SyncLyrics> ParseSyncedLyrics(string syncedLyrics)
{
var lyrics = new List<SyncLyrics>();
Expand Down
2 changes: 1 addition & 1 deletion DeezNET/MusicBrainzLookup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)";
}

/// <summary>
Expand Down
Loading
Loading