perf(backend): cache YouTube searches and shrink the thumbnail URLs

Repeated searches and song lookups now reuse a single-flight memory cache, so
concurrent or debounced queries hit YouTube once instead of on every keystroke.
Thumbnails are resolved at a configurable size instead of the largest variant,
which cuts the image payload the browser pulls from Google.
This commit is contained in:
2026-07-20 17:29:28 +02:00
parent 71c45abcf1
commit c302cfd314
5 changed files with 144 additions and 9 deletions
@@ -0,0 +1,52 @@
namespace Musify.Infrastructure.Services
{
public static class YouTubeThumbnail
{
public static string WithSize(string url, int size)
{
if (string.IsNullOrEmpty(url))
return string.Empty;
if (url.Contains("googleusercontent.com", StringComparison.OrdinalIgnoreCase))
return ResizeGoogleUserContent(url, size);
if (url.Contains("ytimg.com", StringComparison.OrdinalIgnoreCase))
return ResizeYtImg(url, size);
return url;
}
private static string ResizeGoogleUserContent(string url, int size)
{
var separator = url.LastIndexOf('=');
var baseUrl = separator > 0 && IsSizeSuffix(url.AsSpan(separator + 1))
? url[..separator]
: url;
return $"{baseUrl}=w{size}-h{size}-l90-rj";
}
private static string ResizeYtImg(string url, int size)
{
var queryStart = url.IndexOf('?');
var path = queryStart >= 0 ? url[..queryStart] : url;
var lastSlash = path.LastIndexOf('/');
if (lastSlash < 0)
return path;
return $"{path[..lastSlash]}/{YtImgFileName(size)}";
}
private static string YtImgFileName(int size) => size switch
{
<= 120 => "default.jpg",
<= 320 => "mqdefault.jpg",
<= 480 => "hqdefault.jpg",
_ => "maxresdefault.jpg"
};
private static bool IsSizeSuffix(ReadOnlySpan<char> suffix) =>
suffix.Length > 1 && (suffix[0] is 'w' or 's' or 'h') && char.IsDigit(suffix[1]);
}
}