3 Commits

Author SHA1 Message Date
pcjones
a25c950a81 Add RSS sync for Lidarr 2024-02-13 00:04:50 +01:00
Jonas F
14b7bc8e60 Update README.md 2024-02-12 21:37:02 +01:00
Jonas F
9cf590b7e5 Update README.md 2024-02-12 21:34:19 +01:00
8 changed files with 105 additions and 124 deletions

View File

@@ -15,7 +15,7 @@ Zusätzlich müsst ihr in Sonarr oder Prowlarr einen neuen Indexer hinzufügen (
Am Beispiel von sceneNZBs: Am Beispiel von sceneNZBs:
![grafik](https://github.com/PCJones/UmlautAdaptarr/assets/377223/97ca0aef-1a9e-4560-9374-c3a8215dafd2) ![grafik](https://github.com/PCJones/UmlautAdaptarr/assets/377223/07c7ca45-e0e5-4a82-af63-365bb23c55c9)
Also alles wie immer, nur dass ihr als API-URL nicht direkt z.B. `https://scenenzbs.com` eingebt, sondern Also alles wie immer, nur dass ihr als API-URL nicht direkt z.B. `https://scenenzbs.com` eingebt, sondern
`http://localhost:5005/_/scenenzbs.com` `http://localhost:5005/_/scenenzbs.com`
@@ -39,13 +39,13 @@ Einige Beispiele findet ihr unter Features.
| Feature | Status | | Feature | Status |
|-------------------------------------------------------------------|---------------| |-------------------------------------------------------------------|---------------|
| Sonarr & Prowlarr Support | ✓ | | Sonarr & Prowlarr Support | ✓ |
| Lidarr Support | (✓) kein RSS Sync|
| Releases mit deutschem Titel werden erkannt | ✓ | | Releases mit deutschem Titel werden erkannt | ✓ |
| Releases mit TVDB-Alias Titel werden erkannt | ✓ | | Releases mit TVDB-Alias Titel werden erkannt | ✓ |
| Korrekte Suche und Erkennung von Titel mit Umlauten | ✓ | | Korrekte Suche und Erkennung von Titel mit Umlauten | ✓ |
| Anfragen-Caching für 5 Minuten zur Reduzierung der API-Zugriffe | ✓ | | Anfragen-Caching für 5 Minuten zur Reduzierung der API-Zugriffe | ✓ |
| Radarr Support | Geplant | | Radarr Support | Geplant |
| Readarr Support | Geplant | | Readarr Support | Geplant |
| Lidarr Support | Geplant |
| Prowlarr Unterstützung für "DE" SceneNZBs Kategorien | Geplant | | Prowlarr Unterstützung für "DE" SceneNZBs Kategorien | Geplant |
| Unterstützung weiterer Sprachen neben Deutsch | Geplant | | Unterstützung weiterer Sprachen neben Deutsch | Geplant |
| Wünsche? | Vorschläge? | | Wünsche? | Vorschläge? |

View File

@@ -1,9 +1,5 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Text; using System.Text;
using System.Xml.Linq;
using UmlautAdaptarr.Models; using UmlautAdaptarr.Models;
using UmlautAdaptarr.Services; using UmlautAdaptarr.Services;
using UmlautAdaptarr.Utilities; using UmlautAdaptarr.Utilities;

View File

@@ -67,6 +67,7 @@ namespace UmlautAdaptarr.Models
} }
TitleMatchVariations = allTitleVariations.Distinct().ToArray(); TitleMatchVariations = allTitleVariations.Distinct().ToArray();
AuthorMatchVariations = [];
} }
} }

View File

