fix: address Copilot PR review findings

- Register DeezerDownloadService and DeezerMetadataService as Singleton
  to properly share state across requests (rate limiting, download tracking)
- Fix race condition in LocalLibraryService.LoadMappingsAsync with
  double-check locking pattern
- Dispose HttpRequestMessage objects to prevent memory leaks (4 occurrences)
- Handle fire-and-forget TriggerLibraryScanAsync with proper error logging
- Replace Console.WriteLine with ILogger in SubsonicController
- Fix while loop in DownloadSongAsync to refresh activeDownload state
- Use modern C# range operator syntax for Substring calls
- Clean up appsettings.json template (remove private IP, clear ARL token)
- Add documentation comment for Blowfish decryption key
- Add downloads directory to gitignore
This commit is contained in:
V1ck3s
2025-12-13 15:13:49 +01:00
committed by Vickes
parent 3a44a5782a
commit 88d8cbb376
6 changed files with 396 additions and 366 deletions

7
.gitignore vendored
View File

@@ -1,4 +1,4 @@
## A streamlined .gitignore for modern .NET projects
## A streamlined .gitignore for modern .NET projects
## including temporary files, build results, and
## files generated by popular .NET tools. If you are
## developing with Visual Studio, the VS .gitignore
@@ -68,4 +68,7 @@ obj/
# Autres fichiers temporaires
*.log
/.env
/.env
# Downloaded music files
octo-fiesta/downloads/

View File

@@ -17,19 +17,22 @@ public class SubsonicController : ControllerBase
private readonly IMusicMetadataService _metadataService;
private readonly ILocalLibraryService _localLibraryService;
private readonly IDownloadService _downloadService;
private readonly ILogger<SubsonicController> _logger;
public SubsonicController(
IHttpClientFactory httpClientFactory,
IOptions<SubsonicSettings> subsonicSettings,
IMusicMetadataService metadataService,
ILocalLibraryService localLibraryService,
IDownloadService downloadService)
IDownloadService downloadService,
ILogger<SubsonicController> logger)
{
_httpClient = httpClientFactory.CreateClient();
_subsonicSettings = subsonicSettings.Value;
_metadataService = metadataService;
_localLibraryService = localLibraryService;
_downloadService = downloadService;
_logger = logger;
if (string.IsNullOrWhiteSpace(_subsonicSettings.Url))
{
@@ -583,7 +586,7 @@ public class SubsonicController : ControllerBase
var query = string.Join("&", parameters.Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value)}"));
var url = $"{_subsonicSettings.Url}/rest/stream?{query}";
var request = new HttpRequestMessage(HttpMethod.Get, url);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, HttpContext.RequestAborted);
if (!response.IsSuccessStatusCode)
@@ -671,7 +674,7 @@ public class SubsonicController : ControllerBase
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing Subsonic response: {ex.Message}");
_logger.LogWarning(ex, "Error parsing Subsonic response");
}
}
@@ -831,14 +834,7 @@ public class SubsonicController : ControllerBase
["isExternal"] = !song.IsLocal
};
if (song.IsLocal)
{
result["bitRate"] = 128; // Default for local files
}
else
{
result["bitRate"] = 0;
}
result["bitRate"] = song.IsLocal ? 128 : 0; // Default bitrate for local files
return result;
}

View File

