mirror of
https://github.com/SoPat712/allstarr.git
synced 2026-04-27 03:53:10 -04:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
639070556a
|
|||
|
00a5d152a5
|
|||
|
1ba6135115
|
|||
|
ec994773dd
|
|||
|
39c8f16b59
|
|||
|
a6a423d5a1
|
|||
|
899451d405
|
|||
|
8d6dd7ccf1
|
|||
|
ebdd8d4e2a
|
|||
|
e4599a419e
|
|||
|
86290dff0d
|
|||
|
0a9e528418
|
|||
|
f74728fc73
|
|||
|
87467be61b
|
|||
|
713ecd4ec8
|
|||
|
0ff1e3a428
|
|||
|
cef18b9482
|
|||
|
1bfe30b216
|
|||
|
c9c82a650d
|
|||
|
d0a7dbcc96
|
|||
|
9c9a827a91
|
|||
|
96889738df
|
|||
|
f3c791496e
|
+2
-2
@@ -40,8 +40,8 @@ REDIS_DATA_PATH=./redis-data
|
|||||||
# All values are configurable via Web UI (Configuration tab > Cache Settings)
|
# All values are configurable via Web UI (Configuration tab > Cache Settings)
|
||||||
# Changes require container restart to apply
|
# Changes require container restart to apply
|
||||||
|
|
||||||
# Search results cache duration in minutes (default: 1)
|
# Search results cache duration in minutes (default: 120 = 2 hours)
|
||||||
CACHE_SEARCH_RESULTS_MINUTES=1
|
CACHE_SEARCH_RESULTS_MINUTES=120
|
||||||
|
|
||||||
# Playlist cover images cache duration in hours (default: 168 = 1 week)
|
# Playlist cover images cache duration in hours (default: 168 = 1 week)
|
||||||
CACHE_PLAYLIST_IMAGES_HOURS=168
|
CACHE_PLAYLIST_IMAGES_HOURS=168
|
||||||
|
|||||||
@@ -39,22 +39,6 @@ public class AuthHeaderHelperTests
|
|||||||
Assert.True(request.Headers.Contains("X-Emby-Authorization"));
|
Assert.True(request.Headers.Contains("X-Emby-Authorization"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ForwardAuthHeaders_ShouldForwardXEmbyToken()
|
|
||||||
{
|
|
||||||
var headers = new HeaderDictionary
|
|
||||||
{
|
|
||||||
["X-Emby-Token"] = "abc"
|
|
||||||
};
|
|
||||||
|
|
||||||
using var request = new HttpRequestMessage();
|
|
||||||
var forwarded = AuthHeaderHelper.ForwardAuthHeaders(headers, request);
|
|
||||||
|
|
||||||
Assert.True(forwarded);
|
|
||||||
Assert.True(request.Headers.TryGetValues("X-Emby-Token", out var values));
|
|
||||||
Assert.Contains("abc", values);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ForwardAuthHeaders_ShouldForwardStandardAuthorization()
|
public void ForwardAuthHeaders_ShouldForwardStandardAuthorization()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using allstarr.Middleware;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
|
||||||
|
|
||||||
namespace allstarr.Tests;
|
|
||||||
|
|
||||||
public class BotProbeBlockMiddlewareTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task InvokeAsync_ScannerPath_Returns404WithoutCallingNext()
|
|
||||||
{
|
|
||||||
var nextInvoked = false;
|
|
||||||
var middleware = new BotProbeBlockMiddleware(
|
|
||||||
_ =>
|
|
||||||
{
|
|
||||||
nextInvoked = true;
|
|
||||||
return Task.CompletedTask;
|
|
||||||
},
|
|
||||||
NullLogger<BotProbeBlockMiddleware>.Instance);
|
|
||||||
|
|
||||||
var context = CreateContext("/.env");
|
|
||||||
|
|
||||||
await middleware.InvokeAsync(context);
|
|
||||||
|
|
||||||
Assert.False(nextInvoked);
|
|
||||||
Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task InvokeAsync_NormalPath_CallsNext()
|
|
||||||
{
|
|
||||||
var nextInvoked = false;
|
|
||||||
var middleware = new BotProbeBlockMiddleware(
|
|
||||||
context =>
|
|
||||||
{
|
|
||||||
nextInvoked = true;
|
|
||||||
context.Response.StatusCode = StatusCodes.Status204NoContent;
|
|
||||||
return Task.CompletedTask;
|
|
||||||
},
|
|
||||||
NullLogger<BotProbeBlockMiddleware>.Instance);
|
|
||||||
|
|
||||||
var context = CreateContext("/System/Info/Public");
|
|
||||||
|
|
||||||
await middleware.InvokeAsync(context);
|
|
||||||
|
|
||||||
Assert.True(nextInvoked);
|
|
||||||
Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static DefaultHttpContext CreateContext(string path)
|
|
||||||
{
|
|
||||||
var context = new DefaultHttpContext();
|
|
||||||
context.Request.Path = path;
|
|
||||||
context.Request.Method = HttpMethods.Get;
|
|
||||||
context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.10");
|
|
||||||
context.Response.Body = new MemoryStream();
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
using allstarr.Services.Common;
|
|
||||||
|
|
||||||
namespace allstarr.Tests;
|
|
||||||
|
|
||||||
public class BotProbeDetectorTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("/.env")]
|
|
||||||
[InlineData("/.git/config")]
|
|
||||||
[InlineData("/wordpress")]
|
|
||||||
[InlineData("/wp")]
|
|
||||||
[InlineData("/wp-admin/install.php")]
|
|
||||||
[InlineData("/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php")]
|
|
||||||
[InlineData("/public/vendor/laravel-filemanager/js/script.js")]
|
|
||||||
[InlineData("/_ignition/execute-solution")]
|
|
||||||
[InlineData("/debug/default/index")]
|
|
||||||
[InlineData("https://jellyfin.joshpatra.me/.git/config")]
|
|
||||||
public void IsHighConfidenceProbeUrl_ScannerPaths_ReturnsTrue(string path)
|
|
||||||
{
|
|
||||||
Assert.True(BotProbeDetector.IsHighConfidenceProbeUrl(path));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("/System/Info/Public")]
|
|
||||||
[InlineData("/web/index.html")]
|
|
||||||
[InlineData("/Items/123")]
|
|
||||||
[InlineData("/Users/AuthenticateByName")]
|
|
||||||
[InlineData("/new")]
|
|
||||||
[InlineData("/blog")]
|
|
||||||
public void IsHighConfidenceProbeUrl_NormalProxyPaths_ReturnsFalse(string path)
|
|
||||||
{
|
|
||||||
Assert.False(BotProbeDetector.IsHighConfidenceProbeUrl(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -20,42 +20,10 @@ public class CacheKeyBuilderTests
|
|||||||
"1635cd7d23144ba08251ebe22a56119e");
|
"1635cd7d23144ba08251ebe22a56119e");
|
||||||
|
|
||||||
Assert.Equal(
|
Assert.Equal(
|
||||||
"search:data:musicalbum:500:0:efa26829c37196b030fa31d127e0715b:datecreated,sortname:descending:true:1635cd7d23144ba08251ebe22a56119e:",
|
"search:data:musicalbum:500:0:efa26829c37196b030fa31d127e0715b:datecreated,sortname:descending:true:1635cd7d23144ba08251ebe22a56119e",
|
||||||
key);
|
key);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void SearchKey_ShouldDifferentiateFavoriteOnlyQueries()
|
|
||||||
{
|
|
||||||
var normalKey = CacheKeyBuilder.BuildSearchKey(
|
|
||||||
"Sunflower",
|
|
||||||
"Audio",
|
|
||||||
100,
|
|
||||||
0,
|
|
||||||
"parent",
|
|
||||||
"SortName",
|
|
||||||
"Ascending",
|
|
||||||
true,
|
|
||||||
"user-1",
|
|
||||||
"false");
|
|
||||||
|
|
||||||
var favoritesOnlyKey = CacheKeyBuilder.BuildSearchKey(
|
|
||||||
"Sunflower",
|
|
||||||
"Audio",
|
|
||||||
100,
|
|
||||||
0,
|
|
||||||
"parent",
|
|
||||||
"SortName",
|
|
||||||
"Ascending",
|
|
||||||
true,
|
|
||||||
"user-1",
|
|
||||||
"true");
|
|
||||||
|
|
||||||
Assert.NotEqual(normalKey, favoritesOnlyKey);
|
|
||||||
Assert.EndsWith(":false", normalKey);
|
|
||||||
Assert.EndsWith(":true", favoritesOnlyKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void SearchKey_OldOverload_ShouldRemainCompatible()
|
public void SearchKey_OldOverload_ShouldRemainCompatible()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -117,35 +117,6 @@ public class JellyfinProxyServiceTests
|
|||||||
Assert.False(captured.Headers.Contains("X-Emby-Authorization"));
|
Assert.False(captured.Headers.Contains("X-Emby-Authorization"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetJsonAsync_WithXEmbyToken_ForwardsTokenHeader()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
HttpRequestMessage? captured = null;
|
|
||||||
_mockHandler.Protected()
|
|
||||||
.Setup<Task<HttpResponseMessage>>("SendAsync",
|
|
||||||
ItExpr.IsAny<HttpRequestMessage>(),
|
|
||||||
ItExpr.IsAny<CancellationToken>())
|
|
||||||
.Callback<HttpRequestMessage, CancellationToken>((req, ct) => captured = req)
|
|
||||||
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("{}")
|
|
||||||
});
|
|
||||||
|
|
||||||
var headers = new HeaderDictionary
|
|
||||||
{
|
|
||||||
["X-Emby-Token"] = "token-123"
|
|
||||||
};
|
|
||||||
|
|
||||||
// Act
|
|
||||||
await _service.GetJsonAsync("Items", null, headers);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.NotNull(captured);
|
|
||||||
Assert.True(captured!.Headers.TryGetValues("X-Emby-Token", out var values));
|
|
||||||
Assert.Contains("token-123", values);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetBytesAsync_ReturnsBodyAndContentType()
|
public async Task GetBytesAsync_ReturnsBodyAndContentType()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -75,44 +75,6 @@ public class JellyfinResponseBuilderTests
|
|||||||
Assert.Equal("USRC12345678", providerIds["ISRC"]);
|
Assert.Equal("USRC12345678", providerIds["ISRC"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ConvertSongToJellyfinItem_ExternalExplicitSong_AppendsStreamingAndExplicitLabels()
|
|
||||||
{
|
|
||||||
var song = new Song
|
|
||||||
{
|
|
||||||
Id = "ext-squidwtf-song-12345",
|
|
||||||
Title = "Sunflower",
|
|
||||||
Artist = "Artist",
|
|
||||||
IsLocal = false,
|
|
||||||
ExternalProvider = "squidwtf",
|
|
||||||
ExternalId = "12345",
|
|
||||||
ExplicitContentLyrics = 1
|
|
||||||
};
|
|
||||||
|
|
||||||
var result = _builder.ConvertSongToJellyfinItem(song);
|
|
||||||
|
|
||||||
Assert.Equal("Sunflower [S] [E]", result["Name"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ConvertSongToJellyfinItem_ExternalCleanSong_AppendsOnlyStreamingLabel()
|
|
||||||
{
|
|
||||||
var song = new Song
|
|
||||||
{
|
|
||||||
Id = "ext-squidwtf-song-12345",
|
|
||||||
Title = "Sunflower",
|
|
||||||
Artist = "Artist",
|
|
||||||
IsLocal = false,
|
|
||||||
ExternalProvider = "squidwtf",
|
|
||||||
ExternalId = "12345",
|
|
||||||
ExplicitContentLyrics = 0
|
|
||||||
};
|
|
||||||
|
|
||||||
var result = _builder.ConvertSongToJellyfinItem(song);
|
|
||||||
|
|
||||||
Assert.Equal("Sunflower [S]", result["Name"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("deezer")]
|
[InlineData("deezer")]
|
||||||
[InlineData("qobuz")]
|
[InlineData("qobuz")]
|
||||||
|
|||||||
@@ -1,145 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Net;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using allstarr.Models.Settings;
|
|
||||||
using allstarr.Services.Common;
|
|
||||||
using allstarr.Services.Jellyfin;
|
|
||||||
|
|
||||||
namespace allstarr.Tests;
|
|
||||||
|
|
||||||
public class JellyfinSessionManagerTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task MarkSessionPotentiallyEnded_DoesNotAutoRemoveSession()
|
|
||||||
{
|
|
||||||
var handler = new DelegateHttpMessageHandler((_, _) =>
|
|
||||||
Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent)));
|
|
||||||
|
|
||||||
var settings = new JellyfinSettings
|
|
||||||
{
|
|
||||||
Url = "http://127.0.0.1:1",
|
|
||||||
ApiKey = "server-api-key",
|
|
||||||
ClientName = "Allstarr",
|
|
||||||
DeviceName = "Allstarr",
|
|
||||||
DeviceId = "allstarr",
|
|
||||||
ClientVersion = "1.0"
|
|
||||||
};
|
|
||||||
|
|
||||||
var proxyService = CreateProxyService(handler, settings);
|
|
||||||
using var manager = new JellyfinSessionManager(
|
|
||||||
proxyService,
|
|
||||||
Options.Create(settings),
|
|
||||||
NullLogger<JellyfinSessionManager>.Instance);
|
|
||||||
|
|
||||||
var headers = new HeaderDictionary
|
|
||||||
{
|
|
||||||
["X-Emby-Authorization"] =
|
|
||||||
"MediaBrowser Client=\"Feishin\", Device=\"Desktop\", DeviceId=\"dev-123\", Version=\"1.0\", Token=\"abc\""
|
|
||||||
};
|
|
||||||
|
|
||||||
var ensured = await manager.EnsureSessionAsync("dev-123", "Feishin", "Desktop", "1.0", headers);
|
|
||||||
Assert.True(ensured);
|
|
||||||
|
|
||||||
manager.MarkSessionPotentiallyEnded("dev-123", TimeSpan.FromMilliseconds(25));
|
|
||||||
await Task.Delay(100);
|
|
||||||
|
|
||||||
Assert.True(manager.HasSession("dev-123"));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RemoveSessionAsync_ReportsPlaybackStopButDoesNotLogoutUserSession()
|
|
||||||
{
|
|
||||||
var requestedPaths = new ConcurrentBag<string>();
|
|
||||||
var handler = new DelegateHttpMessageHandler((request, _) =>
|
|
||||||
{
|
|
||||||
requestedPaths.Add(request.RequestUri?.AbsolutePath ?? string.Empty);
|
|
||||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent));
|
|
||||||
});
|
|
||||||
|
|
||||||
var settings = new JellyfinSettings
|
|
||||||
{
|
|
||||||
Url = "http://127.0.0.1:1",
|
|
||||||
ApiKey = "server-api-key",
|
|
||||||
ClientName = "Allstarr",
|
|
||||||
DeviceName = "Allstarr",
|
|
||||||
DeviceId = "allstarr",
|
|
||||||
ClientVersion = "1.0"
|
|
||||||
};
|
|
||||||
|
|
||||||
var proxyService = CreateProxyService(handler, settings);
|
|
||||||
using var manager = new JellyfinSessionManager(
|
|
||||||
proxyService,
|
|
||||||
Options.Create(settings),
|
|
||||||
NullLogger<JellyfinSessionManager>.Instance);
|
|
||||||
|
|
||||||
var headers = new HeaderDictionary
|
|
||||||
{
|
|
||||||
["X-Emby-Authorization"] =
|
|
||||||
"MediaBrowser Client=\"Feishin\", Device=\"Desktop\", DeviceId=\"dev-123\", Version=\"1.0\", Token=\"abc\""
|
|
||||||
};
|
|
||||||
|
|
||||||
var ensured = await manager.EnsureSessionAsync("dev-123", "Feishin", "Desktop", "1.0", headers);
|
|
||||||
Assert.True(ensured);
|
|
||||||
|
|
||||||
manager.UpdatePlayingItem("dev-123", "item-123", 42);
|
|
||||||
await manager.RemoveSessionAsync("dev-123");
|
|
||||||
|
|
||||||
Assert.Contains("/Sessions/Capabilities/Full", requestedPaths);
|
|
||||||
Assert.Contains("/Sessions/Playing/Stopped", requestedPaths);
|
|
||||||
Assert.DoesNotContain("/Sessions/Logout", requestedPaths);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static JellyfinProxyService CreateProxyService(HttpMessageHandler handler, JellyfinSettings settings)
|
|
||||||
{
|
|
||||||
var httpClientFactory = new TestHttpClientFactory(handler);
|
|
||||||
var httpContextAccessor = new HttpContextAccessor
|
|
||||||
{
|
|
||||||
HttpContext = new DefaultHttpContext()
|
|
||||||
};
|
|
||||||
|
|
||||||
var cache = new RedisCacheService(
|
|
||||||
Options.Create(new RedisSettings { Enabled = false }),
|
|
||||||
NullLogger<RedisCacheService>.Instance);
|
|
||||||
|
|
||||||
return new JellyfinProxyService(
|
|
||||||
httpClientFactory,
|
|
||||||
Options.Create(settings),
|
|
||||||
httpContextAccessor,
|
|
||||||
NullLogger<JellyfinProxyService>.Instance,
|
|
||||||
cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class TestHttpClientFactory : IHttpClientFactory
|
|
||||||
{
|
|
||||||
private readonly HttpClient _client;
|
|
||||||
|
|
||||||
public TestHttpClientFactory(HttpMessageHandler handler)
|
|
||||||
{
|
|
||||||
_client = new HttpClient(handler, disposeHandler: false);
|
|
||||||
}
|
|
||||||
|
|
||||||
public HttpClient CreateClient(string name)
|
|
||||||
{
|
|
||||||
return _client;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class DelegateHttpMessageHandler : HttpMessageHandler
|
|
||||||
{
|
|
||||||
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handler;
|
|
||||||
|
|
||||||
public DelegateHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
|
|
||||||
{
|
|
||||||
_handler = handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override Task<HttpResponseMessage> SendAsync(
|
|
||||||
HttpRequestMessage request,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return _handler(request, cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,229 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Reflection;
|
|
||||||
using System.Text;
|
|
||||||
using allstarr.Models.Settings;
|
|
||||||
using allstarr.Services;
|
|
||||||
using allstarr.Services.Common;
|
|
||||||
using allstarr.Services.Local;
|
|
||||||
using allstarr.Services.SquidWTF;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using Moq;
|
|
||||||
|
|
||||||
namespace allstarr.Tests;
|
|
||||||
|
|
||||||
public class SquidWTFDownloadServiceTests : IDisposable
|
|
||||||
{
|
|
||||||
private readonly Mock<IHttpClientFactory> _httpClientFactoryMock = new();
|
|
||||||
private readonly Mock<ILocalLibraryService> _localLibraryServiceMock = new();
|
|
||||||
private readonly Mock<IMusicMetadataService> _metadataServiceMock = new();
|
|
||||||
private readonly Mock<IServiceProvider> _serviceProviderMock = new();
|
|
||||||
private readonly Mock<ILogger<SquidWTFDownloadService>> _loggerMock = new();
|
|
||||||
private readonly Mock<ILogger<OdesliService>> _odesliLoggerMock = new();
|
|
||||||
private readonly Mock<ILogger<RedisCacheService>> _redisLoggerMock = new();
|
|
||||||
private readonly string _testDownloadPath;
|
|
||||||
private readonly List<string> _apiUrls =
|
|
||||||
[
|
|
||||||
"http://127.0.0.1:18081",
|
|
||||||
"http://127.0.0.1:18082"
|
|
||||||
];
|
|
||||||
|
|
||||||
public SquidWTFDownloadServiceTests()
|
|
||||||
{
|
|
||||||
_testDownloadPath = Path.Combine(Path.GetTempPath(), "allstarr-squidwtf-download-tests-" + Guid.NewGuid());
|
|
||||||
Directory.CreateDirectory(_testDownloadPath);
|
|
||||||
|
|
||||||
_serviceProviderMock
|
|
||||||
.Setup(sp => sp.GetService(typeof(allstarr.Services.Subsonic.PlaylistSyncService)))
|
|
||||||
.Returns((object?)null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
if (Directory.Exists(_testDownloadPath))
|
|
||||||
{
|
|
||||||
Directory.Delete(_testDownloadPath, true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void BuildQualityFallbackOrder_MapsConfiguredQualityToDescendingFallbacks()
|
|
||||||
{
|
|
||||||
var order = InvokePrivateStaticMethod<IReadOnlyList<string>>(
|
|
||||||
typeof(SquidWTFDownloadService),
|
|
||||||
"BuildQualityFallbackOrder",
|
|
||||||
"HI_RES");
|
|
||||||
|
|
||||||
Assert.Equal(["HI_RES_LOSSLESS", "LOSSLESS", "HIGH", "LOW"], order);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetTrackDownloadInfoAsync_FallsBackToLowerQualityWhenPreferredQualityIsUnavailable()
|
|
||||||
{
|
|
||||||
var requests = new List<string>();
|
|
||||||
using var handler = new StubHttpMessageHandler(request =>
|
|
||||||
{
|
|
||||||
var url = request.RequestUri!.ToString();
|
|
||||||
requests.Add(url);
|
|
||||||
|
|
||||||
if (url.Contains("quality=LOSSLESS", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.Forbidden);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.Contains("quality=HIGH", StringComparison.Ordinal) &&
|
|
||||||
url.StartsWith("http://127.0.0.1:18082/", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.Forbidden);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (url.Contains("quality=HIGH", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent(CreateTrackResponseJson("HIGH", "audio/mp4", "https://cdn.example.com/334284374.m4a"))
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.NotFound);
|
|
||||||
});
|
|
||||||
|
|
||||||
var service = CreateService(handler, quality: "FLAC");
|
|
||||||
|
|
||||||
var result = await InvokePrivateAsync(service, "GetTrackDownloadInfoAsync", "334284374", CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal("http://127.0.0.1:18081", GetProperty<string>(result, "Endpoint"));
|
|
||||||
Assert.Equal("https://cdn.example.com/334284374.m4a", GetProperty<string>(result, "DownloadUrl"));
|
|
||||||
Assert.Equal("audio/mp4", GetProperty<string>(result, "MimeType"));
|
|
||||||
Assert.Equal("HIGH", GetProperty<string>(result, "AudioQuality"));
|
|
||||||
|
|
||||||
Assert.Contains(requests, url => url.Contains("quality=LOSSLESS", StringComparison.Ordinal));
|
|
||||||
Assert.Contains(requests, url => url.Contains("quality=HIGH", StringComparison.Ordinal));
|
|
||||||
|
|
||||||
var lastLosslessRequest = requests.FindLastIndex(url => url.Contains("quality=LOSSLESS", StringComparison.Ordinal));
|
|
||||||
var firstHighRequest = requests.FindIndex(url => url.Contains("quality=HIGH", StringComparison.Ordinal));
|
|
||||||
|
|
||||||
Assert.True(lastLosslessRequest >= 0);
|
|
||||||
Assert.True(firstHighRequest > lastLosslessRequest);
|
|
||||||
}
|
|
||||||
|
|
||||||
private SquidWTFDownloadService CreateService(HttpMessageHandler handler, string quality)
|
|
||||||
{
|
|
||||||
var httpClient = new HttpClient(handler);
|
|
||||||
_httpClientFactoryMock.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(httpClient);
|
|
||||||
|
|
||||||
var configuration = new ConfigurationBuilder()
|
|
||||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
|
||||||
{
|
|
||||||
["Library:DownloadPath"] = _testDownloadPath
|
|
||||||
})
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
var subsonicSettings = Options.Create(new SubsonicSettings
|
|
||||||
{
|
|
||||||
DownloadMode = DownloadMode.Track,
|
|
||||||
StorageMode = StorageMode.Cache
|
|
||||||
});
|
|
||||||
|
|
||||||
var squidwtfSettings = Options.Create(new SquidWTFSettings
|
|
||||||
{
|
|
||||||
Quality = quality
|
|
||||||
});
|
|
||||||
|
|
||||||
var cache = new RedisCacheService(
|
|
||||||
Options.Create(new RedisSettings { Enabled = false }),
|
|
||||||
_redisLoggerMock.Object);
|
|
||||||
|
|
||||||
var odesliService = new OdesliService(_httpClientFactoryMock.Object, _odesliLoggerMock.Object, cache);
|
|
||||||
|
|
||||||
return new SquidWTFDownloadService(
|
|
||||||
_httpClientFactoryMock.Object,
|
|
||||||
configuration,
|
|
||||||
_localLibraryServiceMock.Object,
|
|
||||||
_metadataServiceMock.Object,
|
|
||||||
subsonicSettings,
|
|
||||||
squidwtfSettings,
|
|
||||||
_serviceProviderMock.Object,
|
|
||||||
_loggerMock.Object,
|
|
||||||
odesliService,
|
|
||||||
_apiUrls);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string CreateTrackResponseJson(string audioQuality, string mimeType, string downloadUrl)
|
|
||||||
{
|
|
||||||
var manifestJson = $$"""
|
|
||||||
{
|
|
||||||
"mimeType": "{{mimeType}}",
|
|
||||||
"codecs": "aac",
|
|
||||||
"encryptionType": "NONE",
|
|
||||||
"urls": ["{{downloadUrl}}"]
|
|
||||||
}
|
|
||||||
""";
|
|
||||||
|
|
||||||
var manifestBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(manifestJson));
|
|
||||||
|
|
||||||
return $$"""
|
|
||||||
{
|
|
||||||
"version": "2.4",
|
|
||||||
"data": {
|
|
||||||
"audioQuality": "{{audioQuality}}",
|
|
||||||
"manifest": "{{manifestBase64}}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<object> InvokePrivateAsync(object target, string methodName, params object?[] parameters)
|
|
||||||
{
|
|
||||||
var method = target.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
|
|
||||||
Assert.NotNull(method);
|
|
||||||
|
|
||||||
var task = method!.Invoke(target, parameters) as Task;
|
|
||||||
Assert.NotNull(task);
|
|
||||||
|
|
||||||
await task!;
|
|
||||||
|
|
||||||
var resultProperty = task.GetType().GetProperty("Result");
|
|
||||||
Assert.NotNull(resultProperty);
|
|
||||||
|
|
||||||
var result = resultProperty!.GetValue(task);
|
|
||||||
Assert.NotNull(result);
|
|
||||||
return result!;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static T InvokePrivateStaticMethod<T>(Type targetType, string methodName, params object?[] parameters)
|
|
||||||
{
|
|
||||||
var method = targetType.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);
|
|
||||||
Assert.NotNull(method);
|
|
||||||
|
|
||||||
var result = method!.Invoke(null, parameters);
|
|
||||||
Assert.NotNull(result);
|
|
||||||
return (T)result!;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static T GetProperty<T>(object target, string propertyName)
|
|
||||||
{
|
|
||||||
var property = target.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
|
|
||||||
Assert.NotNull(property);
|
|
||||||
|
|
||||||
var value = property!.GetValue(target);
|
|
||||||
Assert.NotNull(value);
|
|
||||||
return (T)value!;
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class StubHttpMessageHandler : HttpMessageHandler
|
|
||||||
{
|
|
||||||
private readonly Func<HttpRequestMessage, HttpResponseMessage> _handler;
|
|
||||||
|
|
||||||
public StubHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
|
||||||
{
|
|
||||||
_handler = handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.FromResult(_handler(request));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,11 +7,8 @@ using allstarr.Services.Common;
|
|||||||
using allstarr.Models.Domain;
|
using allstarr.Models.Domain;
|
||||||
using allstarr.Models.Settings;
|
using allstarr.Models.Settings;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Net;
|
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace allstarr.Tests;
|
namespace allstarr.Tests;
|
||||||
|
|
||||||
@@ -346,168 +343,6 @@ public class SquidWTFMetadataServiceTests
|
|||||||
Assert.NotNull(service);
|
Assert.NotNull(service);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetTrackRecommendationsAsync_FallsBackWhenFirstEndpointReturnsEmpty()
|
|
||||||
{
|
|
||||||
var handler = new StubHttpMessageHandler(request =>
|
|
||||||
{
|
|
||||||
var port = request.RequestUri?.Port;
|
|
||||||
|
|
||||||
if (port == 5011)
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""
|
|
||||||
{
|
|
||||||
"version": "2.4",
|
|
||||||
"data": {
|
|
||||||
"limit": 20,
|
|
||||||
"offset": 0,
|
|
||||||
"totalNumberOfItems": 0,
|
|
||||||
"items": []
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (port == 5012)
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""
|
|
||||||
{
|
|
||||||
"version": "2.4",
|
|
||||||
"data": {
|
|
||||||
"limit": 20,
|
|
||||||
"offset": 0,
|
|
||||||
"totalNumberOfItems": 1,
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"track": {
|
|
||||||
"id": 371921532,
|
|
||||||
"title": "Take It Slow",
|
|
||||||
"duration": 139,
|
|
||||||
"trackNumber": 1,
|
|
||||||
"volumeNumber": 1,
|
|
||||||
"explicit": false,
|
|
||||||
"artist": { "id": 10330497, "name": "Isaac Dunbar" },
|
|
||||||
"artists": [
|
|
||||||
{ "id": 10330497, "name": "Isaac Dunbar" }
|
|
||||||
],
|
|
||||||
"album": {
|
|
||||||
"id": 371921525,
|
|
||||||
"title": "Take It Slow",
|
|
||||||
"cover": "aeb70f15-78ef-4230-929d-2d62c70ac00c"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new InvalidOperationException($"Unexpected request URI: {request.RequestUri}");
|
|
||||||
});
|
|
||||||
|
|
||||||
var httpClient = new HttpClient(handler);
|
|
||||||
_mockHttpClientFactory.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(httpClient);
|
|
||||||
|
|
||||||
var service = new SquidWTFMetadataService(
|
|
||||||
_mockHttpClientFactory.Object,
|
|
||||||
_subsonicSettings,
|
|
||||||
_squidwtfSettings,
|
|
||||||
_mockLogger.Object,
|
|
||||||
_mockCache.Object,
|
|
||||||
new List<string>
|
|
||||||
{
|
|
||||||
"http://127.0.0.1:5011",
|
|
||||||
"http://127.0.0.1:5012"
|
|
||||||
});
|
|
||||||
|
|
||||||
var result = await service.GetTrackRecommendationsAsync("227242909", 20);
|
|
||||||
|
|
||||||
Assert.Single(result);
|
|
||||||
Assert.Equal("371921532", result[0].ExternalId);
|
|
||||||
Assert.Equal("Take It Slow", result[0].Title);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task GetSongAsync_FallsBackWhenFirstEndpointReturnsErrorPayload()
|
|
||||||
{
|
|
||||||
var handler = new StubHttpMessageHandler(request =>
|
|
||||||
{
|
|
||||||
var port = request.RequestUri?.Port;
|
|
||||||
|
|
||||||
if (port == 5021)
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""
|
|
||||||
{
|
|
||||||
"detail": "Upstream API error"
|
|
||||||
}
|
|
||||||
""")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (port == 5022)
|
|
||||||
{
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""
|
|
||||||
{
|
|
||||||
"version": "2.4",
|
|
||||||
"data": {
|
|
||||||
"id": 227242909,
|
|
||||||
"title": "Monica Lewinsky",
|
|
||||||
"duration": 132,
|
|
||||||
"trackNumber": 1,
|
|
||||||
"volumeNumber": 1,
|
|
||||||
"explicit": true,
|
|
||||||
"artist": { "id": 8420542, "name": "UPSAHL" },
|
|
||||||
"artists": [
|
|
||||||
{ "id": 8420542, "name": "UPSAHL" }
|
|
||||||
],
|
|
||||||
"album": {
|
|
||||||
"id": 227242908,
|
|
||||||
"title": "Monica Lewinsky",
|
|
||||||
"cover": "32522342-3903-42ab-aaea-a6f4f46ca0cc"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
""")
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new InvalidOperationException($"Unexpected request URI: {request.RequestUri}");
|
|
||||||
});
|
|
||||||
|
|
||||||
var httpClient = new HttpClient(handler);
|
|
||||||
_mockHttpClientFactory.Setup(f => f.CreateClient(It.IsAny<string>())).Returns(httpClient);
|
|
||||||
|
|
||||||
var service = new SquidWTFMetadataService(
|
|
||||||
_mockHttpClientFactory.Object,
|
|
||||||
_subsonicSettings,
|
|
||||||
_squidwtfSettings,
|
|
||||||
_mockLogger.Object,
|
|
||||||
_mockCache.Object,
|
|
||||||
new List<string>
|
|
||||||
{
|
|
||||||
"http://127.0.0.1:5021",
|
|
||||||
"http://127.0.0.1:5022"
|
|
||||||
});
|
|
||||||
|
|
||||||
var song = await service.GetSongAsync("squidwtf", "227242909");
|
|
||||||
|
|
||||||
Assert.NotNull(song);
|
|
||||||
Assert.Equal("227242909", song!.ExternalId);
|
|
||||||
Assert.Equal("Monica Lewinsky", song.Title);
|
|
||||||
Assert.Equal(1, song.ExplicitContentLyrics);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildSearchQueryVariants_WithAmpersand_AddsAndVariant()
|
public void BuildSearchQueryVariants_WithAmpersand_AddsAndVariant()
|
||||||
{
|
{
|
||||||
@@ -726,19 +561,4 @@ public class SquidWTFMetadataServiceTests
|
|||||||
Assert.NotNull(result);
|
Assert.NotNull(result);
|
||||||
return (T)result!;
|
return (T)result!;
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class StubHttpMessageHandler : HttpMessageHandler
|
|
||||||
{
|
|
||||||
private readonly Func<HttpRequestMessage, HttpResponseMessage> _handler;
|
|
||||||
|
|
||||||
public StubHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
|
||||||
{
|
|
||||||
_handler = handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.FromResult(_handler(request));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -184,19 +184,7 @@ public partial class JellyfinController
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
if (ex is HttpRequestException httpRequestException && httpRequestException.StatusCode.HasValue)
|
_logger.LogError(ex, "Failed to stream external song {Provider}:{ExternalId}", provider, externalId);
|
||||||
{
|
|
||||||
_logger.LogError("Failed to stream external song {Provider}:{ExternalId}: {StatusCode}: {ReasonPhrase}",
|
|
||||||
provider,
|
|
||||||
externalId,
|
|
||||||
(int)httpRequestException.StatusCode.Value,
|
|
||||||
httpRequestException.StatusCode.Value);
|
|
||||||
_logger.LogDebug(ex, "Detailed streaming failure for external song {Provider}:{ExternalId}", provider, externalId);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Failed to stream external song {Provider}:{ExternalId}", provider, externalId);
|
|
||||||
}
|
|
||||||
return StatusCode(500, new { error = "Streaming failed" });
|
return StatusCode(500, new { error = "Streaming failed" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using allstarr.Services.Common;
|
|
||||||
|
|
||||||
namespace allstarr.Controllers;
|
namespace allstarr.Controllers;
|
||||||
|
|
||||||
@@ -54,10 +53,8 @@ public partial class JellyfinController
|
|||||||
// Post session capabilities in background if we have a token
|
// Post session capabilities in background if we have a token
|
||||||
if (!string.IsNullOrEmpty(accessToken))
|
if (!string.IsNullOrEmpty(accessToken))
|
||||||
{
|
{
|
||||||
var (deviceId, client, device, version) = ExtractDeviceInfo(Request.Headers);
|
|
||||||
// Capture token in closure - don't use Request.Headers (will be disposed)
|
// Capture token in closure - don't use Request.Headers (will be disposed)
|
||||||
var token = accessToken;
|
var token = accessToken;
|
||||||
var authHeader = AuthHeaderHelper.CreateAuthHeader(token, client, device, deviceId, version);
|
|
||||||
_ = Task.Run(async () =>
|
_ = Task.Run(async () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -67,7 +64,6 @@ public partial class JellyfinController
|
|||||||
// Build auth header with the new token
|
// Build auth header with the new token
|
||||||
var authHeaders = new HeaderDictionary
|
var authHeaders = new HeaderDictionary
|
||||||
{
|
{
|
||||||
["X-Emby-Authorization"] = authHeader,
|
|
||||||
["X-Emby-Token"] = token
|
["X-Emby-Token"] = token
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -145,11 +145,12 @@ public partial class JellyfinController
|
|||||||
return NotFound(new { error = "Song not found" });
|
return NotFound(new { error = "Song not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip external track labels from lyrics search terms.
|
// Strip [S] suffix from title, artist, and album for lyrics search
|
||||||
var searchTitle = StripTrackDecorators(song.Title);
|
// The [S] tag is added to external tracks but shouldn't be used in lyrics queries
|
||||||
var searchArtist = StripTrackDecorators(song.Artist);
|
var searchTitle = song.Title.Replace(" [S]", "").Trim();
|
||||||
var searchAlbum = StripTrackDecorators(song.Album);
|
var searchArtist = song.Artist?.Replace(" [S]", "").Trim() ?? "";
|
||||||
var searchArtists = song.Artists.Select(StripTrackDecorators).ToList();
|
var searchAlbum = song.Album?.Replace(" [S]", "").Trim() ?? "";
|
||||||
|
var searchArtists = song.Artists.Select(a => a.Replace(" [S]", "").Trim()).ToList();
|
||||||
|
|
||||||
if (searchArtists.Count == 0 && !string.IsNullOrEmpty(searchArtist))
|
if (searchArtists.Count == 0 && !string.IsNullOrEmpty(searchArtist))
|
||||||
{
|
{
|
||||||
@@ -378,11 +379,11 @@ public partial class JellyfinController
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip external track labels for lyrics search.
|
// Strip [S] suffix for lyrics search
|
||||||
var searchTitle = StripTrackDecorators(song.Title);
|
var searchTitle = song.Title.Replace(" [S]", "").Trim();
|
||||||
var searchArtist = StripTrackDecorators(song.Artist);
|
var searchArtist = song.Artist?.Replace(" [S]", "").Trim() ?? "";
|
||||||
var searchAlbum = StripTrackDecorators(song.Album);
|
var searchAlbum = song.Album?.Replace(" [S]", "").Trim() ?? "";
|
||||||
var searchArtists = song.Artists.Select(StripTrackDecorators).ToList();
|
var searchArtists = song.Artists.Select(a => a.Replace(" [S]", "").Trim()).ToList();
|
||||||
|
|
||||||
if (searchArtists.Count == 0 && !string.IsNullOrEmpty(searchArtist))
|
if (searchArtists.Count == 0 && !string.IsNullOrEmpty(searchArtist))
|
||||||
{
|
{
|
||||||
@@ -466,18 +467,5 @@ public partial class JellyfinController
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string StripTrackDecorators(string? value)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(value))
|
|
||||||
{
|
|
||||||
return string.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
return value
|
|
||||||
.Replace(" [S]", "", StringComparison.Ordinal)
|
|
||||||
.Replace(" [E]", "", StringComparison.Ordinal)
|
|
||||||
.Trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using allstarr.Models.Search;
|
|
||||||
using allstarr.Models.Subsonic;
|
using allstarr.Models.Subsonic;
|
||||||
using allstarr.Services.Common;
|
using allstarr.Services.Common;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
@@ -35,7 +34,6 @@ public partial class JellyfinController
|
|||||||
|
|
||||||
// AlbumArtistIds takes precedence over ArtistIds if both are provided
|
// AlbumArtistIds takes precedence over ArtistIds if both are provided
|
||||||
var effectiveArtistIds = albumArtistIds ?? artistIds;
|
var effectiveArtistIds = albumArtistIds ?? artistIds;
|
||||||
var favoritesOnlyRequest = IsFavoritesOnlyRequest();
|
|
||||||
|
|
||||||
_logger.LogDebug("=== SEARCHITEMS V2 CALLED === searchTerm={SearchTerm}, includeItemTypes={ItemTypes}, parentId={ParentId}, artistIds={ArtistIds}, albumArtistIds={AlbumArtistIds}, albumIds={AlbumIds}, userId={UserId}",
|
_logger.LogDebug("=== SEARCHITEMS V2 CALLED === searchTerm={SearchTerm}, includeItemTypes={ItemTypes}, parentId={ParentId}, artistIds={ArtistIds}, albumArtistIds={AlbumArtistIds}, albumIds={AlbumIds}, userId={UserId}",
|
||||||
searchTerm, includeItemTypes, parentId, artistIds, albumArtistIds, albumIds, userId);
|
searchTerm, includeItemTypes, parentId, artistIds, albumArtistIds, albumIds, userId);
|
||||||
@@ -65,12 +63,6 @@ public partial class JellyfinController
|
|||||||
|
|
||||||
if (isExternal)
|
if (isExternal)
|
||||||
{
|
{
|
||||||
if (favoritesOnlyRequest)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Suppressing external artist results for favorites-only request: {ArtistId}", artistId);
|
|
||||||
return CreateEmptyItemsResponse(startIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if this is a curator ID (format: ext-{provider}-curator-{name})
|
// Check if this is a curator ID (format: ext-{provider}-curator-{name})
|
||||||
if (artistId.Contains("-curator-", StringComparison.OrdinalIgnoreCase))
|
if (artistId.Contains("-curator-", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
@@ -93,12 +85,6 @@ public partial class JellyfinController
|
|||||||
|
|
||||||
if (isExternal)
|
if (isExternal)
|
||||||
{
|
{
|
||||||
if (favoritesOnlyRequest)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Suppressing external album results for favorites-only request: {AlbumId}", albumId);
|
|
||||||
return CreateEmptyItemsResponse(startIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug("Fetching songs for external album: {Provider}/{ExternalId}", provider,
|
_logger.LogDebug("Fetching songs for external album: {Provider}/{ExternalId}", provider,
|
||||||
externalId);
|
externalId);
|
||||||
|
|
||||||
@@ -134,12 +120,6 @@ public partial class JellyfinController
|
|||||||
|
|
||||||
if (isExternal)
|
if (isExternal)
|
||||||
{
|
{
|
||||||
if (favoritesOnlyRequest)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Suppressing external parent results for favorites-only request: {ParentId}", parentId);
|
|
||||||
return CreateEmptyItemsResponse(startIndex);
|
|
||||||
}
|
|
||||||
|
|
||||||
// External parent - get external content
|
// External parent - get external content
|
||||||
_logger.LogDebug("Fetching children for external parent: {Provider}/{Type}/{ExternalId}",
|
_logger.LogDebug("Fetching children for external parent: {Provider}/{Type}/{ExternalId}",
|
||||||
provider, type, externalId);
|
provider, type, externalId);
|
||||||
@@ -190,8 +170,7 @@ public partial class JellyfinController
|
|||||||
sortBy,
|
sortBy,
|
||||||
Request.Query["SortOrder"].ToString(),
|
Request.Query["SortOrder"].ToString(),
|
||||||
recursive,
|
recursive,
|
||||||
userId,
|
userId);
|
||||||
Request.Query["IsFavorite"].ToString());
|
|
||||||
var cachedResult = await _cache.GetAsync<object>(cacheKey);
|
var cachedResult = await _cache.GetAsync<object>(cacheKey);
|
||||||
|
|
||||||
if (cachedResult != null)
|
if (cachedResult != null)
|
||||||
@@ -312,15 +291,13 @@ public partial class JellyfinController
|
|||||||
userId);
|
userId);
|
||||||
|
|
||||||
// Use parallel metadata service if available (races providers), otherwise use primary
|
// Use parallel metadata service if available (races providers), otherwise use primary
|
||||||
var externalTask = favoritesOnlyRequest
|
var externalTask = _parallelMetadataService != null
|
||||||
? Task.FromResult(new SearchResult())
|
? _parallelMetadataService.SearchAllAsync(cleanQuery, limit, limit, limit, HttpContext.RequestAborted)
|
||||||
: _parallelMetadataService != null
|
: _metadataService.SearchAllAsync(cleanQuery, limit, limit, limit, HttpContext.RequestAborted);
|
||||||
? _parallelMetadataService.SearchAllAsync(cleanQuery, limit, limit, limit, HttpContext.RequestAborted)
|
|
||||||
: _metadataService.SearchAllAsync(cleanQuery, limit, limit, limit, HttpContext.RequestAborted);
|
|
||||||
|
|
||||||
var playlistTask = favoritesOnlyRequest || !_settings.EnableExternalPlaylists
|
var playlistTask = _settings.EnableExternalPlaylists
|
||||||
? Task.FromResult(new List<ExternalPlaylist>())
|
? _metadataService.SearchPlaylistsAsync(cleanQuery, limit, HttpContext.RequestAborted)
|
||||||
: _metadataService.SearchPlaylistsAsync(cleanQuery, limit, HttpContext.RequestAborted);
|
: Task.FromResult(new List<ExternalPlaylist>());
|
||||||
|
|
||||||
_logger.LogDebug("Playlist search enabled: {Enabled}, searching for: '{Query}'",
|
_logger.LogDebug("Playlist search enabled: {Enabled}, searching for: '{Query}'",
|
||||||
_settings.EnableExternalPlaylists, cleanQuery);
|
_settings.EnableExternalPlaylists, cleanQuery);
|
||||||
@@ -539,7 +516,7 @@ public partial class JellyfinController
|
|||||||
StartIndex = startIndex
|
StartIndex = startIndex
|
||||||
};
|
};
|
||||||
|
|
||||||
// Cache search results in Redis using the configured search TTL.
|
// Cache search results in Redis (15 min TTL, no file persistence)
|
||||||
if (!string.IsNullOrWhiteSpace(searchTerm) && string.IsNullOrWhiteSpace(effectiveArtistIds))
|
if (!string.IsNullOrWhiteSpace(searchTerm) && string.IsNullOrWhiteSpace(effectiveArtistIds))
|
||||||
{
|
{
|
||||||
if (externalHasRequestedTypeResults)
|
if (externalHasRequestedTypeResults)
|
||||||
@@ -553,8 +530,7 @@ public partial class JellyfinController
|
|||||||
sortBy,
|
sortBy,
|
||||||
Request.Query["SortOrder"].ToString(),
|
Request.Query["SortOrder"].ToString(),
|
||||||
recursive,
|
recursive,
|
||||||
userId,
|
userId);
|
||||||
Request.Query["IsFavorite"].ToString());
|
|
||||||
await _cache.SetAsync(cacheKey, response, CacheExtensions.SearchResultsTTL);
|
await _cache.SetAsync(cacheKey, response, CacheExtensions.SearchResultsTTL);
|
||||||
_logger.LogDebug("💾 Cached search results for '{SearchTerm}' ({Minutes} min TTL)", searchTerm,
|
_logger.LogDebug("💾 Cached search results for '{SearchTerm}' ({Minutes} min TTL)", searchTerm,
|
||||||
CacheExtensions.SearchResultsTTL.TotalMinutes);
|
CacheExtensions.SearchResultsTTL.TotalMinutes);
|
||||||
@@ -746,21 +722,6 @@ public partial class JellyfinController
|
|||||||
return MaskSensitiveQueryString(query);
|
return MaskSensitiveQueryString(query);
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsFavoritesOnlyRequest()
|
|
||||||
{
|
|
||||||
return string.Equals(Request.Query["IsFavorite"].ToString(), "true", StringComparison.OrdinalIgnoreCase);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IActionResult CreateEmptyItemsResponse(int startIndex)
|
|
||||||
{
|
|
||||||
return new JsonResult(new
|
|
||||||
{
|
|
||||||
Items = Array.Empty<object>(),
|
|
||||||
TotalRecordCount = 0,
|
|
||||||
StartIndex = startIndex
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<Dictionary<string, object?>> ApplyRequestedAlbumOrderingIfApplicable(
|
private List<Dictionary<string, object?>> ApplyRequestedAlbumOrderingIfApplicable(
|
||||||
List<Dictionary<string, object?>> items,
|
List<Dictionary<string, object?>> items,
|
||||||
string[]? requestedTypes,
|
string[]? requestedTypes,
|
||||||
|
|||||||
@@ -201,16 +201,6 @@ public partial class JellyfinController : ControllerBase
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<IActionResult> GetExternalChildItems(string provider, string type, string externalId, string? includeItemTypes, CancellationToken cancellationToken = default)
|
private async Task<IActionResult> GetExternalChildItems(string provider, string type, string externalId, string? includeItemTypes, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
if (IsFavoritesOnlyRequest())
|
|
||||||
{
|
|
||||||
_logger.LogDebug(
|
|
||||||
"Suppressing external child items for favorites-only request: provider={Provider}, type={Type}, externalId={ExternalId}",
|
|
||||||
provider,
|
|
||||||
type,
|
|
||||||
externalId);
|
|
||||||
return CreateEmptyItemsResponse(GetRequestedStartIndex());
|
|
||||||
}
|
|
||||||
|
|
||||||
var itemTypes = ParseItemTypes(includeItemTypes);
|
var itemTypes = ParseItemTypes(includeItemTypes);
|
||||||
var itemTypesUnspecified = itemTypes == null || itemTypes.Length == 0;
|
var itemTypesUnspecified = itemTypes == null || itemTypes.Length == 0;
|
||||||
|
|
||||||
@@ -290,13 +280,6 @@ public partial class JellyfinController : ControllerBase
|
|||||||
return _responseBuilder.CreateItemsResponse(new List<Song>());
|
return _responseBuilder.CreateItemsResponse(new List<Song>());
|
||||||
}
|
}
|
||||||
|
|
||||||
private int GetRequestedStartIndex()
|
|
||||||
{
|
|
||||||
return int.TryParse(Request.Query["StartIndex"], out var startIndex) && startIndex > 0
|
|
||||||
? startIndex
|
|
||||||
: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<Song> ApplySongSortAndPagingForCurrentRequest(IReadOnlyCollection<Song> songs, out int totalRecordCount, out int startIndex)
|
private List<Song> ApplySongSortAndPagingForCurrentRequest(IReadOnlyCollection<Song> songs, out int totalRecordCount, out int startIndex)
|
||||||
{
|
{
|
||||||
var sortBy = Request.Query["SortBy"].ToString();
|
var sortBy = Request.Query["SortBy"].ToString();
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
using allstarr.Services.Common;
|
|
||||||
|
|
||||||
namespace allstarr.Middleware;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Short-circuits common internet scanner paths before they reach the Jellyfin proxy.
|
|
||||||
/// </summary>
|
|
||||||
public class BotProbeBlockMiddleware
|
|
||||||
{
|
|
||||||
private readonly RequestDelegate _next;
|
|
||||||
private readonly ILogger<BotProbeBlockMiddleware> _logger;
|
|
||||||
|
|
||||||
public BotProbeBlockMiddleware(
|
|
||||||
RequestDelegate next,
|
|
||||||
ILogger<BotProbeBlockMiddleware> logger)
|
|
||||||
{
|
|
||||||
_next = next;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task InvokeAsync(HttpContext context)
|
|
||||||
{
|
|
||||||
var requestPath = context.Request.Path.Value;
|
|
||||||
if (!BotProbeDetector.IsHighConfidenceProbePath(requestPath))
|
|
||||||
{
|
|
||||||
await _next(context);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug("Short-circuited likely bot probe from {RemoteIp}: {Method} {Path}",
|
|
||||||
context.Connection.RemoteIpAddress?.ToString() ?? "(null)",
|
|
||||||
context.Request.Method,
|
|
||||||
requestPath);
|
|
||||||
|
|
||||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -120,11 +120,6 @@ public class WebSocketProxyMiddleware
|
|||||||
serverWebSocket.Options.SetRequestHeader("X-Emby-Authorization", embyAuthHeader.ToString());
|
serverWebSocket.Options.SetRequestHeader("X-Emby-Authorization", embyAuthHeader.ToString());
|
||||||
_logger.LogDebug("🔑 WEBSOCKET: Forwarded X-Emby-Authorization header");
|
_logger.LogDebug("🔑 WEBSOCKET: Forwarded X-Emby-Authorization header");
|
||||||
}
|
}
|
||||||
else if (context.Request.Headers.TryGetValue("X-Emby-Token", out var tokenHeader))
|
|
||||||
{
|
|
||||||
serverWebSocket.Options.SetRequestHeader("X-Emby-Token", tokenHeader.ToString());
|
|
||||||
_logger.LogDebug("🔑 WEBSOCKET: Forwarded X-Emby-Token header");
|
|
||||||
}
|
|
||||||
else if (context.Request.Headers.TryGetValue("Authorization", out var authHeader2))
|
else if (context.Request.Headers.TryGetValue("Authorization", out var authHeader2))
|
||||||
{
|
{
|
||||||
var authValue = authHeader2.ToString();
|
var authValue = authHeader2.ToString();
|
||||||
|
|||||||
@@ -911,9 +911,6 @@ catch (Exception ex)
|
|||||||
// This processes X-Forwarded-For, X-Real-IP, etc. from nginx
|
// This processes X-Forwarded-For, X-Real-IP, etc. from nginx
|
||||||
app.UseForwardedHeaders();
|
app.UseForwardedHeaders();
|
||||||
|
|
||||||
// Drop high-confidence scanner paths before they hit the proxy or request logging.
|
|
||||||
app.UseMiddleware<BotProbeBlockMiddleware>();
|
|
||||||
|
|
||||||
// Request logging middleware (when DEBUG_LOG_ALL_REQUESTS=true)
|
// Request logging middleware (when DEBUG_LOG_ALL_REQUESTS=true)
|
||||||
app.UseMiddleware<RequestLoggingMiddleware>();
|
app.UseMiddleware<RequestLoggingMiddleware>();
|
||||||
|
|
||||||
|
|||||||
@@ -28,18 +28,7 @@ public static class AuthHeaderHelper
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Some Jellyfin clients send the raw token separately instead of a MediaBrowser auth header.
|
|
||||||
foreach (var header in sourceHeaders)
|
|
||||||
{
|
|
||||||
if (header.Key.Equals("X-Emby-Token", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
var headerValue = header.Value.ToString();
|
|
||||||
targetRequest.Headers.TryAddWithoutValidation("X-Emby-Token", headerValue);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If no X-Emby-Authorization, check if Authorization header contains MediaBrowser format
|
// If no X-Emby-Authorization, check if Authorization header contains MediaBrowser format
|
||||||
foreach (var header in sourceHeaders)
|
foreach (var header in sourceHeaders)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -467,18 +467,7 @@ public abstract class BaseDownloadService : IDownloadService
|
|||||||
Logger.LogDebug("Cleaned up failed download tracking for {SongId}", songId);
|
Logger.LogDebug("Cleaned up failed download tracking for {SongId}", songId);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (ex is HttpRequestException httpRequestException && httpRequestException.StatusCode.HasValue)
|
Logger.LogError(ex, "Download failed for {SongId}", songId);
|
||||||
{
|
|
||||||
Logger.LogError("Download failed for {SongId}: {StatusCode}: {ReasonPhrase}",
|
|
||||||
songId,
|
|
||||||
(int)httpRequestException.StatusCode.Value,
|
|
||||||
httpRequestException.StatusCode.Value);
|
|
||||||
Logger.LogDebug(ex, "Detailed download failure for {SongId}", songId);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Logger.LogError(ex, "Download failed for {SongId}", songId);
|
|
||||||
}
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
|
|||||||
@@ -1,107 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
|
|
||||||
namespace allstarr.Services.Common;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Identifies high-confidence internet scanner paths that should never hit Jellyfin.
|
|
||||||
/// </summary>
|
|
||||||
public static class BotProbeDetector
|
|
||||||
{
|
|
||||||
private static readonly string[] PrefixMatches =
|
|
||||||
{
|
|
||||||
".env",
|
|
||||||
".git",
|
|
||||||
".hg",
|
|
||||||
".svn",
|
|
||||||
"_ignition/",
|
|
||||||
"debug/default",
|
|
||||||
"vendor/",
|
|
||||||
"public/vendor/"
|
|
||||||
};
|
|
||||||
|
|
||||||
private static readonly string[] FragmentMatches =
|
|
||||||
{
|
|
||||||
"/.env",
|
|
||||||
"/.git/",
|
|
||||||
"/vendor/",
|
|
||||||
"phpunit",
|
|
||||||
"laravel-filemanager",
|
|
||||||
"eval-stdin.php"
|
|
||||||
};
|
|
||||||
|
|
||||||
private static readonly string[] SuffixMatches =
|
|
||||||
{
|
|
||||||
".php"
|
|
||||||
};
|
|
||||||
|
|
||||||
public static bool IsHighConfidenceProbePath(string? rawPath)
|
|
||||||
{
|
|
||||||
var path = NormalizePath(rawPath);
|
|
||||||
if (string.IsNullOrEmpty(path))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (path.Equals("wp", StringComparison.Ordinal) ||
|
|
||||||
path.StartsWith("wp-", StringComparison.Ordinal) ||
|
|
||||||
path.StartsWith("wp/", StringComparison.Ordinal) ||
|
|
||||||
path.Equals("wordpress", StringComparison.Ordinal) ||
|
|
||||||
path.StartsWith("wordpress/", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (PrefixMatches.Any(prefix => path.StartsWith(prefix, StringComparison.Ordinal)))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (FragmentMatches.Any(fragment => path.Contains(fragment, StringComparison.Ordinal)))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return SuffixMatches.Any(suffix => path.EndsWith(suffix, StringComparison.Ordinal));
|
|
||||||
}
|
|
||||||
|
|
||||||
public static bool IsHighConfidenceProbeUrl(string? rawUrlOrPath)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(rawUrlOrPath))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Uri.TryCreate(rawUrlOrPath, UriKind.Absolute, out var uri))
|
|
||||||
{
|
|
||||||
return IsHighConfidenceProbePath(uri.AbsolutePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
return IsHighConfidenceProbePath(rawUrlOrPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string NormalizePath(string? rawPath)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(rawPath))
|
|
||||||
{
|
|
||||||
return string.Empty;
|
|
||||||
}
|
|
||||||
|
|
||||||
var path = rawPath.Trim();
|
|
||||||
|
|
||||||
if (Uri.TryCreate(path, UriKind.Absolute, out var uri))
|
|
||||||
{
|
|
||||||
path = uri.AbsolutePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
path = Uri.UnescapeDataString(path)
|
|
||||||
.Replace('\\', '/')
|
|
||||||
.TrimStart('/');
|
|
||||||
|
|
||||||
while (path.Contains("//", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
path = path.Replace("//", "/", StringComparison.Ordinal);
|
|
||||||
}
|
|
||||||
|
|
||||||
return path.ToLower(CultureInfo.InvariantCulture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -22,8 +22,7 @@ public static class CacheKeyBuilder
|
|||||||
string? sortBy,
|
string? sortBy,
|
||||||
string? sortOrder,
|
string? sortOrder,
|
||||||
bool? recursive,
|
bool? recursive,
|
||||||
string? userId,
|
string? userId)
|
||||||
string? isFavorite = null)
|
|
||||||
{
|
{
|
||||||
var normalizedTerm = Normalize(searchTerm);
|
var normalizedTerm = Normalize(searchTerm);
|
||||||
var normalizedItemTypes = Normalize(itemTypes);
|
var normalizedItemTypes = Normalize(itemTypes);
|
||||||
@@ -31,10 +30,9 @@ public static class CacheKeyBuilder
|
|||||||
var normalizedSortBy = Normalize(sortBy);
|
var normalizedSortBy = Normalize(sortBy);
|
||||||
var normalizedSortOrder = Normalize(sortOrder);
|
var normalizedSortOrder = Normalize(sortOrder);
|
||||||
var normalizedUserId = Normalize(userId);
|
var normalizedUserId = Normalize(userId);
|
||||||
var normalizedIsFavorite = Normalize(isFavorite);
|
|
||||||
var normalizedRecursive = recursive.HasValue ? (recursive.Value ? "true" : "false") : string.Empty;
|
var normalizedRecursive = recursive.HasValue ? (recursive.Value ? "true" : "false") : string.Empty;
|
||||||
|
|
||||||
return $"search:{normalizedTerm}:{normalizedItemTypes}:{limit}:{startIndex}:{normalizedParentId}:{normalizedSortBy}:{normalizedSortOrder}:{normalizedRecursive}:{normalizedUserId}:{normalizedIsFavorite}";
|
return $"search:{normalizedTerm}:{normalizedItemTypes}:{limit}:{startIndex}:{normalizedParentId}:{normalizedSortBy}:{normalizedSortOrder}:{normalizedRecursive}:{normalizedUserId}";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Normalize(string? value)
|
private static string Normalize(string? value)
|
||||||
|
|||||||
@@ -235,7 +235,8 @@ public class RoundRobinFallbackHelper
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
LogEndpointFailure(baseUrl, ex, willRetry: attempt < orderedEndpoints.Count - 1);
|
_logger.LogError(ex, "{Service} request failed with endpoint {Endpoint}, trying next...",
|
||||||
|
_serviceName, baseUrl);
|
||||||
|
|
||||||
// Mark as unhealthy in cache
|
// Mark as unhealthy in cache
|
||||||
lock (_healthCacheLock)
|
lock (_healthCacheLock)
|
||||||
@@ -350,7 +351,8 @@ public class RoundRobinFallbackHelper
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
LogEndpointFailure(baseUrl, ex, willRetry: attempt < orderedEndpoints.Count - 1);
|
_logger.LogError(ex, "{Service} request failed with endpoint {Endpoint}, trying next...",
|
||||||
|
_serviceName, baseUrl);
|
||||||
|
|
||||||
// Mark as unhealthy in cache
|
// Mark as unhealthy in cache
|
||||||
lock (_healthCacheLock)
|
lock (_healthCacheLock)
|
||||||
@@ -369,110 +371,10 @@ public class RoundRobinFallbackHelper
|
|||||||
return defaultValue;
|
return defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Tries endpoints until one both succeeds and returns an acceptable result.
|
|
||||||
/// Unacceptable results continue to the next endpoint without poisoning health state.
|
|
||||||
/// </summary>
|
|
||||||
public async Task<T> TryWithFallbackAsync<T>(
|
|
||||||
Func<string, Task<T>> action,
|
|
||||||
Func<T, bool> isAcceptableResult,
|
|
||||||
T defaultValue)
|
|
||||||
{
|
|
||||||
if (isAcceptableResult == null)
|
|
||||||
{
|
|
||||||
throw new ArgumentNullException(nameof(isAcceptableResult));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get healthy endpoints first (with caching to avoid excessive checks)
|
|
||||||
var healthyEndpoints = await GetHealthyEndpointsAsync();
|
|
||||||
|
|
||||||
// Try healthy endpoints first, then fall back to all if needed
|
|
||||||
var endpointsToTry = healthyEndpoints.Count < _apiUrls.Count
|
|
||||||
? healthyEndpoints.Concat(_apiUrls.Except(healthyEndpoints)).ToList()
|
|
||||||
: healthyEndpoints;
|
|
||||||
|
|
||||||
var orderedEndpoints = BuildTryOrder(endpointsToTry);
|
|
||||||
|
|
||||||
for (int attempt = 0; attempt < orderedEndpoints.Count; attempt++)
|
|
||||||
{
|
|
||||||
var baseUrl = orderedEndpoints[attempt];
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Trying {Service} endpoint {Endpoint} (attempt {Attempt}/{Total})",
|
|
||||||
_serviceName, baseUrl, attempt + 1, orderedEndpoints.Count);
|
|
||||||
|
|
||||||
var result = await action(baseUrl);
|
|
||||||
if (isAcceptableResult(result))
|
|
||||||
{
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug("{Service} endpoint {Endpoint} returned an unacceptable result, trying next...",
|
|
||||||
_serviceName, baseUrl);
|
|
||||||
|
|
||||||
if (attempt == orderedEndpoints.Count - 1)
|
|
||||||
{
|
|
||||||
_logger.LogWarning("All {Count} {Service} endpoints returned unacceptable results, returning default value",
|
|
||||||
orderedEndpoints.Count, _serviceName);
|
|
||||||
return defaultValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
LogEndpointFailure(baseUrl, ex, willRetry: attempt < orderedEndpoints.Count - 1);
|
|
||||||
|
|
||||||
lock (_healthCacheLock)
|
|
||||||
{
|
|
||||||
_healthCache[baseUrl] = (false, DateTime.UtcNow);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (attempt == orderedEndpoints.Count - 1)
|
|
||||||
{
|
|
||||||
_logger.LogError("All {Count} {Service} endpoints failed, returning default value",
|
|
||||||
orderedEndpoints.Count, _serviceName);
|
|
||||||
return defaultValue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return defaultValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void LogEndpointFailure(string baseUrl, Exception ex, bool willRetry)
|
|
||||||
{
|
|
||||||
var message = BuildFailureSummary(ex);
|
|
||||||
|
|
||||||
if (willRetry)
|
|
||||||
{
|
|
||||||
_logger.LogWarning("{Service} request failed at {Endpoint}: {Error}. Trying next...",
|
|
||||||
_serviceName, baseUrl, message);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.LogError("{Service} request failed at {Endpoint}: {Error}",
|
|
||||||
_serviceName, baseUrl, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogDebug(ex, "{Service} detailed failure for endpoint {Endpoint}",
|
|
||||||
_serviceName, baseUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string BuildFailureSummary(Exception ex)
|
|
||||||
{
|
|
||||||
if (ex is HttpRequestException httpRequestException && httpRequestException.StatusCode.HasValue)
|
|
||||||
{
|
|
||||||
var statusCode = (int)httpRequestException.StatusCode.Value;
|
|
||||||
return $"{statusCode}: {httpRequestException.StatusCode.Value}";
|
|
||||||
}
|
|
||||||
|
|
||||||
return ex.Message;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Processes multiple items in parallel across all available endpoints.
|
/// Processes multiple items in parallel across all available endpoints.
|
||||||
/// Each endpoint processes items sequentially. Failed endpoints are blacklisted.
|
/// Each endpoint processes items sequentially. Failed endpoints are blacklisted.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task<List<TResult>> ProcessInParallelAsync<TItem, TResult>(
|
public async Task<List<TResult>> ProcessInParallelAsync<TItem, TResult>(
|
||||||
List<TItem> items,
|
List<TItem> items,
|
||||||
Func<string, TItem, CancellationToken, Task<TResult>> action,
|
Func<string, TItem, CancellationToken, Task<TResult>> action,
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using allstarr.Models.Settings;
|
using allstarr.Models.Settings;
|
||||||
using allstarr.Services.Common;
|
using allstarr.Services.Common;
|
||||||
using System.Net;
|
|
||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
@@ -210,9 +209,14 @@ public class JellyfinProxyService
|
|||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
if (!isBrowserStaticRequest && !isPublicEndpoint)
|
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||||
{
|
{
|
||||||
LogUpstreamFailure(HttpMethod.Get, response.StatusCode, url);
|
// 401 means token expired or invalid - client needs to re-authenticate
|
||||||
|
_logger.LogDebug("Jellyfin returned 401 Unauthorized for {Url} - client should re-authenticate", url);
|
||||||
|
}
|
||||||
|
else if (!isBrowserStaticRequest && !isPublicEndpoint)
|
||||||
|
{
|
||||||
|
_logger.LogError("Jellyfin request failed: {StatusCode} for {Url}", response.StatusCode, url);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to parse error response to pass through to client
|
// Try to parse error response to pass through to client
|
||||||
@@ -306,7 +310,17 @@ public class JellyfinProxyService
|
|||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
var errorContent = await response.Content.ReadAsStringAsync();
|
var errorContent = await response.Content.ReadAsStringAsync();
|
||||||
LogUpstreamFailure(HttpMethod.Post, response.StatusCode, url, errorContent);
|
|
||||||
|
// 401 is expected when tokens expire - don't spam logs
|
||||||
|
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Jellyfin POST returned 401 for {Url} - client should re-authenticate", url);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogError("Jellyfin POST request failed: {StatusCode} for {Url}. Response: {Response}",
|
||||||
|
response.StatusCode, url, errorContent.Length > 200 ? errorContent[..200] + "..." : errorContent);
|
||||||
|
}
|
||||||
|
|
||||||
// Try to parse error response as JSON to pass through to client
|
// Try to parse error response as JSON to pass through to client
|
||||||
if (!string.IsNullOrWhiteSpace(errorContent))
|
if (!string.IsNullOrWhiteSpace(errorContent))
|
||||||
@@ -441,7 +455,8 @@ public class JellyfinProxyService
|
|||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
var errorContent = await response.Content.ReadAsStringAsync();
|
var errorContent = await response.Content.ReadAsStringAsync();
|
||||||
LogUpstreamFailure(HttpMethod.Delete, response.StatusCode, url, errorContent);
|
_logger.LogError("Jellyfin DELETE request failed: {StatusCode} for {Url}. Response: {Response}",
|
||||||
|
response.StatusCode, url, errorContent);
|
||||||
return (null, statusCode);
|
return (null, statusCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -900,62 +915,6 @@ public class JellyfinProxyService
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LogUpstreamFailure(HttpMethod method, HttpStatusCode statusCode, string url, string? responseBody = null)
|
|
||||||
{
|
|
||||||
if (statusCode == HttpStatusCode.Unauthorized)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Jellyfin {Method} returned 401 for {Url} - client should re-authenticate",
|
|
||||||
method.Method, url);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var isLikelyBotProbe = BotProbeDetector.IsHighConfidenceProbeUrl(url);
|
|
||||||
|
|
||||||
if (statusCode == HttpStatusCode.NotFound)
|
|
||||||
{
|
|
||||||
if (isLikelyBotProbe)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Likely bot probe returned 404 for {Url}", url);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.LogDebug("Jellyfin {Method} returned 404 for {Url}", method.Method, url);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var responsePreview = string.IsNullOrWhiteSpace(responseBody)
|
|
||||||
? null
|
|
||||||
: responseBody.Length > 200 ? responseBody[..200] + "..." : responseBody;
|
|
||||||
|
|
||||||
if (isLikelyBotProbe)
|
|
||||||
{
|
|
||||||
if (responsePreview == null)
|
|
||||||
{
|
|
||||||
_logger.LogWarning("Likely bot probe returned {StatusCode} for {Url}", statusCode, url);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.LogWarning("Likely bot probe returned {StatusCode} for {Url}. Response: {Response}",
|
|
||||||
statusCode, url, responsePreview);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (responsePreview == null)
|
|
||||||
{
|
|
||||||
_logger.LogError("Jellyfin {Method} request failed: {StatusCode} for {Url}",
|
|
||||||
method.Method, statusCode, url);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_logger.LogError("Jellyfin {Method} request failed: {StatusCode} for {Url}. Response: {Response}",
|
|
||||||
method.Method, statusCode, url, responsePreview);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends a GET request to the Jellyfin server using the server's API key for internal operations.
|
/// Sends a GET request to the Jellyfin server using the server's API key for internal operations.
|
||||||
/// This should only be used for server-side operations, not for proxying client requests.
|
/// This should only be used for server-side operations, not for proxying client requests.
|
||||||
|
|||||||
@@ -294,7 +294,7 @@ public class JellyfinResponseBuilder
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public Dictionary<string, object?> ConvertSongToJellyfinItem(Song song)
|
public Dictionary<string, object?> ConvertSongToJellyfinItem(Song song)
|
||||||
{
|
{
|
||||||
// Add external/explicit labels to song titles for external tracks.
|
// Add " [S]" suffix to external song titles (S = streaming source)
|
||||||
var songTitle = song.Title;
|
var songTitle = song.Title;
|
||||||
var artistName = song.Artist;
|
var artistName = song.Artist;
|
||||||
var albumName = song.Album;
|
var albumName = song.Album;
|
||||||
@@ -302,7 +302,7 @@ public class JellyfinResponseBuilder
|
|||||||
|
|
||||||
if (!song.IsLocal)
|
if (!song.IsLocal)
|
||||||
{
|
{
|
||||||
songTitle = BuildExternalSongTitle(song);
|
songTitle = $"{song.Title} [S]";
|
||||||
|
|
||||||
// Also add [S] to artist and album names for consistency
|
// Also add [S] to artist and album names for consistency
|
||||||
if (!string.IsNullOrEmpty(artistName) && !artistName.EndsWith(" [S]"))
|
if (!string.IsNullOrEmpty(artistName) && !artistName.EndsWith(" [S]"))
|
||||||
@@ -502,18 +502,6 @@ public class JellyfinResponseBuilder
|
|||||||
return item;
|
return item;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string BuildExternalSongTitle(Song song)
|
|
||||||
{
|
|
||||||
var title = $"{song.Title} [S]";
|
|
||||||
|
|
||||||
if (song.ExplicitContentLyrics == 1)
|
|
||||||
{
|
|
||||||
title = $"{title} [E]";
|
|
||||||
}
|
|
||||||
|
|
||||||
return title;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool ShouldDisableTranscoding(string provider)
|
private static bool ShouldDisableTranscoding(string provider)
|
||||||
{
|
{
|
||||||
return provider.Equals("deezer", StringComparison.OrdinalIgnoreCase) ||
|
return provider.Equals("deezer", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
|||||||
@@ -298,16 +298,32 @@ public class JellyfinSessionManager : IDisposable
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Marks a session as potentially ended (e.g., after playback stops).
|
/// Marks a session as potentially ended (e.g., after playback stops).
|
||||||
/// Jellyfin should decide when the upstream playback session expires.
|
/// The session will be cleaned up if no new activity occurs within the timeout.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void MarkSessionPotentiallyEnded(string deviceId, TimeSpan timeout)
|
public void MarkSessionPotentiallyEnded(string deviceId, TimeSpan timeout)
|
||||||
{
|
{
|
||||||
if (_sessions.TryGetValue(deviceId, out _))
|
if (_sessions.TryGetValue(deviceId, out var session))
|
||||||
{
|
{
|
||||||
_logger.LogDebug(
|
_logger.LogDebug("⏰ SESSION: Marking session {DeviceId} as potentially ended, will cleanup in {Seconds}s if no activity",
|
||||||
"⏰ SESSION: Playback stopped for {DeviceId}; leaving upstream session lifetime to Jellyfin (timeout hint {Seconds}s ignored)",
|
deviceId, timeout.TotalSeconds);
|
||||||
deviceId,
|
|
||||||
timeout.TotalSeconds);
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
var markedTime = DateTime.UtcNow;
|
||||||
|
await Task.Delay(timeout);
|
||||||
|
|
||||||
|
// Check if there's been activity since we marked it
|
||||||
|
if (_sessions.TryGetValue(deviceId, out var currentSession) &&
|
||||||
|
currentSession.LastActivity <= markedTime)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("🧹 SESSION: Auto-removing inactive session {DeviceId} after playback stop", deviceId);
|
||||||
|
await RemoveSessionAsync(deviceId);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_logger.LogDebug("✓ SESSION: Session {DeviceId} had activity, keeping alive", deviceId);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -382,7 +398,8 @@ public class JellyfinSessionManager : IDisposable
|
|||||||
deviceId, session.LastPlayingItemId, session.LastPlayingPositionTicks);
|
deviceId, session.LastPlayingItemId, session.LastPlayingPositionTicks);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let Jellyfin retire the session naturally; internal cleanup must not revoke the user's token.
|
// Notify Jellyfin that the session is ending
|
||||||
|
await _proxyService.PostJsonAsync("Sessions/Logout", "{}", session.Headers);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -435,12 +452,6 @@ public class JellyfinSessionManager : IDisposable
|
|||||||
_logger.LogDebug("🔑 WEBSOCKET: Using X-Emby-Authorization for {DeviceId}", deviceId);
|
_logger.LogDebug("🔑 WEBSOCKET: Using X-Emby-Authorization for {DeviceId}", deviceId);
|
||||||
authFound = true;
|
authFound = true;
|
||||||
}
|
}
|
||||||
else if (sessionHeaders.TryGetValue("X-Emby-Token", out var token))
|
|
||||||
{
|
|
||||||
webSocket.Options.SetRequestHeader("X-Emby-Token", token.ToString());
|
|
||||||
_logger.LogDebug("🔑 WEBSOCKET: Using X-Emby-Token for {DeviceId}", deviceId);
|
|
||||||
authFound = true;
|
|
||||||
}
|
|
||||||
else if (sessionHeaders.TryGetValue("Authorization", out var auth))
|
else if (sessionHeaders.TryGetValue("Authorization", out var auth))
|
||||||
{
|
{
|
||||||
var authValue = auth.ToString();
|
var authValue = auth.ToString();
|
||||||
|
|||||||
@@ -100,12 +100,8 @@ public class SquidWTFDownloadService : BaseDownloadService
|
|||||||
{
|
{
|
||||||
var downloadInfo = await GetTrackDownloadInfoAsync(trackId, cancellationToken);
|
var downloadInfo = await GetTrackDownloadInfoAsync(trackId, cancellationToken);
|
||||||
|
|
||||||
Logger.LogInformation(
|
Logger.LogInformation("Track download URL obtained from hifi-api: {Url}", downloadInfo.DownloadUrl);
|
||||||
"Track download info resolved via {Endpoint} (Format: {Format}, Quality: {Quality})",
|
Logger.LogInformation("Using format: {Format} (Quality: {Quality})", downloadInfo.MimeType, downloadInfo.AudioQuality);
|
||||||
downloadInfo.Endpoint,
|
|
||||||
downloadInfo.MimeType,
|
|
||||||
downloadInfo.AudioQuality);
|
|
||||||
Logger.LogDebug("Resolved SquidWTF CDN download URL: {Url}", downloadInfo.DownloadUrl);
|
|
||||||
|
|
||||||
// Determine extension from MIME type
|
// Determine extension from MIME type
|
||||||
var extension = downloadInfo.MimeType?.ToLower() switch
|
var extension = downloadInfo.MimeType?.ToLower() switch
|
||||||
@@ -131,11 +127,65 @@ public class SquidWTFDownloadService : BaseDownloadService
|
|||||||
// Resolve unique path if file already exists
|
// Resolve unique path if file already exists
|
||||||
outputPath = PathHelper.ResolveUniquePath(outputPath);
|
outputPath = PathHelper.ResolveUniquePath(outputPath);
|
||||||
|
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, downloadInfo.DownloadUrl);
|
// Use round-robin with fallback for downloads to reduce CPU usage
|
||||||
request.Headers.Add("User-Agent", "Mozilla/5.0");
|
Logger.LogDebug("Using round-robin endpoint selection for download");
|
||||||
request.Headers.Add("Accept", "*/*");
|
|
||||||
|
var response = await _fallbackHelper.TryWithFallbackAsync(async (baseUrl) =>
|
||||||
using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
{
|
||||||
|
// Map quality settings to Tidal's quality levels per hifi-api spec
|
||||||
|
var quality = _squidwtfSettings.Quality?.ToUpperInvariant() switch
|
||||||
|
{
|
||||||
|
"FLAC" => "LOSSLESS",
|
||||||
|
"HI_RES" => "HI_RES_LOSSLESS",
|
||||||
|
"LOSSLESS" => "LOSSLESS",
|
||||||
|
"HIGH" => "HIGH",
|
||||||
|
"LOW" => "LOW",
|
||||||
|
_ => "LOSSLESS"
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{baseUrl}/track/?id={trackId}&quality={quality}";
|
||||||
|
|
||||||
|
Logger.LogDebug("Requesting track download info: {Url}", url);
|
||||||
|
|
||||||
|
// Get download info from this endpoint
|
||||||
|
var infoResponse = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
|
|
||||||
|
if (!infoResponse.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
Logger.LogWarning("Track download request failed: {StatusCode} {Url}", infoResponse.StatusCode, url);
|
||||||
|
infoResponse.EnsureSuccessStatusCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
var json = await infoResponse.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
var doc = JsonDocument.Parse(json);
|
||||||
|
|
||||||
|
if (!doc.RootElement.TryGetProperty("data", out var data))
|
||||||
|
{
|
||||||
|
throw new Exception("Invalid response from API");
|
||||||
|
}
|
||||||
|
|
||||||
|
var manifestBase64 = data.GetProperty("manifest").GetString()
|
||||||
|
?? throw new Exception("No manifest in response");
|
||||||
|
|
||||||
|
// Decode base64 manifest to get actual CDN URL
|
||||||
|
var manifestJson = Encoding.UTF8.GetString(Convert.FromBase64String(manifestBase64));
|
||||||
|
var manifest = JsonDocument.Parse(manifestJson);
|
||||||
|
|
||||||
|
if (!manifest.RootElement.TryGetProperty("urls", out var urls) || urls.GetArrayLength() == 0)
|
||||||
|
{
|
||||||
|
throw new Exception("No download URLs in manifest");
|
||||||
|
}
|
||||||
|
|
||||||
|
var downloadUrl = urls[0].GetString()
|
||||||
|
?? throw new Exception("Download URL is null");
|
||||||
|
|
||||||
|
// Start the actual download from Tidal CDN (no encryption - squid.wtf handles everything)
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
|
||||||
|
request.Headers.Add("User-Agent", "Mozilla/5.0");
|
||||||
|
request.Headers.Add("Accept", "*/*");
|
||||||
|
|
||||||
|
return await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||||
|
});
|
||||||
|
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
@@ -185,139 +235,81 @@ public class SquidWTFDownloadService : BaseDownloadService
|
|||||||
/// The manifest is base64-encoded JSON containing: { mimeType, codecs, encryptionType, urls: [downloadUrl] }
|
/// The manifest is base64-encoded JSON containing: { mimeType, codecs, encryptionType, urls: [downloadUrl] }
|
||||||
/// Quality options: HI_RES_LOSSLESS (24-bit/192kHz FLAC), LOSSLESS (16-bit/44.1kHz FLAC), HIGH (320kbps AAC), LOW (96kbps AAC)
|
/// Quality options: HI_RES_LOSSLESS (24-bit/192kHz FLAC), LOSSLESS (16-bit/44.1kHz FLAC), HIGH (320kbps AAC), LOW (96kbps AAC)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<DownloadResult> GetTrackDownloadInfoAsync(string trackId, CancellationToken cancellationToken)
|
private async Task<DownloadResult> GetTrackDownloadInfoAsync(string trackId, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
return await QueueRequestAsync(async () =>
|
return await QueueRequestAsync(async () =>
|
||||||
{
|
{
|
||||||
Exception? lastException = null;
|
// Use round-robin with fallback instead of racing to reduce CPU usage
|
||||||
var qualityOrder = BuildQualityFallbackOrder(_squidwtfSettings.Quality);
|
return await _fallbackHelper.TryWithFallbackAsync(async (baseUrl) =>
|
||||||
|
|
||||||
foreach (var quality in qualityOrder)
|
|
||||||
{
|
{
|
||||||
try
|
// Map quality settings to Tidal's quality levels per hifi-api spec
|
||||||
|
var quality = _squidwtfSettings.Quality?.ToUpperInvariant() switch
|
||||||
{
|
{
|
||||||
return await _fallbackHelper.TryWithFallbackAsync(baseUrl =>
|
"FLAC" => "LOSSLESS",
|
||||||
FetchTrackDownloadInfoAsync(baseUrl, trackId, quality, cancellationToken));
|
"HI_RES" => "HI_RES_LOSSLESS",
|
||||||
}
|
"LOSSLESS" => "LOSSLESS",
|
||||||
catch (Exception ex)
|
"HIGH" => "HIGH",
|
||||||
|
"LOW" => "LOW",
|
||||||
|
_ => "LOSSLESS" // Default to lossless
|
||||||
|
};
|
||||||
|
|
||||||
|
var url = $"{baseUrl}/track/?id={trackId}&quality={quality}";
|
||||||
|
|
||||||
|
Logger.LogDebug("Fetching track download info from: {Url}", url);
|
||||||
|
|
||||||
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
lastException = ex;
|
Logger.LogWarning("Track download info request failed: {StatusCode} {Url}", response.StatusCode, url);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
if (!string.Equals(quality, qualityOrder[^1], StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
Logger.LogWarning(
|
|
||||||
"Track {TrackId} unavailable at SquidWTF quality {Quality}: {Error}. Trying lower quality",
|
|
||||||
trackId,
|
|
||||||
quality,
|
|
||||||
DescribeException(ex));
|
|
||||||
Logger.LogDebug(ex,
|
|
||||||
"Detailed SquidWTF quality failure for track {TrackId} at quality {Quality}",
|
|
||||||
trackId,
|
|
||||||
quality);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
throw lastException ?? new Exception($"Unable to fetch SquidWTF download info for track {trackId}");
|
var doc = JsonDocument.Parse(json);
|
||||||
|
|
||||||
|
if (!doc.RootElement.TryGetProperty("data", out var data))
|
||||||
|
{
|
||||||
|
throw new Exception("Invalid response from API");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the manifest (base64 encoded JSON containing the actual CDN URL)
|
||||||
|
var manifestBase64 = data.GetProperty("manifest").GetString()
|
||||||
|
?? throw new Exception("No manifest in response");
|
||||||
|
|
||||||
|
// Decode the manifest
|
||||||
|
var manifestJson = Encoding.UTF8.GetString(Convert.FromBase64String(manifestBase64));
|
||||||
|
var manifest = JsonDocument.Parse(manifestJson);
|
||||||
|
|
||||||
|
// Extract the download URL from the manifest
|
||||||
|
if (!manifest.RootElement.TryGetProperty("urls", out var urls) || urls.GetArrayLength() == 0)
|
||||||
|
{
|
||||||
|
throw new Exception("No download URLs in manifest");
|
||||||
|
}
|
||||||
|
|
||||||
|
var downloadUrl = urls[0].GetString()
|
||||||
|
?? throw new Exception("Download URL is null");
|
||||||
|
|
||||||
|
var mimeType = manifest.RootElement.TryGetProperty("mimeType", out var mimeTypeEl)
|
||||||
|
? mimeTypeEl.GetString()
|
||||||
|
: "audio/flac";
|
||||||
|
|
||||||
|
var audioQuality = data.TryGetProperty("audioQuality", out var audioQualityEl)
|
||||||
|
? audioQualityEl.GetString()
|
||||||
|
: "LOSSLESS";
|
||||||
|
|
||||||
|
Logger.LogInformation("Track download URL obtained from hifi-api: {Url}", downloadUrl);
|
||||||
|
|
||||||
|
return new DownloadResult
|
||||||
|
{
|
||||||
|
DownloadUrl = downloadUrl,
|
||||||
|
MimeType = mimeType ?? "audio/flac",
|
||||||
|
AudioQuality = audioQuality ?? "LOSSLESS"
|
||||||
|
};
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<DownloadResult> FetchTrackDownloadInfoAsync(
|
|
||||||
string baseUrl,
|
|
||||||
string trackId,
|
|
||||||
string quality,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var url = $"{baseUrl}/track/?id={trackId}&quality={quality}";
|
|
||||||
|
|
||||||
Logger.LogDebug("Fetching track download info from: {Url}", url);
|
|
||||||
|
|
||||||
using var response = await _httpClient.GetAsync(url, cancellationToken);
|
|
||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
|
||||||
{
|
|
||||||
response.EnsureSuccessStatusCode();
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
|
||||||
using var doc = JsonDocument.Parse(json);
|
|
||||||
|
|
||||||
if (!doc.RootElement.TryGetProperty("data", out var data))
|
|
||||||
{
|
|
||||||
throw new Exception("Invalid response from API");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get the manifest (base64 encoded JSON containing the actual CDN URL)
|
|
||||||
var manifestBase64 = data.GetProperty("manifest").GetString()
|
|
||||||
?? throw new Exception("No manifest in response");
|
|
||||||
|
|
||||||
// Decode the manifest
|
|
||||||
var manifestJson = Encoding.UTF8.GetString(Convert.FromBase64String(manifestBase64));
|
|
||||||
using var manifest = JsonDocument.Parse(manifestJson);
|
|
||||||
|
|
||||||
// Extract the download URL from the manifest
|
|
||||||
if (!manifest.RootElement.TryGetProperty("urls", out var urls) || urls.GetArrayLength() == 0)
|
|
||||||
{
|
|
||||||
throw new Exception("No download URLs in manifest");
|
|
||||||
}
|
|
||||||
|
|
||||||
var downloadUrl = urls[0].GetString()
|
|
||||||
?? throw new Exception("Download URL is null");
|
|
||||||
|
|
||||||
var mimeType = manifest.RootElement.TryGetProperty("mimeType", out var mimeTypeEl)
|
|
||||||
? mimeTypeEl.GetString()
|
|
||||||
: "audio/flac";
|
|
||||||
|
|
||||||
var audioQuality = data.TryGetProperty("audioQuality", out var audioQualityEl)
|
|
||||||
? audioQualityEl.GetString()
|
|
||||||
: quality;
|
|
||||||
|
|
||||||
return new DownloadResult
|
|
||||||
{
|
|
||||||
Endpoint = baseUrl,
|
|
||||||
DownloadUrl = downloadUrl,
|
|
||||||
MimeType = mimeType ?? "audio/flac",
|
|
||||||
AudioQuality = audioQuality ?? quality
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IReadOnlyList<string> BuildQualityFallbackOrder(string? configuredQuality)
|
|
||||||
{
|
|
||||||
return NormalizeQuality(configuredQuality) switch
|
|
||||||
{
|
|
||||||
"HI_RES_LOSSLESS" => ["HI_RES_LOSSLESS", "LOSSLESS", "HIGH", "LOW"],
|
|
||||||
"LOSSLESS" => ["LOSSLESS", "HIGH", "LOW"],
|
|
||||||
"HIGH" => ["HIGH", "LOW"],
|
|
||||||
"LOW" => ["LOW"],
|
|
||||||
_ => ["LOSSLESS", "HIGH", "LOW"]
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string NormalizeQuality(string? configuredQuality)
|
|
||||||
{
|
|
||||||
return configuredQuality?.ToUpperInvariant() switch
|
|
||||||
{
|
|
||||||
"FLAC" => "LOSSLESS",
|
|
||||||
"HI_RES" => "HI_RES_LOSSLESS",
|
|
||||||
"HI_RES_LOSSLESS" => "HI_RES_LOSSLESS",
|
|
||||||
"LOSSLESS" => "LOSSLESS",
|
|
||||||
"HIGH" => "HIGH",
|
|
||||||
"LOW" => "LOW",
|
|
||||||
_ => "LOSSLESS"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string DescribeException(Exception ex)
|
|
||||||
{
|
|
||||||
if (ex is HttpRequestException httpRequestException && httpRequestException.StatusCode.HasValue)
|
|
||||||
{
|
|
||||||
var statusCode = (int)httpRequestException.StatusCode.Value;
|
|
||||||
return $"{statusCode}: {httpRequestException.StatusCode.Value}";
|
|
||||||
}
|
|
||||||
|
|
||||||
return ex.Message;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -375,9 +367,8 @@ public class SquidWTFDownloadService : BaseDownloadService
|
|||||||
|
|
||||||
private class DownloadResult
|
private class DownloadResult
|
||||||
{
|
{
|
||||||
public string Endpoint { get; set; } = string.Empty;
|
|
||||||
public string DownloadUrl { get; set; } = string.Empty;
|
public string DownloadUrl { get; set; } = string.Empty;
|
||||||
public string MimeType { get; set; } = string.Empty;
|
public string MimeType { get; set; } = string.Empty;
|
||||||
public string AudioQuality { get; set; } = string.Empty;
|
public string AudioQuality { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -226,10 +226,6 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("SquidWTF song search response did not contain data.items");
|
|
||||||
}
|
|
||||||
return songs;
|
return songs;
|
||||||
}, new List<Song>());
|
}, new List<Song>());
|
||||||
}
|
}
|
||||||
@@ -267,10 +263,6 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("SquidWTF album search response did not contain data.albums.items");
|
|
||||||
}
|
|
||||||
|
|
||||||
return albums;
|
return albums;
|
||||||
}, new List<Album>());
|
}, new List<Album>());
|
||||||
@@ -296,12 +288,6 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var result = JsonDocument.Parse(json);
|
var result = JsonDocument.Parse(json);
|
||||||
|
|
||||||
if (result.RootElement.TryGetProperty("detail", out _) ||
|
|
||||||
result.RootElement.TryGetProperty("error", out _))
|
|
||||||
{
|
|
||||||
throw new HttpRequestException("API returned error response");
|
|
||||||
}
|
|
||||||
|
|
||||||
var artists = new List<Artist>();
|
var artists = new List<Artist>();
|
||||||
// Per hifi-api spec: artist search returns data.artists.items array
|
// Per hifi-api spec: artist search returns data.artists.items array
|
||||||
if (result.RootElement.TryGetProperty("data", out var data) &&
|
if (result.RootElement.TryGetProperty("data", out var data) &&
|
||||||
@@ -319,10 +305,6 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("SquidWTF artist search response did not contain data.artists.items");
|
|
||||||
}
|
|
||||||
|
|
||||||
return artists;
|
return artists;
|
||||||
}, new List<Artist>());
|
}, new List<Artist>());
|
||||||
@@ -363,20 +345,11 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
// Per hifi-api spec: use 'p' parameter for playlist search
|
// Per hifi-api spec: use 'p' parameter for playlist search
|
||||||
var url = $"{baseUrl}/search/?p={Uri.EscapeDataString(query)}";
|
var url = $"{baseUrl}/search/?p={Uri.EscapeDataString(query)}";
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode) return new List<ExternalPlaylist>();
|
||||||
{
|
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var result = JsonDocument.Parse(json);
|
var result = JsonDocument.Parse(json);
|
||||||
|
|
||||||
if (result.RootElement.TryGetProperty("detail", out _) ||
|
|
||||||
result.RootElement.TryGetProperty("error", out _))
|
|
||||||
{
|
|
||||||
throw new HttpRequestException("API returned error response");
|
|
||||||
}
|
|
||||||
|
|
||||||
var playlists = new List<ExternalPlaylist>();
|
var playlists = new List<ExternalPlaylist>();
|
||||||
// Per hifi-api spec: playlist search returns data.playlists.items array
|
// Per hifi-api spec: playlist search returns data.playlists.items array
|
||||||
if (result.RootElement.TryGetProperty("data", out var data) &&
|
if (result.RootElement.TryGetProperty("data", out var data) &&
|
||||||
@@ -397,13 +370,9 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
{
|
{
|
||||||
_logger.LogWarning(ex, "Failed to parse playlist, skipping");
|
_logger.LogWarning(ex, "Failed to parse playlist, skipping");
|
||||||
// Skip this playlist and continue with others
|
// Skip this playlist and continue with others
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
}
|
||||||
{
|
|
||||||
throw new InvalidOperationException("SquidWTF playlist search response did not contain data.playlists.items");
|
|
||||||
}
|
|
||||||
return playlists;
|
return playlists;
|
||||||
}, new List<ExternalPlaylist>());
|
}, new List<ExternalPlaylist>());
|
||||||
}
|
}
|
||||||
@@ -437,19 +406,14 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
var url = $"{baseUrl}/info/?id={externalId}";
|
var url = $"{baseUrl}/info/?id={externalId}";
|
||||||
|
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode) return null;
|
||||||
{
|
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var result = JsonDocument.Parse(json);
|
var result = JsonDocument.Parse(json);
|
||||||
|
|
||||||
// Per hifi-api spec: response is { "version": "2.0", "data": { track object } }
|
// Per hifi-api spec: response is { "version": "2.0", "data": { track object } }
|
||||||
if (!result.RootElement.TryGetProperty("data", out var track))
|
if (!result.RootElement.TryGetProperty("data", out var track))
|
||||||
{
|
return null;
|
||||||
throw new InvalidOperationException($"SquidWTF /info response for track {externalId} did not contain data");
|
|
||||||
}
|
|
||||||
|
|
||||||
var song = ParseTidalTrackFull(track);
|
var song = ParseTidalTrackFull(track);
|
||||||
|
|
||||||
@@ -481,96 +445,84 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
{
|
{
|
||||||
if (string.IsNullOrWhiteSpace(externalId)) return new List<Song>();
|
if (string.IsNullOrWhiteSpace(externalId)) return new List<Song>();
|
||||||
|
|
||||||
return await _fallbackHelper.TryWithFallbackAsync(
|
return await _fallbackHelper.TryWithFallbackAsync(async (baseUrl) =>
|
||||||
async (baseUrl) =>
|
{
|
||||||
|
var url = $"{baseUrl}/recommendations/?id={Uri.EscapeDataString(externalId)}";
|
||||||
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
|
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
var url = $"{baseUrl}/recommendations/?id={Uri.EscapeDataString(externalId)}";
|
_logger.LogDebug("SquidWTF recommendations request failed for track {TrackId} with status {StatusCode}",
|
||||||
if (limit > 0)
|
externalId, response.StatusCode);
|
||||||
|
return new List<Song>();
|
||||||
|
}
|
||||||
|
|
||||||
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
|
var result = JsonDocument.Parse(json);
|
||||||
|
|
||||||
|
if (!result.RootElement.TryGetProperty("data", out var data) ||
|
||||||
|
!data.TryGetProperty("items", out var items) ||
|
||||||
|
items.ValueKind != JsonValueKind.Array)
|
||||||
|
{
|
||||||
|
return new List<Song>();
|
||||||
|
}
|
||||||
|
|
||||||
|
var songs = new List<Song>();
|
||||||
|
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
foreach (var recommendation in items.EnumerateArray())
|
||||||
|
{
|
||||||
|
JsonElement track;
|
||||||
|
if (recommendation.TryGetProperty("track", out var wrappedTrack))
|
||||||
{
|
{
|
||||||
url += $"&limit={limit}";
|
track = wrappedTrack;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
track = recommendation;
|
||||||
}
|
}
|
||||||
|
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
if (!track.TryGetProperty("id", out _))
|
||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
|
||||||
{
|
{
|
||||||
throw new HttpRequestException(
|
continue;
|
||||||
$"SquidWTF recommendations request failed for track {externalId} with status {response.StatusCode}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
Song song;
|
||||||
var result = JsonDocument.Parse(json);
|
try
|
||||||
|
|
||||||
if (!result.RootElement.TryGetProperty("data", out var data) ||
|
|
||||||
!data.TryGetProperty("items", out var items) ||
|
|
||||||
items.ValueKind != JsonValueKind.Array)
|
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException(
|
song = ParseTidalTrack(track);
|
||||||
$"SquidWTF recommendations response for track {externalId} did not contain data.items");
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var songs = new List<Song>();
|
if (string.Equals(song.ExternalId, externalId, StringComparison.OrdinalIgnoreCase))
|
||||||
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
foreach (var recommendation in items.EnumerateArray())
|
|
||||||
{
|
{
|
||||||
JsonElement track;
|
continue;
|
||||||
if (recommendation.TryGetProperty("track", out var wrappedTrack))
|
|
||||||
{
|
|
||||||
track = wrappedTrack;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
track = recommendation;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!track.TryGetProperty("id", out _))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
Song song;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
song = ParseTidalTrack(track);
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.Equals(song.ExternalId, externalId, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var songKey = !string.IsNullOrWhiteSpace(song.ExternalId) ? song.ExternalId : song.Id;
|
|
||||||
if (string.IsNullOrWhiteSpace(songKey) || !seenIds.Add(songKey))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ShouldIncludeSong(song))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
songs.Add(song);
|
|
||||||
if (songs.Count >= limit)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_logger.LogDebug(
|
var songKey = !string.IsNullOrWhiteSpace(song.ExternalId) ? song.ExternalId : song.Id;
|
||||||
"SQUIDWTF: Recommendations returned {Count} songs for track {TrackId} from {BaseUrl}",
|
if (string.IsNullOrWhiteSpace(songKey) || !seenIds.Add(songKey))
|
||||||
songs.Count,
|
{
|
||||||
externalId,
|
continue;
|
||||||
baseUrl);
|
}
|
||||||
return songs;
|
|
||||||
},
|
if (!ShouldIncludeSong(song))
|
||||||
songs => songs.Count > 0,
|
{
|
||||||
new List<Song>());
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
songs.Add(song);
|
||||||
|
if (songs.Count >= limit)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogDebug("SQUIDWTF: Recommendations returned {Count} songs for track {TrackId}", songs.Count, externalId);
|
||||||
|
return songs;
|
||||||
|
}, new List<Song>());
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Album?> GetAlbumAsync(string externalProvider, string externalId, CancellationToken cancellationToken = default)
|
public async Task<Album?> GetAlbumAsync(string externalProvider, string externalId, CancellationToken cancellationToken = default)
|
||||||
@@ -588,19 +540,14 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
var url = $"{baseUrl}/album/?id={externalId}";
|
var url = $"{baseUrl}/album/?id={externalId}";
|
||||||
|
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode) return null;
|
||||||
{
|
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var result = JsonDocument.Parse(json);
|
var result = JsonDocument.Parse(json);
|
||||||
|
|
||||||
// Response structure: { "data": { album object with "items" array of tracks } }
|
// Response structure: { "data": { album object with "items" array of tracks } }
|
||||||
if (!result.RootElement.TryGetProperty("data", out var albumElement))
|
if (!result.RootElement.TryGetProperty("data", out var albumElement))
|
||||||
{
|
return null;
|
||||||
throw new InvalidOperationException($"SquidWTF /album response for album {externalId} did not contain data");
|
|
||||||
}
|
|
||||||
|
|
||||||
var album = ParseTidalAlbum(albumElement);
|
var album = ParseTidalAlbum(albumElement);
|
||||||
|
|
||||||
@@ -652,7 +599,8 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
_logger.LogError("SquidWTF artist request failed with status {StatusCode}", response.StatusCode);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
@@ -689,9 +637,9 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
|
|
||||||
if (artistSource == null)
|
if (artistSource == null)
|
||||||
{
|
{
|
||||||
var keys = string.Join(", ", result.RootElement.EnumerateObject().Select(p => p.Name));
|
_logger.LogDebug("Could not find artist data in response. Response keys: {Keys}",
|
||||||
throw new InvalidOperationException(
|
string.Join(", ", result.RootElement.EnumerateObject().Select(p => p.Name)));
|
||||||
$"SquidWTF artist response for {externalId} did not contain artist data. Keys: {keys}");
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var artistElement = artistSource.Value;
|
var artistElement = artistSource.Value;
|
||||||
@@ -739,7 +687,8 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
_logger.LogError("SquidWTF artist albums request failed with status {StatusCode}", response.StatusCode);
|
||||||
|
return new List<Album>();
|
||||||
}
|
}
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
@@ -763,8 +712,7 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException(
|
_logger.LogWarning("No albums found in response for artist {ExternalId}", externalId);
|
||||||
$"SquidWTF artist albums response for {externalId} did not contain albums.items");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return albums;
|
return albums;
|
||||||
@@ -786,7 +734,8 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
|
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode)
|
||||||
{
|
{
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
_logger.LogError("SquidWTF artist tracks request failed with status {StatusCode}", response.StatusCode);
|
||||||
|
return new List<Song>();
|
||||||
}
|
}
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
@@ -807,8 +756,7 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException(
|
_logger.LogWarning("No tracks found in response for artist {ExternalId}", externalId);
|
||||||
$"SquidWTF artist tracks response for {externalId} did not contain tracks");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return tracks;
|
return tracks;
|
||||||
@@ -824,26 +772,18 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
// Note: hifi-api doesn't document playlist endpoint, but /playlist/?id={playlistId} is commonly used
|
// Note: hifi-api doesn't document playlist endpoint, but /playlist/?id={playlistId} is commonly used
|
||||||
var url = $"{baseUrl}/playlist/?id={externalId}";
|
var url = $"{baseUrl}/playlist/?id={externalId}";
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode) return null;
|
||||||
{
|
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var rootElement = JsonDocument.Parse(json).RootElement;
|
var rootElement = JsonDocument.Parse(json).RootElement;
|
||||||
|
|
||||||
// Check for error response
|
// Check for error response
|
||||||
if (rootElement.TryGetProperty("error", out _))
|
if (rootElement.TryGetProperty("error", out _)) return null;
|
||||||
{
|
|
||||||
throw new InvalidOperationException($"SquidWTF playlist response for {externalId} contained an error payload");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Response structure: { "playlist": { playlist object }, "items": [ track wrappers ] }
|
// Response structure: { "playlist": { playlist object }, "items": [ track wrappers ] }
|
||||||
// Extract the playlist object from the response
|
// Extract the playlist object from the response
|
||||||
if (!rootElement.TryGetProperty("playlist", out var playlistElement))
|
if (!rootElement.TryGetProperty("playlist", out var playlistElement))
|
||||||
{
|
return null;
|
||||||
throw new InvalidOperationException($"SquidWTF playlist response for {externalId} did not contain playlist");
|
|
||||||
}
|
|
||||||
|
|
||||||
return ParseTidalPlaylist(playlistElement);
|
return ParseTidalPlaylist(playlistElement);
|
||||||
}, (ExternalPlaylist?)null);
|
}, (ExternalPlaylist?)null);
|
||||||
@@ -858,19 +798,13 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
// Note: hifi-api doesn't document playlist endpoint, but /playlist/?id={playlistId} is commonly used
|
// Note: hifi-api doesn't document playlist endpoint, but /playlist/?id={playlistId} is commonly used
|
||||||
var url = $"{baseUrl}/playlist/?id={externalId}";
|
var url = $"{baseUrl}/playlist/?id={externalId}";
|
||||||
var response = await _httpClient.GetAsync(url, cancellationToken);
|
var response = await _httpClient.GetAsync(url, cancellationToken);
|
||||||
if (!response.IsSuccessStatusCode)
|
if (!response.IsSuccessStatusCode) return new List<Song>();
|
||||||
{
|
|
||||||
throw new HttpRequestException($"HTTP {response.StatusCode}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
var json = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||||
var playlistElement = JsonDocument.Parse(json).RootElement;
|
var playlistElement = JsonDocument.Parse(json).RootElement;
|
||||||
|
|
||||||
// Check for error response
|
// Check for error response
|
||||||
if (playlistElement.TryGetProperty("error", out _))
|
if (playlistElement.TryGetProperty("error", out _)) return new List<Song>();
|
||||||
{
|
|
||||||
throw new InvalidOperationException($"SquidWTF playlist tracks response for {externalId} contained an error payload");
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonElement? playlist = null;
|
JsonElement? playlist = null;
|
||||||
JsonElement? tracks = null;
|
JsonElement? tracks = null;
|
||||||
@@ -886,12 +820,6 @@ public class SquidWTFMetadataService : TrackParserBase, IMusicMetadataService
|
|||||||
tracks = tracksEl;
|
tracks = tracksEl;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!tracks.HasValue)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"SquidWTF playlist tracks response for {externalId} did not contain items");
|
|
||||||
}
|
|
||||||
|
|
||||||
var songs = new List<Song>();
|
var songs = new List<Song>();
|
||||||
|
|
||||||
// Get playlist name for album field
|
// Get playlist name for album field
|
||||||
|
|||||||
+1
-1
@@ -77,7 +77,7 @@ services:
|
|||||||
- Redis__Enabled=${REDIS_ENABLED:-true}
|
- Redis__Enabled=${REDIS_ENABLED:-true}
|
||||||
|
|
||||||
# ===== CACHE TTL SETTINGS =====
|
# ===== CACHE TTL SETTINGS =====
|
||||||
- Cache__SearchResultsMinutes=${CACHE_SEARCH_RESULTS_MINUTES:-1}
|
- Cache__SearchResultsMinutes=${CACHE_SEARCH_RESULTS_MINUTES:-120}
|
||||||
- Cache__PlaylistImagesHours=${CACHE_PLAYLIST_IMAGES_HOURS:-168}
|
- Cache__PlaylistImagesHours=${CACHE_PLAYLIST_IMAGES_HOURS:-168}
|
||||||
- Cache__SpotifyPlaylistItemsHours=${CACHE_SPOTIFY_PLAYLIST_ITEMS_HOURS:-168}
|
- Cache__SpotifyPlaylistItemsHours=${CACHE_SPOTIFY_PLAYLIST_ITEMS_HOURS:-168}
|
||||||
- Cache__SpotifyMatchedTracksDays=${CACHE_SPOTIFY_MATCHED_TRACKS_DAYS:-30}
|
- Cache__SpotifyMatchedTracksDays=${CACHE_SPOTIFY_MATCHED_TRACKS_DAYS:-30}
|
||||||
|
|||||||
Reference in New Issue
Block a user