Skip to content

Commit

Permalink
Use StreamResult instead SongStream
Browse files Browse the repository at this point in the history
  • Loading branch information
geloczi committed Dec 19, 2021
1 parent 998d5cb commit 9365402
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ public static void ClassInitialize(TestContext context)
{
// Connect to the server and login
AudioStation = new AudioStationClient();
SynoClient = new SynoClient(new Uri(CoreConfig.Server), true, AudioStation);
SynoClient = new SynoClient(new Uri(CoreConfig.Server), true)
.Add(AudioStation);
var session = SynoClient.LoginAsync(CoreConfig.Username, CoreConfig.Password/*, SessionName*/).Result;

Assert.IsNotNull(session);
Expand Down Expand Up @@ -300,15 +301,15 @@ private void TestStreamSongInternal(TranscodeMode transcodeMode, string mediaTyp
transcodeMode,
TestSong.ID,
0,
songStream =>
streamArgs =>
{
if (!string.IsNullOrEmpty(mediaType))
Assert.AreEqual(songStream.ContentType, mediaType);
Assert.IsTrue(songStream.ContentLength > 0);
Assert.AreEqual(streamArgs.ContentType, mediaType);
Assert.IsTrue(streamArgs.ContentLength > 0);

// Read 4KB just to test the download
var buffer = new byte[4096];
songStream.Stream.Read(buffer, 0, buffer.Length);
streamArgs.Stream.Read(buffer, 0, buffer.Length);
// There must be at least one non-zero byte in a 4KB chunk
Assert.IsTrue(buffer.Any(b => b > 0));
}
Expand Down
62 changes: 14 additions & 48 deletions SynologyDotNet.AudioStation/AudioStationClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
Expand All @@ -18,6 +17,16 @@ namespace SynologyDotNet.AudioStation
/// </summary>
public sealed class AudioStationClient : StationConnectorBase
{
#region Fields

/// <summary>
/// This exists only if the AudioStation package has been installed.
/// This endpoint is used to edit song metadata prgorammatically.
/// </summary>
private const string TagEditorEndpoint = "webman/3rdparty/AudioStation/tagEditorUI/tag_editor.cgi";

#endregion Fields

#region Apis

const string SYNO_AudioStation_Info = "SYNO.AudioStation.Info";
Expand Down Expand Up @@ -225,48 +234,10 @@ public async Task StreamSongAsync(
TranscodeMode transcode,
string songId,
double positionSeconds,
Action<SongStream> readStreamAction)
Action<StreamResult> readStreamAction)
{
var req = CreateSongStreamRequest(SYNO_AudioStation_Stream, transcode, songId, positionSeconds);
using (var response = await Client.HttpClient.SendAsync(req.ToPostRequest(), HttpCompletionOption.ResponseHeadersRead, cancellationToken))
{
if (!response.IsSuccessStatusCode)
throw new Exception($"Cannot open the specified song. HTTP {(int)response.StatusCode}");
if (response.Content is null)
throw new NullReferenceException("No content.");
if (cancellationToken.IsCancellationRequested)
throw new OperationCanceledException();
long contentLength;
string contentType;

// DSM 6 compatibility
if (response.Content is StreamContent streamContent)
{
contentType = streamContent.Headers.ContentType.MediaType;
contentLength = streamContent.Headers.ContentLength.Value;
}
// DSM 7 compatibility
else if (response.Content.Headers.TryGetValues("Content-Type", out var contentTypeValues)
&& contentTypeValues.Any()
&& response.Content.Headers.TryGetValues("Content-Length", out var contentLengthValues)
&& contentLengthValues.Any()
&& long.TryParse(contentLengthValues.First(), out contentLength))
{
contentType = contentTypeValues.First();
}
// Not supported
else
{
throw new NotSupportedException($"Content not supported: {response.Content.GetType().FullName}");
}

using (var responseStream = await response.Content.ReadAsStreamAsync())
{
if (cancellationToken.IsCancellationRequested)
throw new OperationCanceledException();
readStreamAction(new SongStream(responseStream, contentType, contentLength, cancellationToken));
}
}
await Client.QueryStreamAsync(req, readStreamAction, cancellationToken);
}

#endregion
Expand All @@ -290,11 +261,6 @@ public async Task StreamSongAsync(

#region Tags

/// <summary>
/// This exists only if the AudioStation package has been installed, and the Application Portal 'audio' is enabled too.
/// </summary>
private const string tag_editor_cgi_endpoint = "webman/3rdparty/AudioStation/tagEditorUI/tag_editor.cgi";

/// <summary>
/// Query song tags
/// </summary>
Expand All @@ -306,7 +272,7 @@ public async Task<FileTags> GetSongFileTags(params string[] paths)
throw new ArgumentNullException(nameof(paths));
if (paths.Any(p => p.Contains("\\")))
throw new ArgumentException("Invalid path. Path must contain forward slashes '/', not back-slashes '\\'");
var req = new RequestBuilder().SetEndpoint(tag_editor_cgi_endpoint).Action("load");
var req = new RequestBuilder().SetEndpoint(TagEditorEndpoint).Action("load");
req["audioInfos"] = JsonConvert.SerializeObject(paths.Select(p => new { path = p }));
req["requestFrom"] = string.Empty;
var result = await Client.QueryObjectAsync<FileTags>(req);
Expand All @@ -323,7 +289,7 @@ public async Task<ApiResponse> SetSongFileTags(FileTagChange change)
if (change?.AudioInfos?.Any() != true)
throw new ArgumentNullException($"{nameof(change)}.{nameof(change.AudioInfos)}");

var req = new RequestBuilder().SetEndpoint(tag_editor_cgi_endpoint).Action("apply");
var req = new RequestBuilder().SetEndpoint(TagEditorEndpoint).Action("apply");
req["data"] = JsonConvert.SerializeObject(new object[] { change });
var result = await Client.QueryObjectAsync<ApiResponse>(req);
return result;
Expand Down
30 changes: 0 additions & 30 deletions SynologyDotNet.AudioStation/SongStream.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<!-- General -->
<PropertyGroup>
<Product>SynologyDotNet.AudioStation</Product>
<Version>0.4.0</Version>
<Version>0.4.1</Version>
<Description>SynologyDotNet.AudioStation</Description>
<RepositoryUrl>https://github.com/geloczigeri/synologydotnet-audiostation</RepositoryUrl>
<Authors>Gergő Gelóczi</Authors>
Expand Down Expand Up @@ -58,7 +58,7 @@
</When>
<Otherwise>
<ItemGroup>
<PackageReference Include="SynologyDotNet.Core" Version="0.4.0" />
<PackageReference Include="SynologyDotNet.Core" Version="0.4.1" />
</ItemGroup>
</Otherwise>
</Choose>
Expand Down

0 comments on commit 9365402

Please sign in to comment.