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
39 changes: 39 additions & 0 deletions DeezNET.Tests/DecryptionTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text;
using DeezNET.Exceptions;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
Expand Down Expand Up @@ -120,6 +121,44 @@ public async Task DecodeTrackStreamAsyncShortReadTest()
outStream.ToArray().ShouldBe(track);
}

[Fact]
public async Task DecodeTrackStreamAsyncReturnsBytesReadTest()
{
// the encrypted input, which is what Content-Length counts, not the decoded output
byte[] encrypted = Encrypt(Track(6144 * 2 + 100), Key);
using ShortReadStream stream = new(encrypted);
using MemoryStream outStream = new();

long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5));

received.ShouldBe(encrypted.Length);
}

[Fact]
public async Task DecodeTrackStreamAsyncTruncatedBodyIsCaughtTest()
{
// a connection closed early looks like the end of the stream; only the length shows the track is short
byte[] encrypted = Encrypt(Track(6144 * 3), Key);
using MemoryStream stream = new(encrypted[..(6144 + 1000)]);
using MemoryStream outStream = new();

long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5));

Should.Throw<IncompleteTrackException>(() => Decryption.EnsureComplete(received, encrypted.Length, 42))
.Message.ShouldContain("ended after 7144 of 18432 bytes");
}

[Theory]
[InlineData(100, 100L)]
[InlineData(100, null)]
[InlineData(100, 0L)]
[InlineData(150, 100L)]
public void EnsureCompleteAllowsTest(long received, long? expected)
{
// a matching length, no Content-Length, or more than expected
Should.NotThrow(() => Decryption.EnsureComplete(received, expected, 42));
}

[Fact]
public async Task DecodeTrackStreamAsyncStallTimesOutTest()
{
Expand Down
22 changes: 21 additions & 1 deletion DeezNET/Decryption.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Org.BouncyCastle.Security;
using System.Security.Cryptography;
using System.Text;
using DeezNET.Exceptions;

namespace DeezNET;

Expand Down Expand Up @@ -37,19 +38,38 @@ public static void DecodeTrackStream(Stream input, Stream output, bool isCrypted
/// <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)
/// <returns>The number of bytes read from <paramref name="input"/>, to compare with the size the server reported.</returns>
public static async Task<long> DecodeTrackStreamAsync(Stream input, Stream output, bool isCrypted, string blowfishKey, TimeSpan? readTimeout = null, CancellationToken token = default)
{
bool isStart = true;
long totalRead = 0;

int bytesRead;
byte[] buffer = new byte[BLOCK_SIZE];
while ((bytesRead = await ReadBlockAsync(input, buffer, readTimeout, token)) > 0)
{
totalRead += bytesRead;

int offset = DecodeBlock(buffer, bytesRead, isCrypted, blowfishKey, isStart);
isStart = false;

await output.WriteAsync(buffer.AsMemory(offset, bytesRead - offset), token);
}

return totalRead;
}

/// <summary>
/// Throws when fewer bytes arrived than the server said it would send. A connection closed partway can end the body
/// like a normal finish, and a FLAC cut short still reports its full length in its header, so nothing else notices.
/// </summary>
/// <param name="received">The bytes read from the response body.</param>
/// <param name="expected">The response's Content-Length, or null when the server didn't send one.</param>
/// <param name="trackId">The track, for the error message.</param>
public static void EnsureComplete(long received, long? expected, long trackId)
{
if (expected is > 0 && received < expected)
throw new IncompleteTrackException($"Track ID {trackId} ended after {received} of {expected} bytes. The connection to the Deezer CDN closed early.");
}

// Decrypts the block in place and returns where its audio starts.
Expand Down
17 changes: 11 additions & 6 deletions DeezNET/Downloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,12 @@ public async Task<Stream> GetRawTrackStream(long trackId, Bitrate bitrate, Bitra
{
MemoryStream outStream = new();

var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token);
var (stream, blowfishKey, isCrypted, contentLength) = await GetEncryptedTrackData(trackId, bitrate, fallback, token);
using (stream)
await Decryption.DecodeTrackStreamAsync(stream, outStream, isCrypted, blowfishKey, ReadTimeout, token);
{
long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, isCrypted, blowfishKey, ReadTimeout, token);
Decryption.EnsureComplete(received, contentLength, trackId);
}

outStream.Seek(0, SeekOrigin.Begin);
return outStream;
Expand Down Expand Up @@ -74,12 +77,13 @@ public async Task<byte[]> GetRawTrackBytes(long trackId, Bitrate bitrate, Bitrat
public async Task WriteRawTrackToFile(long trackId, string trackPath, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default)
{
// fetch first so a failed request doesn't leave an empty file behind
var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token);
var (stream, blowfishKey, isCrypted, contentLength) = await GetEncryptedTrackData(trackId, bitrate, fallback, token);

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);
long received = await Decryption.DecodeTrackStreamAsync(stream, fileStream, isCrypted, blowfishKey, ReadTimeout, token);
Decryption.EnsureComplete(received, contentLength, trackId);
}
}

Expand Down Expand Up @@ -246,7 +250,7 @@ public static string GetCDNUrl(string id, int resolution)
return string.Format(CDN_TEMPLATE, id, resolution);
}

private async Task<(Stream stream, string blowfishKey, bool isCrypted)> GetEncryptedTrackData(long trackId, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default)
private async Task<(Stream stream, string blowfishKey, bool isCrypted, long? contentLength)> GetEncryptedTrackData(long trackId, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default)
{
JToken page = await _gw.GetTrackPage(trackId, token);
TrackUrls urls = await GetTrackUrl(page["DATA"]!["TRACK_TOKEN"]!.ToString(), bitrate, token);
Expand Down Expand Up @@ -282,7 +286,8 @@ public static string GetCDNUrl(string id, int resolution)
string blowfishKey = Decryption.GenerateBlowfishKey(trackId.ToString());
bool isCrypted = encryptedUri.ToString().Contains("/mobile/") || encryptedUri.ToString().Contains("/media/");

return (stream, blowfishKey, isCrypted);
// null when the CDN sends no Content-Length (a chunked response), which skips the completeness check
return (stream, blowfishKey, isCrypted, response.Content.Headers.ContentLength);
}

private async Task<TrackUrls> GetTrackUrl(string token, Bitrate bitrate, CancellationToken cancelToken = default, bool isRetry = false)
Expand Down
11 changes: 11 additions & 0 deletions DeezNET/Exceptions/IncompleteTrackException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace DeezNET.Exceptions;

/// <summary>
/// Thrown when a track's download ends before the size the Deezer CDN reported.
/// </summary>
public class IncompleteTrackException : Exception
{
public IncompleteTrackException() { }
public IncompleteTrackException(string message) : base(message) { }
public IncompleteTrackException(string message, Exception inner) : base(message, inner) { }
}