@@ -1,4 +1,5 @@
using Newtonsoft.Json; using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using UmlautAdaptarr.Models; using UmlautAdaptarr.Models;
using UmlautAdaptarr.Services; using UmlautAdaptarr.Services;
@@ -9,7 +10,8 @@ namespace UmlautAdaptarr.Providers
public class LidarrClient( public class LidarrClient(
IHttpClientFactory clientFactory, IHttpClientFactory clientFactory,
IConfiguration configuration, IConfiguration configuration,
TitleApiService titleService, CacheService cacheService,
IMemoryCache cache,
ILogger<LidarrClient> logger) : ArrClientBase() ILogger<LidarrClient> logger) : ArrClientBase()
{ {
private readonly string _lidarrHost = configuration.GetValue<string>("LIDARR_HOST") ?? throw new ArgumentException("LIDARR_HOST environment variable must be set"); private readonly string _lidarrHost = configuration.GetValue<string>("LIDARR_HOST") ?? throw new ArgumentException("LIDARR_HOST environment variable must be set");
@@ -23,7 +25,6 @@ namespace UmlautAdaptarr.Providers
try try
{ {
var lidarrArtistsUrl = $"{_lidarrHost}/api/v1/artist?apikey={_lidarrApiKey}"; var lidarrArtistsUrl = $"{_lidarrHost}/api/v1/artist?apikey={_lidarrApiKey}";
logger.LogInformation($"Fetching all artists from Lidarr: {UrlUtilities.RedactApiKey(lidarrArtistsUrl)}"); logger.LogInformation($"Fetching all artists from Lidarr: {UrlUtilities.RedactApiKey(lidarrArtistsUrl)}");
var artistsApiResponse = await httpClient.GetStringAsync(lidarrArtistsUrl); var artistsApiResponse = await httpClient.GetStringAsync(lidarrArtistsUrl);
@@ -40,9 +41,17 @@ namespace UmlautAdaptarr.Providers
var artistId = (int)artist.id; var artistId = (int)artist.id;
var lidarrAlbumUrl = $"{_lidarrHost}/api/v1/album?artistId={artistId}&apikey={_lidarrApiKey}"; var lidarrAlbumUrl = $"{_lidarrHost}/api/v1/album?artistId={artistId}&apikey={_lidarrApiKey}";
if (cache.TryGetValue(lidarrAlbumUrl, out List<dynamic>? albums))
{
logger.LogInformation($"Using cached albums for {UrlUtilities.RedactApiKey(lidarrAlbumUrl)}");
}
else
{
logger.LogInformation($"Fetching all albums from artistId {artistId} from Lidarr: {UrlUtilities.RedactApiKey(lidarrArtistsUrl)}"); logger.LogInformation($"Fetching all albums from artistId {artistId} from Lidarr: {UrlUtilities.RedactApiKey(lidarrArtistsUrl)}");
var albumApiResponse = await httpClient.GetStringAsync(lidarrAlbumUrl); var albumApiResponse = await httpClient.GetStringAsync(lidarrAlbumUrl);
var albums = JsonConvert.DeserializeObject<List<dynamic>>(albumApiResponse); albums = JsonConvert.DeserializeObject<List<dynamic>>(albumApiResponse);
}
if (albums == null) if (albums == null)
{ {
@@ -52,6 +61,9 @@ namespace UmlautAdaptarr.Providers
logger.LogInformation($"Successfully fetched {albums.Count} albums for artistId {artistId} from Lidarr."); logger.LogInformation($"Successfully fetched {albums.Count} albums for artistId {artistId} from Lidarr.");
// Cache albums for 3 minutes
cache.Set(lidarrAlbumUrl, albums, TimeSpan.FromMinutes(3));
foreach (var album in albums) foreach (var album in albums)
{ {
var artistName = (string)album.artist.artistName; var artistName = (string)album.artist.artistName;
@@ -92,42 +104,20 @@ namespace UmlautAdaptarr.Providers
public override async Task<SearchItem?> FetchItemByExternalIdAsync(string externalId) public override async Task<SearchItem?> FetchItemByExternalIdAsync(string externalId)
{ {
var httpClient = clientFactory.CreateClient();
try try
{ {
var lidarrUrl = $"{_lidarrHost}/api/v1/series?mbId={externalId}&includeSeasonImages=false&apikey={_lidarrApiKey}"; // For now we have to fetch all items every time
logger.LogInformation($"Fetching item by external ID from Lidarr: {UrlUtilities.RedactApiKey(lidarrUrl)}"); var searchItems = await FetchAllItemsAsync();
var response = await httpClient.GetStringAsync(lidarrUrl); foreach (var searchItem in searchItems ?? [])
var artists = JsonConvert.DeserializeObject<dynamic>(response);
var artist = artists?[0];
if (artist != null)
{ {
var mbId = (string)artist.mbId; try
if (mbId == null)
{ {
logger.LogWarning($"Lidarr Artist {artist.id} doesn't have a mbId."); cacheService.CacheSearchItem(searchItem);
return null; }
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred while caching search item with ID {searchItem.ArrId}.");
} }
(var germanTitle, var aliases) = await titleService.FetchGermanTitleAndAliasesByExternalIdAsync(_mediaType, mbId);
throw new NotImplementedException();
var searchItem = new SearchItem
(
arrId: (int)artist.id,
externalId: mbId,
title: (string)artist.title,
expectedTitle: (string)artist.title,
germanTitle: germanTitle,
aliases: aliases,
mediaType: _mediaType,
expectedAuthor: "TODO"
); ;
logger.LogInformation($"Successfully fetched artist {searchItem} from Lidarr.");
return searchItem;
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -140,54 +130,10 @@ namespace UmlautAdaptarr.Providers
public override async Task<SearchItem?> FetchItemByTitleAsync(string title) public override async Task<SearchItem?> FetchItemByTitleAsync(string title)
{ {
var httpClient = clientFactory.CreateClient();
try try
{ {
(string? germanTitle, string? mbId, string[]? aliases) = await titleService.FetchGermanTitleAndExternalIdAndAliasesByTitle(_mediaType, title); // this should never be called at the moment
if (mbId == null)
{
return null;
}
var lidarrUrl = $"{_lidarrHost}/api/v1/series?mbId={mbId}&includeSeasonImages=false&apikey={_lidarrApiKey}";
var lidarrApiResponse = await httpClient.GetStringAsync(lidarrUrl);
var artists = JsonConvert.DeserializeObject<dynamic>(lidarrApiResponse);
if (artists == null)
{
logger.LogError($"Parsing Lidarr API response for MB ID {mbId} resulted in null");
return null;
}
else if (artists.Count == 0)
{
logger.LogWarning($"No results found for MB ID {mbId}");
return null;
}
var expectedTitle = (string)artists[0].title;
if (expectedTitle == null)
{
logger.LogError($"Lidarr Title for MB ID {mbId} is null");
return null;
}
throw new NotImplementedException(); throw new NotImplementedException();
var searchItem = new SearchItem
(
arrId: (int)artists[0].id,
externalId: mbId,
title: (string)artists[0].title,
expectedTitle: (string)artists[0].title,
germanTitle: germanTitle,
aliases: aliases,
mediaType: _mediaType,
expectedAuthor: "TODO"
);
logger.LogInformation($"Successfully fetched artist {searchItem} from Lidarr.");
return searchItem;
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@@ -1,4 +1,6 @@
using Microsoft.Extensions.Caching.Memory; using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection.Metadata.Ecma335;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using UmlautAdaptarr.Models; using UmlautAdaptarr.Models;
using UmlautAdaptarr.Utilities; using UmlautAdaptarr.Utilities;
@@ -8,16 +10,17 @@ namespace UmlautAdaptarr.Services
public partial class CacheService(IMemoryCache cache) public partial class CacheService(IMemoryCache cache)
{ {
private readonly Dictionary<string, HashSet<string>> VariationIndex = []; private readonly Dictionary<string, HashSet<string>> VariationIndex = [];
private readonly Dictionary<string, List<SearchItem>> AudioFuzzyIndex = []; private readonly Dictionary<string, List<(HashSet<string> TitleVariations, string CacheKey)>> AudioVariationIndex = [];
private const int VARIATION_LOOKUP_CACHE_LENGTH = 5; private const int VARIATION_LOOKUP_CACHE_LENGTH = 5;
public void CacheSearchItem(SearchItem item) public void CacheSearchItem(SearchItem item)
{ {
var prefix = item.MediaType; var prefix = item.MediaType;
cache.Set($"{prefix}_extid_{item.ExternalId}", item); var cacheKey = $"{prefix}_extid_{item.ExternalId}";
cache.Set(cacheKey, item);
if (item.MediaType == "audio") if (item.MediaType == "audio")
{ {
CacheAudioSearchItem(item); CacheAudioSearchItem(item, cacheKey);
return; return;
} }
@@ -28,7 +31,7 @@ namespace UmlautAdaptarr.Services
foreach (var variation in item.TitleMatchVariations) foreach (var variation in item.TitleMatchVariations)
{ {
var normalizedVariation = variation.RemoveAccentButKeepGermanUmlauts().ToLower(); var normalizedVariation = variation.RemoveAccentButKeepGermanUmlauts().ToLower();
var cacheKey = $"{prefix}_var_{normalizedVariation}"; cacheKey = $"{prefix}_var_{normalizedVariation}";
cache.Set(cacheKey, item); cache.Set(cacheKey, item);
// Indexing by prefix // Indexing by prefix
@@ -41,30 +44,32 @@ namespace UmlautAdaptarr.Services
} }
} }
private void CacheAudioSearchItem(SearchItem item) public void CacheAudioSearchItem(SearchItem item, string cacheKey)
{ {
// Normalize and simplify the title and author for fuzzy matching // Index author and title variations
var key = NormalizeForFuzzyMatching(item.ExternalId); foreach (var authorVariation in item.AuthorMatchVariations)
{
var normalizedAuthor = authorVariation.NormalizeForComparison();
if (!AudioFuzzyIndex.ContainsKey(key)) if (!AudioVariationIndex.ContainsKey(normalizedAuthor))
{ {
AudioFuzzyIndex[key] = new List<SearchItem>(); AudioVariationIndex[normalizedAuthor] = [];
}
AudioFuzzyIndex[key].Add(item);
} }
private string NormalizeForFuzzyMatching(string input) var titleVariations = item.TitleMatchVariations.Select(titleMatchVariation => titleMatchVariation.NormalizeForComparison()).ToHashSet();
{ AudioVariationIndex[normalizedAuthor].Add((titleVariations, cacheKey));
// Normalize the input string by removing accents, converting to lower case, and removing non-alphanumeric characters }
var normalized = input.RemoveAccentButKeepGermanUmlauts().RemoveSpecialCharacters().ToLower();
normalized = WhiteSpaceRegex().Replace(normalized, "");
return normalized;
} }
public SearchItem? SearchItemByTitle(string mediaType, string title) public SearchItem? SearchItemByTitle(string mediaType, string title)
{ {
var normalizedTitle = title.RemoveAccentButKeepGermanUmlauts().ToLower(); var normalizedTitle = title.RemoveAccentButKeepGermanUmlauts().ToLower();
if (mediaType == "audio")
{
return FindBestMatchForAudio(normalizedTitle.NormalizeForComparison());
}
// Use the first few characters of the normalized title for cache prefix search // Use the first few characters of the normalized title for cache prefix search
var cacheSearchPrefix = normalizedTitle[..Math.Min(VARIATION_LOOKUP_CACHE_LENGTH, normalizedTitle.Length)]; var cacheSearchPrefix = normalizedTitle[..Math.Min(VARIATION_LOOKUP_CACHE_LENGTH, normalizedTitle.Length)];
@@ -107,10 +112,12 @@ namespace UmlautAdaptarr.Services
{ {
var normalizedTitle = title.RemoveAccentButKeepGermanUmlauts().ToLower(); var normalizedTitle = title.RemoveAccentButKeepGermanUmlauts().ToLower();
if (mediaType == "generic") if (mediaType == "generic")
{ {
// TODO // TODO
} }
cache.TryGetValue($"{mediaType}_var_{normalizedTitle}", out SearchItem? item); cache.TryGetValue($"{mediaType}_var_{normalizedTitle}", out SearchItem? item);
if (item == null) if (item == null)
{ {
@@ -119,6 +126,31 @@ namespace UmlautAdaptarr.Services
return item; return item;
} }
private SearchItem? FindBestMatchForAudio(string normalizedOriginalTitle)
{
foreach (var authorEntry in AudioVariationIndex)
{
if (normalizedOriginalTitle.Contains(authorEntry.Key))
{
var sortedEntries = authorEntry.Value.OrderByDescending(entry => entry.TitleVariations.FirstOrDefault()?.Length).ToList();
foreach (var (titleVariations, cacheKey) in sortedEntries)
{
if (titleVariations.Any(normalizedOriginalTitle.Contains))
{
if (cache.TryGetValue(cacheKey, out SearchItem? item))
{
return item;
}
}
}
}
}
return null;
}
[GeneratedRegex("\\s")] [GeneratedRegex("\\s")]
private static partial Regex WhiteSpaceRegex(); private static partial Regex WhiteSpaceRegex();
} }

View File

@@ -62,6 +62,8 @@ namespace UmlautAdaptarr.Services
fetchedItem = await sonarrClient.FetchItemByTitleAsync(title); fetchedItem = await sonarrClient.FetchItemByTitleAsync(title);
} }
break; break;
case "audio":
break;
// TODO add cases for other sources as needed, such as Radarr, Lidarr, etc. // TODO add cases for other sources as needed, such as Radarr, Lidarr, etc.
} }
@@ -74,5 +76,4 @@ namespace UmlautAdaptarr.Services
return fetchedItem; return fetchedItem;
} }
} }
} }

View File

@@ -51,7 +51,7 @@ namespace UmlautAdaptarr.Services
FindAndReplaceForMoviesAndTV(logger, searchItem, titleElement, originalTitle, normalizedOriginalTitle!); FindAndReplaceForMoviesAndTV(logger, searchItem, titleElement, originalTitle, normalizedOriginalTitle!);
break; break;
case "audio": case "audio":
ReplaceForAudio(searchItem, titleElement, originalTitle, normalizedOriginalTitle!); FindAndReplaceForAudio(searchItem, titleElement, originalTitle!);
break; break;
default: default:
throw new NotImplementedException(); throw new NotImplementedException();
@@ -62,23 +62,25 @@ namespace UmlautAdaptarr.Services
return xDoc.ToString(); return xDoc.ToString();
} }
private string NormalizeString(string text) public void FindAndReplaceForAudio(SearchItem searchItem, XElement? titleElement, string originalTitle)
{ {
return text.RemoveGermanUmlautDots().RemoveAccent().RemoveSpecialCharacters().Replace(" ", "").Trim().ToLower(); var authorMatch = FindBestMatch(searchItem.AuthorMatchVariations, originalTitle.NormalizeForComparison(), originalTitle);
} var titleMatch = FindBestMatch(searchItem.TitleMatchVariations, originalTitle.NormalizeForComparison(), originalTitle);
public void ReplaceForAudio(SearchItem searchItem, XElement? titleElement, string originalTitle, string normalizedOriginalTitle)
{
var authorMatch = FindBestMatch(searchItem.AuthorMatchVariations, NormalizeString(normalizedOriginalTitle), originalTitle);
var titleMatch = FindBestMatch(searchItem.TitleMatchVariations, NormalizeString(normalizedOriginalTitle), originalTitle);
if (authorMatch.Item1 && titleMatch.Item1) if (authorMatch.Item1 && titleMatch.Item1)
{ {
int matchEndPositionInOriginal = Math.Max(authorMatch.Item3, titleMatch.Item3); int matchEndPositionInOriginal = Math.Max(authorMatch.Item3, titleMatch.Item3);
var test = originalTitle[matchEndPositionInOriginal];
// Check and adjust for immediate following delimiter
if (matchEndPositionInOriginal < originalTitle.Length && new char[] { ' ', '-', '_', '.' }.Contains(originalTitle[matchEndPositionInOriginal]))
{
matchEndPositionInOriginal++; // Skip the delimiter if it's immediately after the match
}
// Ensure we trim any leading delimiters from the suffix // Ensure we trim any leading delimiters from the suffix
string suffix = originalTitle.Substring(matchEndPositionInOriginal).TrimStart([' ', '-', '_']); string suffix = originalTitle[matchEndPositionInOriginal..].TrimStart([' ', '-', '_', '.']).Trim();
suffix = suffix.Replace("-", ".");
// Concatenate the expected title with the remaining suffix // Concatenate the expected title with the remaining suffix
var updatedTitle = $"{searchItem.ExpectedAuthor} - {searchItem.ExpectedTitle}-{suffix}"; var updatedTitle = $"{searchItem.ExpectedAuthor} - {searchItem.ExpectedTitle}-{suffix}";
@@ -102,7 +104,7 @@ namespace UmlautAdaptarr.Services
foreach (var variation in variations) foreach (var variation in variations)
{ {
var normalizedVariation = NormalizeString(variation); var normalizedVariation = variation.NormalizeForComparison();
int startNormalized = normalizedOriginal.IndexOf(normalizedVariation); int startNormalized = normalizedOriginal.IndexOf(normalizedVariation);
if (startNormalized >= 0) if (startNormalized >= 0)
@@ -148,11 +150,9 @@ namespace UmlautAdaptarr.Services
originalIndex = i; originalIndex = i;
} }
return originalIndex + 1; // +1 to move past the matched character or to the next character in the original title return originalIndex;
} }
// This method replaces the first variation that starts at the beginning of the release title // This method replaces the first variation that starts at the beginning of the release title
private static void FindAndReplaceForMoviesAndTV(ILogger<TitleMatchingService> logger, SearchItem searchItem, XElement? titleElement, string originalTitle, string normalizedOriginalTitle) private static void FindAndReplaceForMoviesAndTV(ILogger<TitleMatchingService> logger, SearchItem searchItem, XElement? titleElement, string originalTitle, string normalizedOriginalTitle)
{ {

View File

@@ -53,6 +53,11 @@ namespace UmlautAdaptarr.Utilities
return text.Replace("(", "").Replace(")", "").Replace("?","").Replace(":", "").Replace("'", ""); return text.Replace("(", "").Replace(")", "").Replace("?","").Replace(":", "").Replace("'", "");
} }
public static string NormalizeForComparison(this string text)
{
return text.RemoveGermanUmlautDots().RemoveAccent().RemoveSpecialCharacters().Replace(" ", "").Trim().ToLower();
}
public static string RemoveSpecialCharacters(this string text) public static string RemoveSpecialCharacters(this string text)
{ {
return SpecialCharactersRegex().Replace(text, ""); return SpecialCharactersRegex().Replace(text, "");