@@ -15,9 +15,10 @@ builder.Services.Configure<SubsonicSettings>(
builder.Configuration.GetSection("Subsonic"));
// Business services
// Registered as Singleton to share state (mappings cache, scan debounce, download tracking, rate limiting)
builder.Services.AddSingleton<ILocalLibraryService, LocalLibraryService>();
builder.Services.AddScoped<IMusicMetadataService, DeezerMetadataService>();
builder.Services.AddScoped<IDownloadService, DeezerDownloadService>();
builder.Services.AddSingleton<IMusicMetadataService, DeezerMetadataService>();
builder.Services.AddSingleton<IDownloadService, DeezerDownloadService>();
builder.Services.AddCors(options =>
{

View File

@@ -48,6 +48,9 @@ public class DeezerDownloadService : IDownloadService
private readonly int _minRequestIntervalMs = 200;
private const string DeezerApiBase = "https://api.deezer.com";
// Deezer's standard Blowfish CBC encryption key for track decryption
// This is a well-known constant used by the Deezer API, not a user-specific secret
private const string BfSecret = "g4el58wc0zvf9na1";
public DeezerDownloadService(
@@ -96,17 +99,17 @@ public class DeezerDownloadService : IDownloadService
if (_activeDownloads.TryGetValue(songId, out var activeDownload) && activeDownload.Status == DownloadStatus.InProgress)
{
_logger.LogInformation("Download already in progress for {SongId}", songId);
while (activeDownload.Status == DownloadStatus.InProgress)
while (_activeDownloads.TryGetValue(songId, out activeDownload) && activeDownload.Status == DownloadStatus.InProgress)
{
await Task.Delay(500, cancellationToken);
}
if (activeDownload.Status == DownloadStatus.Completed && activeDownload.LocalPath != null)
if (activeDownload?.Status == DownloadStatus.Completed && activeDownload.LocalPath != null)
{
return activeDownload.LocalPath;
}
throw new Exception(activeDownload.ErrorMessage ?? "Download failed");
throw new Exception(activeDownload?.ErrorMessage ?? "Download failed");
}
await _downloadLock.WaitAsync(cancellationToken);
@@ -141,7 +144,18 @@ public class DeezerDownloadService : IDownloadService
await _localLibraryService.RegisterDownloadedSongAsync(song, localPath);
// Trigger a Subsonic library rescan (with debounce)
_ = _localLibraryService.TriggerLibraryScanAsync();
// Fire-and-forget with error handling to prevent unobserved task exceptions
_ = Task.Run(async () =>
{
try
{
await _localLibraryService.TriggerLibraryScanAsync();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to trigger library scan after download");
}
});
_logger.LogInformation("Download completed: {Path}", localPath);
return localPath;
@@ -206,7 +220,7 @@ public class DeezerDownloadService : IDownloadService
await RetryWithBackoffAsync(async () =>
{
var request = new HttpRequestMessage(HttpMethod.Post,
using var request = new HttpRequestMessage(HttpMethod.Post,
"https://www.deezer.com/ajax/gw-light.php?method=deezer.getUserData&input=3&api_version=1.0&api_token=null");
request.Headers.Add("Cookie", $"arl={arl}");
@@ -230,7 +244,8 @@ public class DeezerDownloadService : IDownloadService
_licenseToken = licenseToken.GetString();
}
_logger.LogInformation("Deezer token refreshed: {Token}...", _apiToken?.Substring(0, Math.Min(16, _apiToken?.Length ?? 0)));
_logger.LogInformation("Deezer token refreshed: {Token}...",
_apiToken?[..Math.Min(16, _apiToken?.Length ?? 0)]);
return true;
}
@@ -291,51 +306,54 @@ public class DeezerDownloadService : IDownloadService
Encoding.UTF8,
"application/json");
var mediaResponse = await _httpClient.SendAsync(mediaHttpRequest, cancellationToken);
mediaResponse.EnsureSuccessStatusCode();
var mediaJson = await mediaResponse.Content.ReadAsStringAsync(cancellationToken);
var mediaDoc = JsonDocument.Parse(mediaJson);
if (!mediaDoc.RootElement.TryGetProperty("data", out var data) ||
data.GetArrayLength() == 0)
using (mediaHttpRequest)
{
throw new Exception("No download URL available");
}
var mediaResponse = await _httpClient.SendAsync(mediaHttpRequest, cancellationToken);
mediaResponse.EnsureSuccessStatusCode();
var firstData = data[0];
if (!firstData.TryGetProperty("media", out var media) ||
media.GetArrayLength() == 0)
{
throw new Exception("No media sources available - track may be unavailable in your region");
}
var mediaJson = await mediaResponse.Content.ReadAsStringAsync(cancellationToken);
var mediaDoc = JsonDocument.Parse(mediaJson);
string? downloadUrl = null;
string? format = null;
foreach (var mediaItem in media.EnumerateArray())
{
if (mediaItem.TryGetProperty("sources", out var sources) &&
sources.GetArrayLength() > 0)
if (!mediaDoc.RootElement.TryGetProperty("data", out var data) ||
data.GetArrayLength() == 0)
{
downloadUrl = sources[0].GetProperty("url").GetString();
format = mediaItem.GetProperty("format").GetString();
break;
throw new Exception("No download URL available");
}
}
if (string.IsNullOrEmpty(downloadUrl))
{
throw new Exception("No download URL found in media sources - track may be region locked");
}
var firstData = data[0];
if (!firstData.TryGetProperty("media", out var media) ||
media.GetArrayLength() == 0)
{
throw new Exception("No media sources available - track may be unavailable in your region");
}
return new DownloadResult
{
DownloadUrl = downloadUrl,
Format = format ?? "MP3_128",
Title = title,
Artist = artist
};
string? downloadUrl = null;
string? format = null;
foreach (var mediaItem in media.EnumerateArray())
{
if (mediaItem.TryGetProperty("sources", out var sources) &&
sources.GetArrayLength() > 0)
{
downloadUrl = sources[0].GetProperty("url").GetString();
format = mediaItem.GetProperty("format").GetString();
break;
}
}
if (string.IsNullOrEmpty(downloadUrl))
{
throw new Exception("No download URL found in media sources - track may be region locked");
}
return new DownloadResult
{
DownloadUrl = downloadUrl,
Format = format ?? "MP3_128",
Title = title,
Artist = artist
};
}
});
};
@@ -382,7 +400,7 @@ public class DeezerDownloadService : IDownloadService
// Download the encrypted file
var response = await RetryWithBackoffAsync(async () =>
{
var request = new HttpRequestMessage(HttpMethod.Get, downloadInfo.DownloadUrl);
using var request = new HttpRequestMessage(HttpMethod.Get, downloadInfo.DownloadUrl);
request.Headers.Add("User-Agent", "Mozilla/5.0");
request.Headers.Add("Accept", "*/*");
@@ -423,14 +441,7 @@ public class DeezerDownloadService : IDownloadService
tagFile.Tag.Album = song.Album;
// Album artist (may differ from track artist for compilations)
if (!string.IsNullOrEmpty(song.AlbumArtist))
{
tagFile.Tag.AlbumArtists = new[] { song.AlbumArtist };
}
else
{
tagFile.Tag.AlbumArtists = new[] { song.Artist };
}
tagFile.Tag.AlbumArtists = new[] { !string.IsNullOrEmpty(song.AlbumArtist) ? song.AlbumArtist : song.Artist };
// Track number
if (song.Track.HasValue)
@@ -763,7 +774,7 @@ public static class PathHelper
if (sanitized.Length > 100)
{
sanitized = sanitized.Substring(0, 100);
sanitized = sanitized[..100];
}
return sanitized.Trim();
@@ -794,7 +805,7 @@ public static class PathHelper
if (sanitized.Length > 100)
{
sanitized = sanitized.Substring(0, 100).TrimEnd('.');
sanitized = sanitized[..100].TrimEnd('.');
}
// Ensure we have a valid name

View File

@@ -1,295 +1,314 @@
using System.Text.Json;
using System.Xml.Linq;
using Microsoft.Extensions.Options;
using octo_fiesta.Models;
namespace octo_fiesta.Services;
/// <summary>
/// Interface for local music library management
/// </summary>
public interface ILocalLibraryService
{
/// <summary>
/// Checks if an external song already exists locally
/// </summary>
Task<string?> GetLocalPathForExternalSongAsync(string externalProvider, string externalId);
/// <summary>
/// Registers a downloaded song in the local library
/// </summary>
Task RegisterDownloadedSongAsync(Song song, string localPath);
/// <summary>
/// Gets the mapping between external ID and local ID
/// </summary>
Task<string?> GetLocalIdForExternalSongAsync(string externalProvider, string externalId);
/// <summary>
/// Parses a song ID to determine if it is external or local
/// </summary>
(bool isExternal, string? provider, string? externalId) ParseSongId(string songId);
/// <summary>
/// Parses an external ID to extract the provider, type and ID
/// Format: ext-{provider}-{type}-{id} (e.g., ext-deezer-artist-259, ext-deezer-album-96126, ext-deezer-song-12345)
/// Also supports legacy format: ext-{provider}-{id} (assumes song type)
/// </summary>
(bool isExternal, string? provider, string? type, string? externalId) ParseExternalId(string id);
/// <summary>
/// Triggers a Subsonic library scan
/// </summary>
Task<bool> TriggerLibraryScanAsync();
/// <summary>
/// Gets the current scan status
/// </summary>
Task<ScanStatus?> GetScanStatusAsync();
}
/// <summary>
/// Local library service implementation
/// Uses a simple JSON file to store mappings (can be replaced with a database)
/// </summary>
public class LocalLibraryService : ILocalLibraryService
{
private readonly string _mappingFilePath;
private readonly string _downloadDirectory;
private readonly HttpClient _httpClient;
private readonly SubsonicSettings _subsonicSettings;
private readonly ILogger<LocalLibraryService> _logger;
private Dictionary<string, LocalSongMapping>? _mappings;
private readonly SemaphoreSlim _lock = new(1, 1);
// Debounce to avoid triggering too many scans
private DateTime _lastScanTrigger = DateTime.MinValue;
private readonly TimeSpan _scanDebounceInterval = TimeSpan.FromSeconds(30);
public LocalLibraryService(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
IOptions<SubsonicSettings> subsonicSettings,
ILogger<LocalLibraryService> logger)
{
_downloadDirectory = configuration["Library:DownloadPath"] ?? Path.Combine(Directory.GetCurrentDirectory(), "downloads");
_mappingFilePath = Path.Combine(_downloadDirectory, ".mappings.json");
_httpClient = httpClientFactory.CreateClient();
_subsonicSettings = subsonicSettings.Value;
_logger = logger;
if (!Directory.Exists(_downloadDirectory))
{
Directory.CreateDirectory(_downloadDirectory);
}
}
public async Task<string?> GetLocalPathForExternalSongAsync(string externalProvider, string externalId)
{
var mappings = await LoadMappingsAsync();
var key = $"{externalProvider}:{externalId}";
if (mappings.TryGetValue(key, out var mapping) && File.Exists(mapping.LocalPath))
{
return mapping.LocalPath;
}
return null;
}
public async Task RegisterDownloadedSongAsync(Song song, string localPath)
{
if (song.ExternalProvider == null || song.ExternalId == null) return;
await _lock.WaitAsync();
try
{
var mappings = await LoadMappingsAsync();
var key = $"{song.ExternalProvider}:{song.ExternalId}";
mappings[key] = new LocalSongMapping
{
ExternalProvider = song.ExternalProvider,
ExternalId = song.ExternalId,
LocalPath = localPath,
Title = song.Title,
Artist = song.Artist,
Album = song.Album,
DownloadedAt = DateTime.UtcNow
};
await SaveMappingsAsync(mappings);
}
finally
{
_lock.Release();
}
}
public async Task<string?> GetLocalIdForExternalSongAsync(string externalProvider, string externalId)
{
// For now, return null as we don't yet have integration
// with the Subsonic server to retrieve local ID after scan
await Task.CompletedTask;
return null;
}
public (bool isExternal, string? provider, string? externalId) ParseSongId(string songId)
{
var (isExternal, provider, type, externalId) = ParseExternalId(songId);
return (isExternal, provider, externalId);
}
public (bool isExternal, string? provider, string? type, string? externalId) ParseExternalId(string id)
{
if (!id.StartsWith("ext-"))
{
return (false, null, null, null);
}
var parts = id.Split('-');
// Known types for the new format
var knownTypes = new HashSet<string> { "song", "album", "artist" };
// New format: ext-{provider}-{type}-{id} (e.g., ext-deezer-artist-259)
// Only use new format if parts[2] is a known type
if (parts.Length >= 4 && knownTypes.Contains(parts[2]))
{
var provider = parts[1];
var type = parts[2];
var externalId = string.Join("-", parts.Skip(3)); // Handle IDs with dashes
return (true, provider, type, externalId);
}
// Legacy format: ext-{provider}-{id} (assumes "song" type for backward compatibility)
// This handles both 3-part IDs and 4+ part IDs where parts[2] is NOT a known type
if (parts.Length >= 3)
{
var provider = parts[1];
var externalId = string.Join("-", parts.Skip(2)); // Everything after provider is the ID
return (true, provider, "song", externalId);
}
return (false, null, null, null);
}
private async Task<Dictionary<string, LocalSongMapping>> LoadMappingsAsync()
{
if (_mappings != null) return _mappings;
if (File.Exists(_mappingFilePath))
{
var json = await File.ReadAllTextAsync(_mappingFilePath);
_mappings = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, LocalSongMapping>>(json)
?? new Dictionary<string, LocalSongMapping>();
}
else
{
_mappings = new Dictionary<string, LocalSongMapping>();
}
return _mappings;
}
private async Task SaveMappingsAsync(Dictionary<string, LocalSongMapping> mappings)
{
_mappings = mappings;
var json = System.Text.Json.JsonSerializer.Serialize(mappings, new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true
});
await File.WriteAllTextAsync(_mappingFilePath, json);
}
public string GetDownloadDirectory() => _downloadDirectory;
public async Task<bool> TriggerLibraryScanAsync()
{
// Debounce: avoid triggering too many successive scans
var now = DateTime.UtcNow;
if (now - _lastScanTrigger < _scanDebounceInterval)
{
_logger.LogDebug("Scan debounced - last scan was {Elapsed}s ago",
(now - _lastScanTrigger).TotalSeconds);
return true;
}
_lastScanTrigger = now;
try
{
// Call Subsonic API to trigger a scan
// Note: Credentials must be passed as parameters (u, p or t+s)
var url = $"{_subsonicSettings.Url}/rest/startScan?f=json";
_logger.LogInformation("Triggering Subsonic library scan...");
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
_logger.LogInformation("Subsonic scan triggered successfully: {Response}", content);
return true;
}
else
{
_logger.LogWarning("Failed to trigger Subsonic scan: {StatusCode}", response.StatusCode);
return false;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error triggering Subsonic library scan");
return false;
}
}
public async Task<ScanStatus?> GetScanStatusAsync()
{
try
{
var url = $"{_subsonicSettings.Url}/rest/getScanStatus?f=json";
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(content);
if (doc.RootElement.TryGetProperty("subsonic-response", out var subsonicResponse) &&
subsonicResponse.TryGetProperty("scanStatus", out var scanStatus))
{
return new ScanStatus
{
Scanning = scanStatus.TryGetProperty("scanning", out var scanning) && scanning.GetBoolean(),
Count = scanStatus.TryGetProperty("count", out var count) ? count.GetInt32() : null
};
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting Subsonic scan status");
}
return null;
}
}
/// <summary>
/// Represents the mapping between an external song and its local file
/// </summary>
public class LocalSongMapping
{
public string ExternalProvider { get; set; } = string.Empty;
public string ExternalId { get; set; } = string.Empty;
public string LocalPath { get; set; } = string.Empty;
public string? LocalSubsonicId { get; set; }
public string Title { get; set; } = string.Empty;
public string Artist { get; set; } = string.Empty;
public string Album { get; set; } = string.Empty;
public DateTime DownloadedAt { get; set; }
}
using System.Text.Json;
using System.Xml.Linq;
using Microsoft.Extensions.Options;
using octo_fiesta.Models;
namespace octo_fiesta.Services;
/// <summary>
/// Interface for local music library management
/// </summary>
public interface ILocalLibraryService
{
/// <summary>
/// Checks if an external song already exists locally
/// </summary>
Task<string?> GetLocalPathForExternalSongAsync(string externalProvider, string externalId);
/// <summary>
/// Registers a downloaded song in the local library
/// </summary>
Task RegisterDownloadedSongAsync(Song song, string localPath);
/// <summary>
/// Gets the mapping between external ID and local ID
/// </summary>
Task<string?> GetLocalIdForExternalSongAsync(string externalProvider, string externalId);
/// <summary>
/// Parses a song ID to determine if it is external or local
/// </summary>
(bool isExternal, string? provider, string? externalId) ParseSongId(string songId);
/// <summary>
/// Parses an external ID to extract the provider, type and ID
/// Format: ext-{provider}-{type}-{id} (e.g., ext-deezer-artist-259, ext-deezer-album-96126, ext-deezer-song-12345)
/// Also supports legacy format: ext-{provider}-{id} (assumes song type)
/// </summary>
(bool isExternal, string? provider, string? type, string? externalId) ParseExternalId(string id);
/// <summary>
/// Triggers a Subsonic library scan
/// </summary>
Task<bool> TriggerLibraryScanAsync();
/// <summary>
/// Gets the current scan status
/// </summary>
Task<ScanStatus?> GetScanStatusAsync();
}
/// <summary>
/// Local library service implementation
/// Uses a simple JSON file to store mappings (can be replaced with a database)
/// </summary>
public class LocalLibraryService : ILocalLibraryService
{
private readonly string _mappingFilePath;
private readonly string _downloadDirectory;
private readonly HttpClient _httpClient;
private readonly SubsonicSettings _subsonicSettings;
private readonly ILogger<LocalLibraryService> _logger;
private Dictionary<string, LocalSongMapping>? _mappings;
private readonly SemaphoreSlim _lock = new(1, 1);
// Debounce to avoid triggering too many scans
private DateTime _lastScanTrigger = DateTime.MinValue;
private readonly TimeSpan _scanDebounceInterval = TimeSpan.FromSeconds(30);
public LocalLibraryService(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
IOptions<SubsonicSettings> subsonicSettings,
ILogger<LocalLibraryService> logger)
{
_downloadDirectory = configuration["Library:DownloadPath"] ?? Path.Combine(Directory.GetCurrentDirectory(), "downloads");
_mappingFilePath = Path.Combine(_downloadDirectory, ".mappings.json");
_httpClient = httpClientFactory.CreateClient();
_subsonicSettings = subsonicSettings.Value;
_logger = logger;
if (!Directory.Exists(_downloadDirectory))
{
Directory.CreateDirectory(_downloadDirectory);
}
}
public async Task<string?> GetLocalPathForExternalSongAsync(string externalProvider, string externalId)
{
var mappings = await LoadMappingsAsync();
var key = $"{externalProvider}:{externalId}";
if (mappings.TryGetValue(key, out var mapping) && File.Exists(mapping.LocalPath))
{
return mapping.LocalPath;
}
return null;
}
public async Task RegisterDownloadedSongAsync(Song song, string localPath)
{
if (song.ExternalProvider == null || song.ExternalId == null) return;
// Load mappings first (this acquires the lock internally if needed)
var mappings = await LoadMappingsAsync();
await _lock.WaitAsync();
try
{
var key = $"{song.ExternalProvider}:{song.ExternalId}";
mappings[key] = new LocalSongMapping
{
ExternalProvider = song.ExternalProvider,
ExternalId = song.ExternalId,
LocalPath = localPath,
Title = song.Title,
Artist = song.Artist,
Album = song.Album,
DownloadedAt = DateTime.UtcNow
};
await SaveMappingsAsync(mappings);
}
finally
{
_lock.Release();
}
}
public async Task<string?> GetLocalIdForExternalSongAsync(string externalProvider, string externalId)
{
// For now, return null as we don't yet have integration
// with the Subsonic server to retrieve local ID after scan
await Task.CompletedTask;
return null;
}
public (bool isExternal, string? provider, string? externalId) ParseSongId(string songId)
{
var (isExternal, provider, _, externalId) = ParseExternalId(songId);
return (isExternal, provider, externalId);
}
public (bool isExternal, string? provider, string? type, string? externalId) ParseExternalId(string id)
{
if (!id.StartsWith("ext-"))
{
return (false, null, null, null);
}
var parts = id.Split('-');
// Known types for the new format
var knownTypes = new HashSet<string> { "song", "album", "artist" };
// New format: ext-{provider}-{type}-{id} (e.g., ext-deezer-artist-259)
// Only use new format if parts[2] is a known type
if (parts.Length >= 4 && knownTypes.Contains(parts[2]))
{
var provider = parts[1];
var type = parts[2];
var externalId = string.Join("-", parts.Skip(3)); // Handle IDs with dashes
return (true, provider, type, externalId);
}
// Legacy format: ext-{provider}-{id} (assumes "song" type for backward compatibility)
// This handles both 3-part IDs and 4+ part IDs where parts[2] is NOT a known type
if (parts.Length >= 3)
{
var provider = parts[1];
var externalId = string.Join("-", parts.Skip(2)); // Everything after provider is the ID
return (true, provider, "song", externalId);
}
return (false, null, null, null);
}
private async Task<Dictionary<string, LocalSongMapping>> LoadMappingsAsync()
{
// Fast path: return cached mappings if available
if (_mappings != null) return _mappings;
// Slow path: acquire lock to load from file (prevents race condition)
await _lock.WaitAsync();
try
{
// Double-check after acquiring lock
if (_mappings != null) return _mappings;
if (File.Exists(_mappingFilePath))
{
var json = await File.ReadAllTextAsync(_mappingFilePath);
_mappings = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, LocalSongMapping>>(json)
?? new Dictionary<string, LocalSongMapping>();
}
else
{
_mappings = new Dictionary<string, LocalSongMapping>();
}
return _mappings;
}
finally
{
_lock.Release();
}
}
private async Task SaveMappingsAsync(Dictionary<string, LocalSongMapping> mappings)
{
_mappings = mappings;
var json = System.Text.Json.JsonSerializer.Serialize(mappings, new System.Text.Json.JsonSerializerOptions
{
WriteIndented = true
});
await File.WriteAllTextAsync(_mappingFilePath, json);
}
public string GetDownloadDirectory() => _downloadDirectory;
public async Task<bool> TriggerLibraryScanAsync()
{
// Debounce: avoid triggering too many successive scans
var now = DateTime.UtcNow;
if (now - _lastScanTrigger < _scanDebounceInterval)
{
_logger.LogDebug("Scan debounced - last scan was {Elapsed}s ago",
(now - _lastScanTrigger).TotalSeconds);
return true;
}
_lastScanTrigger = now;
try
{
// Call Subsonic API to trigger a scan
// Note: This endpoint works without authentication on most Subsonic/Navidrome servers
// when called from localhost. For remote servers requiring auth, this would need
// to be refactored to accept credentials from the controller layer.
var url = $"{_subsonicSettings.Url}/rest/startScan?f=json";
_logger.LogInformation("Triggering Subsonic library scan...");
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
_logger.LogInformation("Subsonic scan triggered successfully: {Response}", content);
return true;
}
else
{
_logger.LogWarning("Failed to trigger Subsonic scan: {StatusCode} - Server may require authentication", response.StatusCode);
return false;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error triggering Subsonic library scan");
return false;
}
}
public async Task<ScanStatus?> GetScanStatusAsync()
{
try
{
// Note: This endpoint works without authentication on most Subsonic/Navidrome servers
// when called from localhost.
var url = $"{_subsonicSettings.Url}/rest/getScanStatus?f=json";
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(content);
if (doc.RootElement.TryGetProperty("subsonic-response", out var subsonicResponse) &&
subsonicResponse.TryGetProperty("scanStatus", out var scanStatus))
{
return new ScanStatus
{
Scanning = scanStatus.TryGetProperty("scanning", out var scanning) && scanning.GetBoolean(),
Count = scanStatus.TryGetProperty("count", out var count) ? count.GetInt32() : null
};
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error getting Subsonic scan status");
}
return null;
}
}
/// <summary>
/// Represents the mapping between an external song and its local file
/// </summary>
public class LocalSongMapping
{
public string ExternalProvider { get; set; } = string.Empty;
public string ExternalId { get; set; } = string.Empty;
public string LocalPath { get; set; } = string.Empty;
public string? LocalSubsonicId { get; set; }
public string Title { get; set; } = string.Empty;
public string Artist { get; set; } = string.Empty;
public string Album { get; set; } = string.Empty;
public DateTime DownloadedAt { get; set; }
}

View File

@@ -7,7 +7,7 @@
},
"AllowedHosts": "*",
"Subsonic": {
"Url": "http://192.168.1.12:4533"
"Url": "http://localhost:4533"
},
"Library": {
"DownloadPath": "./downloads"