| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Collections.Frozen; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Globalization; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Linq; |
| | | 9 | | using System.Reflection; |
| | | 10 | | using System.Text.Json; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | using Jellyfin.Extensions; |
| | | 13 | | using Jellyfin.Extensions.Json; |
| | | 14 | | using MediaBrowser.Controller.Configuration; |
| | | 15 | | using MediaBrowser.Model.Entities; |
| | | 16 | | using MediaBrowser.Model.Globalization; |
| | | 17 | | using Microsoft.Extensions.Logging; |
| | | 18 | | |
| | | 19 | | namespace Emby.Server.Implementations.Localization |
| | | 20 | | { |
| | | 21 | | /// <summary> |
| | | 22 | | /// Class LocalizationManager. |
| | | 23 | | /// </summary> |
| | | 24 | | public class LocalizationManager : ILocalizationManager |
| | | 25 | | { |
| | | 26 | | private const string DefaultCulture = "en-US"; |
| | | 27 | | private const string RatingsPath = "Emby.Server.Implementations.Localization.Ratings."; |
| | | 28 | | private const string CulturesPath = "Emby.Server.Implementations.Localization.iso6392.txt"; |
| | | 29 | | private const string CountriesPath = "Emby.Server.Implementations.Localization.countries.json"; |
| | | 30 | | private const string CoreResourcePrefix = "Emby.Server.Implementations.Localization.Core."; |
| | 2 | 31 | | private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly; |
| | 2 | 32 | | private static readonly string[] _unratedValues = ["n/a", "unrated", "not rated", "nr"]; |
| | | 33 | | |
| | | 34 | | private readonly IServerConfigurationManager _configurationManager; |
| | | 35 | | private readonly ILogger<LocalizationManager> _logger; |
| | | 36 | | |
| | 156 | 37 | | private readonly Dictionary<string, Dictionary<string, ParentalRatingScore?>> _allParentalRatings = new(StringCo |
| | | 38 | | |
| | 156 | 39 | | private readonly ConcurrentDictionary<string, Dictionary<string, string>> _cultureOnlyDictionaries = new(StringC |
| | | 40 | | |
| | 156 | 41 | | private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; |
| | | 42 | | |
| | 156 | 43 | | private readonly ConcurrentDictionary<string, CultureDto?> _cultureCache = new(StringComparer.OrdinalIgnoreCase) |
| | 156 | 44 | | private List<CultureDto> _cultures = []; |
| | | 45 | | |
| | 2 | 46 | | private static readonly (IReadOnlyList<LocalizationOption> Options, FrozenDictionary<string, string> Bcp47ToJell |
| | 2 | 47 | | private static readonly IReadOnlyList<LocalizationOption> _localizationOptions = _localizationData.Options; |
| | | 48 | | |
| | | 49 | | // Maps BCP-47 hyphenated culture codes (set by ASP.NET Core's RequestLocalizationMiddleware |
| | | 50 | | // and used as CurrentUICulture.Name) to Jellyfin's underscore-based resource file codes. |
| | | 51 | | // Built reflexively from the resource file scan so both directions stay in sync. |
| | 2 | 52 | | private static readonly FrozenDictionary<string, string> _bcp47ToJellyfinMap = _localizationData.Bcp47ToJellyfin |
| | | 53 | | |
| | | 54 | | private FrozenDictionary<string, string> _iso6392BtoT = null!; |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Initializes a new instance of the <see cref="LocalizationManager" /> class. |
| | | 58 | | /// </summary> |
| | | 59 | | /// <param name="configurationManager">The configuration manager.</param> |
| | | 60 | | /// <param name="logger">The logger.</param> |
| | | 61 | | public LocalizationManager( |
| | | 62 | | IServerConfigurationManager configurationManager, |
| | | 63 | | ILogger<LocalizationManager> logger) |
| | | 64 | | { |
| | 156 | 65 | | _configurationManager = configurationManager; |
| | 156 | 66 | | _logger = logger; |
| | | 67 | | |
| | 156 | 68 | | _configurationManager.ConfigurationUpdated += OnConfigurationUpdated; |
| | 156 | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Gets the supported UI cultures. |
| | | 73 | | /// </summary> |
| | | 74 | | /// <returns>A list of <see cref="CultureInfo"/> objects covering every embedded translation.</returns> |
| | | 75 | | public static IList<CultureInfo> GetSupportedUICultures() |
| | | 76 | | { |
| | 28 | 77 | | var cultures = new List<CultureInfo>(); |
| | 5936 | 78 | | foreach (var option in _localizationOptions) |
| | | 79 | | { |
| | | 80 | | // Skip novelty codes (e.g. "pr" Pirate, "jbo" Lojban) that .NET cannot resolve. |
| | 2940 | 81 | | if (TryGetCultureInfo(option.Value, out var cultureInfo)) |
| | | 82 | | { |
| | 2940 | 83 | | cultures.Add(cultureInfo); |
| | | 84 | | } |
| | | 85 | | } |
| | | 86 | | |
| | 28 | 87 | | return cultures; |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Resolves a Jellyfin resource culture code (which may use underscores, e.g. <c>es_419</c>) |
| | | 92 | | /// to a <see cref="CultureInfo"/>. Returns <see langword="false"/> for codes .NET cannot resolve. |
| | | 93 | | /// </summary> |
| | | 94 | | private static bool TryGetCultureInfo(string cultureCode, [NotNullWhen(true)] out CultureInfo? cultureInfo) |
| | | 95 | | { |
| | | 96 | | try |
| | | 97 | | { |
| | | 98 | | // Resource files use underscores for some variants (e.g. es_419); |
| | | 99 | | // CultureInfo only accepts hyphenated BCP-47 codes. |
| | 3148 | 100 | | cultureInfo = CultureInfo.GetCultureInfo(cultureCode.Replace('_', '-')); |
| | 3148 | 101 | | return true; |
| | | 102 | | } |
| | 0 | 103 | | catch (CultureNotFoundException) |
| | | 104 | | { |
| | 0 | 105 | | cultureInfo = null; |
| | 0 | 106 | | return false; |
| | | 107 | | } |
| | 3148 | 108 | | } |
| | | 109 | | |
| | | 110 | | private static void OnConfigurationUpdated(object? sender, EventArgs e) |
| | | 111 | | { |
| | 125 | 112 | | if (sender is IServerConfigurationManager configManager) |
| | | 113 | | { |
| | 125 | 114 | | var uiCulture = configManager.Configuration.UICulture; |
| | 125 | 115 | | if (!string.IsNullOrEmpty(uiCulture)) |
| | | 116 | | { |
| | 125 | 117 | | CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(uiCulture); |
| | | 118 | | } |
| | | 119 | | } |
| | 125 | 120 | | } |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Loads all resources into memory. |
| | | 124 | | /// </summary> |
| | | 125 | | /// <returns><see cref="Task" />.</returns> |
| | | 126 | | public async Task LoadAll() |
| | | 127 | | { |
| | | 128 | | // Extract from the assembly |
| | 44676 | 129 | | foreach (var resource in _assembly.GetManifestResourceNames()) |
| | | 130 | | { |
| | 22192 | 131 | | if (!resource.StartsWith(RatingsPath, StringComparison.Ordinal)) |
| | | 132 | | { |
| | | 133 | | continue; |
| | | 134 | | } |
| | | 135 | | |
| | 6570 | 136 | | using var stream = _assembly.GetManifestResourceStream(resource); |
| | 6570 | 137 | | if (stream is not null) |
| | | 138 | | { |
| | 6570 | 139 | | var ratingSystem = await JsonSerializer.DeserializeAsync<ParentalRatingSystem>(stream, _jsonOptions) |
| | 6570 | 140 | | ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'"); |
| | | 141 | | |
| | | 142 | | // Rating strings are compared case insensitively, providers are not consistent about casing (e.g. " |
| | 6570 | 143 | | var dict = new Dictionary<string, ParentalRatingScore?>(StringComparer.OrdinalIgnoreCase); |
| | 6570 | 144 | | if (ratingSystem.Ratings is not null) |
| | | 145 | | { |
| | 105412 | 146 | | foreach (var ratingEntry in ratingSystem.Ratings) |
| | | 147 | | { |
| | 268640 | 148 | | foreach (var ratingString in ratingEntry.RatingStrings) |
| | | 149 | | { |
| | 88184 | 150 | | dict[ratingString] = ratingEntry.RatingScore; |
| | | 151 | | } |
| | | 152 | | } |
| | | 153 | | |
| | 6570 | 154 | | _allParentalRatings[ratingSystem.CountryCode] = dict; |
| | | 155 | | } |
| | | 156 | | } |
| | 6570 | 157 | | } |
| | | 158 | | |
| | 146 | 159 | | await LoadCultures().ConfigureAwait(false); |
| | 146 | 160 | | } |
| | | 161 | | |
| | | 162 | | /// <summary> |
| | | 163 | | /// Gets the cultures. |
| | | 164 | | /// </summary> |
| | | 165 | | /// <returns><see cref="IEnumerable{CultureDto}" />.</returns> |
| | | 166 | | public IEnumerable<CultureDto> GetCultures() |
| | 1 | 167 | | => _cultures; |
| | | 168 | | |
| | | 169 | | private async Task LoadCultures() |
| | | 170 | | { |
| | 146 | 171 | | List<CultureDto> list = []; |
| | 146 | 172 | | Dictionary<string, string> iso6392BtoTdict = new Dictionary<string, string>(); |
| | | 173 | | |
| | 146 | 174 | | using var stream = _assembly.GetManifestResourceStream(CulturesPath); |
| | 146 | 175 | | if (stream is null) |
| | | 176 | | { |
| | 0 | 177 | | throw new InvalidOperationException($"Invalid resource path: '{CulturesPath}'"); |
| | | 178 | | } |
| | | 179 | | else |
| | | 180 | | { |
| | 146 | 181 | | using var reader = new StreamReader(stream); |
| | 145124 | 182 | | await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false)) |
| | | 183 | | { |
| | 72416 | 184 | | if (string.IsNullOrWhiteSpace(line)) |
| | | 185 | | { |
| | | 186 | | continue; |
| | | 187 | | } |
| | | 188 | | |
| | 72416 | 189 | | var parts = line.Split('|'); |
| | 72416 | 190 | | if (parts.Length != 5) |
| | | 191 | | { |
| | 0 | 192 | | throw new InvalidDataException($"Invalid culture data found at: '{line}'"); |
| | | 193 | | } |
| | | 194 | | |
| | 72416 | 195 | | string name = parts[3]; |
| | 72416 | 196 | | string displayname = parts[3]; |
| | 72416 | 197 | | if (string.IsNullOrWhiteSpace(displayname)) |
| | | 198 | | { |
| | | 199 | | continue; |
| | | 200 | | } |
| | | 201 | | |
| | 72416 | 202 | | string twoCharName = parts[2]; |
| | 72416 | 203 | | if (string.IsNullOrWhiteSpace(twoCharName)) |
| | | 204 | | { |
| | 44092 | 205 | | twoCharName = string.Empty; |
| | | 206 | | } |
| | 28324 | 207 | | else if (twoCharName.Contains('-', StringComparison.OrdinalIgnoreCase)) |
| | | 208 | | { |
| | 1314 | 209 | | name = twoCharName; |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | string[] threeLetterNames; |
| | 72416 | 213 | | if (string.IsNullOrWhiteSpace(parts[1])) |
| | | 214 | | { |
| | 68620 | 215 | | threeLetterNames = [parts[0]]; |
| | | 216 | | } |
| | | 217 | | else |
| | | 218 | | { |
| | 3796 | 219 | | threeLetterNames = [parts[0], parts[1]]; |
| | | 220 | | |
| | | 221 | | // In cases where there are two TLN the first one is ISO 639-2/T and the second one is ISO 639-2 |
| | | 222 | | // We need ISO 639-2/T for the .NET cultures so we cultivate a dictionary for the translation B- |
| | 3796 | 223 | | iso6392BtoTdict.TryAdd(parts[1], parts[0]); |
| | | 224 | | } |
| | | 225 | | |
| | 72416 | 226 | | list.Add(new CultureDto(name, displayname, twoCharName, threeLetterNames)); |
| | | 227 | | } |
| | | 228 | | |
| | 146 | 229 | | _cultureCache.Clear(); |
| | 146 | 230 | | _cultures = list; |
| | 146 | 231 | | _iso6392BtoT = iso6392BtoTdict.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); |
| | 146 | 232 | | } |
| | 146 | 233 | | } |
| | | 234 | | |
| | | 235 | | /// <inheritdoc /> |
| | | 236 | | public CultureDto? FindLanguageInfo(string language) |
| | | 237 | | { |
| | 180 | 238 | | if (string.IsNullOrEmpty(language)) |
| | | 239 | | { |
| | 165 | 240 | | return null; |
| | | 241 | | } |
| | | 242 | | |
| | 15 | 243 | | return _cultureCache.GetOrAdd( |
| | 15 | 244 | | language, |
| | 15 | 245 | | static (lang, cultures) => |
| | 15 | 246 | | { |
| | 15 | 247 | | // TODO language should ideally be a ReadOnlySpan but moq cannot mock ref structs |
| | 15 | 248 | | for (var i = 0; i < cultures.Count; i++) |
| | 15 | 249 | | { |
| | 15 | 250 | | var culture = cultures[i]; |
| | 15 | 251 | | if (lang.Equals(culture.DisplayName, StringComparison.OrdinalIgnoreCase) |
| | 15 | 252 | | || lang.Equals(culture.Name, StringComparison.OrdinalIgnoreCase) |
| | 15 | 253 | | || culture.ThreeLetterISOLanguageNames.Contains(lang, StringComparison.OrdinalIgnoreCase) |
| | 15 | 254 | | || lang.Equals(culture.TwoLetterISOLanguageName, StringComparison.OrdinalIgnoreCase)) |
| | 15 | 255 | | { |
| | 15 | 256 | | return culture; |
| | 15 | 257 | | } |
| | 15 | 258 | | } |
| | 15 | 259 | | |
| | 15 | 260 | | return null; |
| | 15 | 261 | | }, |
| | 15 | 262 | | _cultures); |
| | | 263 | | } |
| | | 264 | | |
| | | 265 | | /// <inheritdoc /> |
| | | 266 | | public string? GetLanguageDisplayName(string language) |
| | | 267 | | { |
| | 8 | 268 | | if (string.IsNullOrEmpty(language)) |
| | | 269 | | { |
| | 2 | 270 | | return null; |
| | | 271 | | } |
| | | 272 | | |
| | 6 | 273 | | var displayName = FindLanguageInfo(language)?.DisplayName; |
| | 6 | 274 | | if (displayName is null) |
| | | 275 | | { |
| | 1 | 276 | | return null; |
| | | 277 | | } |
| | | 278 | | |
| | | 279 | | // Truncate at the first delimiter to avoid cluttered display names |
| | 5 | 280 | | return displayName.Split([';', ','], StringSplitOptions.None)[0].Trim(); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | /// <inheritdoc /> |
| | | 284 | | public IReadOnlyList<CountryInfo> GetCountries() |
| | | 285 | | { |
| | 1 | 286 | | using var stream = _assembly.GetManifestResourceStream(CountriesPath) ?? throw new InvalidOperationException |
| | | 287 | | |
| | 1 | 288 | | return JsonSerializer.Deserialize<IReadOnlyList<CountryInfo>>(stream, _jsonOptions) ?? []; |
| | 1 | 289 | | } |
| | | 290 | | |
| | | 291 | | /// <inheritdoc /> |
| | | 292 | | public IReadOnlyList<ParentalRating> GetParentalRatings() |
| | | 293 | | { |
| | | 294 | | // Use server default language for ratings |
| | | 295 | | // Fall back to empty list if there are no parental ratings for that language |
| | 2 | 296 | | var ratings = GetParentalRatingsDictionary()?.Select(x => new ParentalRating(x.Key, x.Value)).ToList() ?? [] |
| | | 297 | | |
| | | 298 | | // Add common ratings to ensure them being available for selection |
| | | 299 | | // Based on the US rating system due to it being the main source of rating in the metadata providers |
| | | 300 | | // Unrated |
| | 2 | 301 | | if (!ratings.Any(x => x is null)) |
| | | 302 | | { |
| | 2 | 303 | | ratings.Add(new("Unrated", null)); |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | // Minimum rating possible |
| | 2 | 307 | | if (ratings.All(x => x.RatingScore?.Score != 0)) |
| | | 308 | | { |
| | 0 | 309 | | ratings.Add(new("Approved", new(0, null))); |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | // Matches PG (this has different age restrictions depending on country) |
| | 2 | 313 | | if (ratings.All(x => x.RatingScore?.Score != 10)) |
| | | 314 | | { |
| | 1 | 315 | | ratings.Add(new("10", new(10, null))); |
| | | 316 | | } |
| | | 317 | | |
| | | 318 | | // Matches PG-13 |
| | 2 | 319 | | if (ratings.All(x => x.RatingScore?.Score != 13)) |
| | | 320 | | { |
| | 1 | 321 | | ratings.Add(new("13", new(13, null))); |
| | | 322 | | } |
| | | 323 | | |
| | | 324 | | // Matches TV-14 |
| | 2 | 325 | | if (ratings.All(x => x.RatingScore?.Score != 14)) |
| | | 326 | | { |
| | 1 | 327 | | ratings.Add(new("14", new(14, null))); |
| | | 328 | | } |
| | | 329 | | |
| | | 330 | | // Catchall if max rating of country is less than 21 |
| | | 331 | | // Using 21 instead of 18 to be sure to allow access to all rated content except adult and banned |
| | 2 | 332 | | if (!ratings.Any(x => x.RatingScore?.Score >= 21)) |
| | | 333 | | { |
| | 2 | 334 | | ratings.Add(new ParentalRating("21", new(21, null))); |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | // A lot of countries don't explicitly have a separate rating for adult content |
| | 2 | 338 | | if (ratings.All(x => x.RatingScore?.Score != 1000)) |
| | | 339 | | { |
| | 2 | 340 | | ratings.Add(new ParentalRating("XXX", new(1000, null))); |
| | | 341 | | } |
| | | 342 | | |
| | | 343 | | // A lot of countries don't explicitly have a separate rating for banned content |
| | 2 | 344 | | if (ratings.All(x => x.RatingScore?.Score != 1001)) |
| | | 345 | | { |
| | 2 | 346 | | ratings.Add(new ParentalRating("Banned", new(1001, null))); |
| | | 347 | | } |
| | | 348 | | |
| | 2 | 349 | | return [.. ratings.OrderBy(r => r.RatingScore?.Score).ThenBy(r => r.RatingScore?.SubScore)]; |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | /// <summary> |
| | | 353 | | /// Gets the parental ratings dictionary. |
| | | 354 | | /// </summary> |
| | | 355 | | /// <param name="countryCode">The optional two letter ISO language string.</param> |
| | | 356 | | /// <returns><see cref="Dictionary{String, ParentalRatingScore}" />.</returns> |
| | | 357 | | private Dictionary<string, ParentalRatingScore?>? GetParentalRatingsDictionary(string? countryCode = null) |
| | | 358 | | { |
| | | 359 | | // Fallback to server default if no country code is specified. |
| | 101 | 360 | | if (string.IsNullOrEmpty(countryCode)) |
| | | 361 | | { |
| | 101 | 362 | | countryCode = _configurationManager.Configuration.MetadataCountryCode; |
| | | 363 | | } |
| | | 364 | | |
| | 101 | 365 | | if (_allParentalRatings.TryGetValue(countryCode, out var countryValue)) |
| | | 366 | | { |
| | 100 | 367 | | return countryValue; |
| | | 368 | | } |
| | | 369 | | |
| | 1 | 370 | | return null; |
| | | 371 | | } |
| | | 372 | | |
| | | 373 | | /// <inheritdoc /> |
| | | 374 | | public ParentalRatingScore? GetRatingScore(string rating, string? countryCode = null) |
| | | 375 | | { |
| | 105 | 376 | | ArgumentException.ThrowIfNullOrEmpty(rating); |
| | | 377 | | |
| | | 378 | | // Handle unrated content. This has to happen before the split below, |
| | | 379 | | // because some of the unrated values contain a '/' themselves (e.g. "n/a"). |
| | 105 | 380 | | if (IsUnrated(rating)) |
| | | 381 | | { |
| | 6 | 382 | | return null; |
| | | 383 | | } |
| | | 384 | | |
| | | 385 | | // Several rating systems contain a '/' inside a single rating (e.g. "M/12" in PT, |
| | | 386 | | // "U/A 13+" in IN, "7/i/fig" in ES), so the value as a whole always wins over the split below. |
| | 99 | 387 | | var wholeValueScore = GetSingleRatingScore(rating, countryCode); |
| | 99 | 388 | | if (wholeValueScore is not null) |
| | | 389 | | { |
| | 84 | 390 | | return wholeValueScore; |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | // Some providers may list multiple ratings separated by '/' (e.g. "SE:15 / SE:15+ / SE:Från 15 år"). |
| | | 394 | | // Try each one in order and use the first that resolves. |
| | 15 | 395 | | var ratingValues = rating.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 15 | 396 | | if (ratingValues.Length == 1) |
| | | 397 | | { |
| | 6 | 398 | | return null; |
| | | 399 | | } |
| | | 400 | | |
| | 9 | 401 | | var hasUnknownRating = false; |
| | 36 | 402 | | foreach (var ratingValue in ratingValues) |
| | | 403 | | { |
| | | 404 | | // A single entry of such a list may be unrated while a later one still resolves |
| | 13 | 405 | | if (IsUnrated(ratingValue)) |
| | | 406 | | { |
| | | 407 | | continue; |
| | | 408 | | } |
| | | 409 | | |
| | | 410 | | // An unknown entry is not worth a warning of its own as long as another entry still resolves |
| | 11 | 411 | | var score = GetSingleRatingScore(ratingValue, countryCode, logUnknownRating: false); |
| | 11 | 412 | | if (score is not null) |
| | | 413 | | { |
| | 8 | 414 | | return score; |
| | | 415 | | } |
| | | 416 | | |
| | 3 | 417 | | hasUnknownRating = true; |
| | | 418 | | } |
| | | 419 | | |
| | 1 | 420 | | if (hasUnknownRating) |
| | | 421 | | { |
| | 1 | 422 | | _logger.LogWarning( |
| | 1 | 423 | | "None of the ratings in '{Rating}' were found in a known rating system, treating as unrated", |
| | 1 | 424 | | rating); |
| | | 425 | | } |
| | | 426 | | |
| | 1 | 427 | | return null; |
| | | 428 | | } |
| | | 429 | | |
| | | 430 | | /// <summary> |
| | | 431 | | /// Checks whether a rating value marks the content as unrated. |
| | | 432 | | /// </summary> |
| | | 433 | | /// <param name="rating">Rating value to check.</param> |
| | | 434 | | /// <returns>Returns true if the value is an unrated marker.</returns> |
| | | 435 | | private static bool IsUnrated(ReadOnlySpan<char> rating) |
| | 125 | 436 | | => _unratedValues.Contains(rating.Trim(), StringComparison.OrdinalIgnoreCase); |
| | | 437 | | |
| | | 438 | | /// <summary> |
| | | 439 | | /// Resolves a single rating value to a score. |
| | | 440 | | /// </summary> |
| | | 441 | | private ParentalRatingScore? GetSingleRatingScore(string rating, string? countryCode, bool logUnknownRating = tr |
| | | 442 | | { |
| | | 443 | | // Convert ints directly |
| | | 444 | | // This may override some of the locale specific age ratings (but those always map to the same age) |
| | 110 | 445 | | if (TryParseRatingAsScore(rating, out var ratingAge)) |
| | | 446 | | { |
| | 11 | 447 | | return new(ratingAge, null); |
| | | 448 | | } |
| | | 449 | | |
| | | 450 | | // Fairly common for some users to have "Rated R" in their rating field |
| | 99 | 451 | | rating = rating.Replace("Rated :", string.Empty, StringComparison.OrdinalIgnoreCase) |
| | 99 | 452 | | .Replace("Rated:", string.Empty, StringComparison.OrdinalIgnoreCase) |
| | 99 | 453 | | .Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase) |
| | 99 | 454 | | .Trim(); |
| | | 455 | | |
| | | 456 | | // Use rating system matching the language |
| | 99 | 457 | | if (!string.IsNullOrEmpty(countryCode)) |
| | | 458 | | { |
| | 0 | 459 | | var ratingsDictionary = GetParentalRatingsDictionary(countryCode); |
| | 0 | 460 | | if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRatingScore? valu |
| | | 461 | | { |
| | 0 | 462 | | return value; |
| | | 463 | | } |
| | | 464 | | |
| | 0 | 465 | | if (ratingsDictionary is not null && rating.Length > countryCode.Length |
| | 0 | 466 | | && rating.StartsWith(countryCode, StringComparison.OrdinalIgnoreCase) |
| | 0 | 467 | | && (rating[countryCode.Length] == '-' || rating[countryCode.Length] == ':') |
| | 0 | 468 | | && ratingsDictionary.TryGetValue(rating[(countryCode.Length + 1)..].Trim(), out var normalizedValue) |
| | | 469 | | { |
| | 0 | 470 | | return normalizedValue; |
| | | 471 | | } |
| | | 472 | | } |
| | | 473 | | else |
| | | 474 | | { |
| | | 475 | | // Fall back to server default language for ratings check |
| | 99 | 476 | | var ratingsDictionary = GetParentalRatingsDictionary(); |
| | 99 | 477 | | if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRatingScore? valu |
| | | 478 | | { |
| | 52 | 479 | | return value; |
| | | 480 | | } |
| | | 481 | | } |
| | | 482 | | |
| | | 483 | | // If we don't find anything, check all ratings systems, starting with US |
| | 47 | 484 | | if (_allParentalRatings.TryGetValue("us", out var usRatings) && usRatings.TryGetValue(rating, out var usValu |
| | | 485 | | { |
| | 3 | 486 | | return usValue; |
| | | 487 | | } |
| | | 488 | | |
| | 3696 | 489 | | foreach (var dictionary in _allParentalRatings.Values) |
| | | 490 | | { |
| | 1806 | 491 | | if (dictionary.TryGetValue(rating, out var value)) |
| | | 492 | | { |
| | 4 | 493 | | return value; |
| | | 494 | | } |
| | | 495 | | } |
| | | 496 | | |
| | | 497 | | // Try splitting by country prefix separator to handle "US:PG-13", "Germany: FSK-18", "DE-FSK-18". |
| | | 498 | | // A '/' marks a list of ratings, which this would split into the first entry's country and the last entry's |
| | 40 | 499 | | if (!rating.Contains('/', StringComparison.Ordinal) |
| | 40 | 500 | | && (TryGetRatingScoreBySeparator(rating, ':', logUnknownRating, out var result) |
| | 40 | 501 | | || TryGetRatingScoreBySeparator(rating, '-', logUnknownRating, out result))) |
| | | 502 | | { |
| | 29 | 503 | | return result; |
| | | 504 | | } |
| | | 505 | | |
| | 11 | 506 | | return null; |
| | 4 | 507 | | } |
| | | 508 | | |
| | | 509 | | private bool TryGetRatingScoreBySeparator(string rating, char separator, bool logUnknownRating, out ParentalRati |
| | | 510 | | { |
| | 48 | 511 | | result = null; |
| | | 512 | | |
| | 48 | 513 | | if (rating.IndexOf(separator, StringComparison.Ordinal) < 0) |
| | | 514 | | { |
| | 17 | 515 | | return false; |
| | | 516 | | } |
| | | 517 | | |
| | 31 | 518 | | var ratingSpan = rating.AsSpan(); |
| | 31 | 519 | | var countryPart = ratingSpan.LeftPart(separator).Trim().ToString(); |
| | 31 | 520 | | var ratingPart = ratingSpan.RightPart(separator).Trim().ToString(); |
| | 31 | 521 | | if (ratingPart.Length == 0) |
| | | 522 | | { |
| | 2 | 523 | | return false; |
| | | 524 | | } |
| | | 525 | | |
| | 29 | 526 | | string? resolvedCountryCode = null; |
| | | 527 | | |
| | 29 | 528 | | if (_allParentalRatings.ContainsKey(countryPart)) |
| | | 529 | | { |
| | 28 | 530 | | resolvedCountryCode = countryPart; |
| | | 531 | | } |
| | | 532 | | else |
| | | 533 | | { |
| | 1 | 534 | | var culture = FindLanguageInfo(countryPart); |
| | 1 | 535 | | if (culture is not null) |
| | | 536 | | { |
| | 0 | 537 | | resolvedCountryCode = culture.TwoLetterISOLanguageName; |
| | | 538 | | } |
| | | 539 | | } |
| | | 540 | | |
| | 29 | 541 | | if (resolvedCountryCode is not null |
| | 29 | 542 | | && _allParentalRatings.TryGetValue(resolvedCountryCode, out var countryRatings)) |
| | | 543 | | { |
| | 28 | 544 | | if (countryRatings.TryGetValue(ratingPart, out result)) |
| | | 545 | | { |
| | 21 | 546 | | return true; |
| | | 547 | | } |
| | | 548 | | |
| | | 549 | | // If it's not a recognized rating string, fall back to using the number as the score |
| | 7 | 550 | | if (TryParseRatingAsScore(ratingPart, out var numericScore)) |
| | | 551 | | { |
| | 0 | 552 | | result = new ParentalRatingScore(numericScore, null); |
| | 0 | 553 | | return true; |
| | | 554 | | } |
| | | 555 | | |
| | | 556 | | // Explicitly unrated content (e.g. "IT-NR") is unrated by definition, not a lookup failure |
| | 7 | 557 | | if (IsUnrated(ratingPart)) |
| | | 558 | | { |
| | 0 | 559 | | return true; |
| | | 560 | | } |
| | | 561 | | |
| | 7 | 562 | | if (logUnknownRating) |
| | | 563 | | { |
| | 4 | 564 | | _logger.LogWarning( |
| | 4 | 565 | | "Rating '{Rating}' not found in the '{CountryCode}' rating system, treating as unrated", |
| | 4 | 566 | | rating, |
| | 4 | 567 | | resolvedCountryCode); |
| | | 568 | | } |
| | | 569 | | |
| | 7 | 570 | | return true; |
| | | 571 | | } |
| | | 572 | | |
| | | 573 | | // Country not identified or no rating data available, try recursive lookup |
| | 1 | 574 | | result = GetRatingScore(ratingPart, resolvedCountryCode); |
| | | 575 | | |
| | 1 | 576 | | return true; |
| | | 577 | | } |
| | | 578 | | |
| | | 579 | | /// <summary> |
| | | 580 | | /// Tries to parse a rating as a number, allowing an optional trailing '+' (e.g. "16" or "18+") |
| | | 581 | | /// or a leading '-' (e.g. the French "-12"). |
| | | 582 | | /// </summary> |
| | | 583 | | /// <param name="ratingValue">Rating value to parse.</param> |
| | | 584 | | /// <param name="score">Parsed score.</param> |
| | | 585 | | /// <returns>Returns true if parsing was successful.</returns> |
| | | 586 | | private static bool TryParseRatingAsScore(ReadOnlySpan<char> ratingValue, out int score) |
| | | 587 | | { |
| | | 588 | | // A leading '-' marks a minimum age ("-12" is French for "not for under 12s"), never a negative score |
| | 117 | 589 | | var trimmed = ratingValue.TrimStart('-').TrimEnd('+'); |
| | 117 | 590 | | return int.TryParse(trimmed, out score); |
| | | 591 | | } |
| | | 592 | | |
| | | 593 | | /// <inheritdoc /> |
| | | 594 | | public string GetLocalizedString(string phrase) |
| | | 595 | | { |
| | 553 | 596 | | return GetLocalizedString(phrase, CultureInfo.CurrentUICulture.Name); |
| | | 597 | | } |
| | | 598 | | |
| | | 599 | | /// <inheritdoc /> |
| | | 600 | | public string GetServerLocalizedString(string phrase) |
| | | 601 | | { |
| | 77 | 602 | | return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture); |
| | | 603 | | } |
| | | 604 | | |
| | | 605 | | /// <inheritdoc /> |
| | | 606 | | public string GetLocalizedString(string phrase, string culture) |
| | | 607 | | { |
| | 634 | 608 | | if (string.IsNullOrEmpty(culture)) |
| | | 609 | | { |
| | 0 | 610 | | culture = _configurationManager.Configuration.UICulture; |
| | | 611 | | } |
| | | 612 | | |
| | 634 | 613 | | if (string.IsNullOrEmpty(culture)) |
| | | 614 | | { |
| | 0 | 615 | | culture = DefaultCulture; |
| | | 616 | | } |
| | | 617 | | |
| | | 618 | | // Normalize BCP-47 hyphenated codes to Jellyfin's underscore-based codes |
| | 634 | 619 | | if (_bcp47ToJellyfinMap.TryGetValue(culture, out var mapped)) |
| | | 620 | | { |
| | 2 | 621 | | culture = mapped; |
| | | 622 | | } |
| | | 623 | | |
| | 634 | 624 | | var dictionary = GetLocalizationDictionary(culture); |
| | | 625 | | |
| | 634 | 626 | | if (dictionary.TryGetValue(phrase, out var value)) |
| | | 627 | | { |
| | 625 | 628 | | return value; |
| | | 629 | | } |
| | | 630 | | |
| | 9 | 631 | | if (!string.Equals(culture, DefaultCulture, StringComparison.OrdinalIgnoreCase)) |
| | | 632 | | { |
| | 8 | 633 | | var fallback = GetLocalizationDictionary(DefaultCulture); |
| | 8 | 634 | | if (fallback.TryGetValue(phrase, out var fallbackValue)) |
| | | 635 | | { |
| | 8 | 636 | | return fallbackValue; |
| | | 637 | | } |
| | | 638 | | } |
| | | 639 | | |
| | 1 | 640 | | return phrase; |
| | | 641 | | } |
| | | 642 | | |
| | | 643 | | private Dictionary<string, string> GetLocalizationDictionary(string culture) |
| | | 644 | | { |
| | 642 | 645 | | ArgumentException.ThrowIfNullOrEmpty(culture); |
| | | 646 | | |
| | 642 | 647 | | return _cultureOnlyDictionaries.GetOrAdd( |
| | 642 | 648 | | culture, |
| | 642 | 649 | | static (key, localizationManager) => |
| | 642 | 650 | | { |
| | 642 | 651 | | var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| | 642 | 652 | | var namespaceName = localizationManager.GetType().Namespace + ".Core"; |
| | 642 | 653 | | localizationManager.CopyInto(dictionary, namespaceName + "." + GetResourceFilename(key)).GetAwaiter( |
| | 642 | 654 | | |
| | 642 | 655 | | return dictionary; |
| | 642 | 656 | | }, |
| | 642 | 657 | | this); |
| | | 658 | | } |
| | | 659 | | |
| | | 660 | | private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath) |
| | | 661 | | { |
| | 38 | 662 | | using var stream = _assembly.GetManifestResourceStream(resourcePath); |
| | | 663 | | // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the c |
| | 38 | 664 | | if (stream is null) |
| | | 665 | | { |
| | 2 | 666 | | _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath); |
| | 2 | 667 | | return; |
| | | 668 | | } |
| | | 669 | | |
| | 36 | 670 | | var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).Configure |
| | 8902 | 671 | | foreach (var key in dict.Keys) |
| | | 672 | | { |
| | 4415 | 673 | | dictionary[key] = dict[key]; |
| | | 674 | | } |
| | 38 | 675 | | } |
| | | 676 | | |
| | | 677 | | private static string GetResourceFilename(string culture) |
| | | 678 | | { |
| | | 679 | | // Region codes may use a '-' (BCP-47, e.g. "pt-BR") or '_' (e.g. "es_419", "ar_SA") separator. |
| | | 680 | | // Normalize the casing (lower-case language, upper-case region) while preserving the separator |
| | | 681 | | // so the result matches the embedded resource file name, which is case-sensitive. |
| | 38 | 682 | | var separatorIndex = culture.IndexOfAny(['-', '_']); |
| | | 683 | | |
| | 38 | 684 | | if (separatorIndex > 0) |
| | | 685 | | { |
| | 33 | 686 | | var separator = culture[separatorIndex]; |
| | 33 | 687 | | culture = culture[..separatorIndex].ToLowerInvariant() + separator + culture[(separatorIndex + 1)..].ToU |
| | | 688 | | } |
| | | 689 | | else |
| | | 690 | | { |
| | 5 | 691 | | culture = culture.ToLowerInvariant(); |
| | | 692 | | } |
| | | 693 | | |
| | 38 | 694 | | return culture + ".json"; |
| | | 695 | | } |
| | | 696 | | |
| | | 697 | | /// <inheritdoc /> |
| | | 698 | | public IEnumerable<LocalizationOption> GetLocalizationOptions() |
| | | 699 | | { |
| | 0 | 700 | | return _localizationOptions; |
| | | 701 | | } |
| | | 702 | | |
| | | 703 | | private static (IReadOnlyList<LocalizationOption> Options, FrozenDictionary<string, string> Bcp47ToJellyfinMap) |
| | | 704 | | { |
| | 2 | 705 | | var options = new List<LocalizationOption>(); |
| | 2 | 706 | | var bcp47Map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); |
| | 2 | 707 | | var prefix = CoreResourcePrefix; |
| | | 708 | | |
| | 612 | 709 | | foreach (var resource in _assembly.GetManifestResourceNames()) |
| | | 710 | | { |
| | 304 | 711 | | if (!resource.StartsWith(prefix, StringComparison.Ordinal) |
| | 304 | 712 | | || !resource.EndsWith(".json", StringComparison.Ordinal)) |
| | | 713 | | { |
| | | 714 | | continue; |
| | | 715 | | } |
| | | 716 | | |
| | | 717 | | // Extract culture code from resource name: "...Core.de.json" -> "de", "...Core.pt-BR.json" -> "pt-BR" |
| | 210 | 718 | | var code = resource[prefix.Length..^5]; |
| | | 719 | | |
| | | 720 | | // Record the BCP-47 → Jellyfin mapping for any resource file using underscores. |
| | 210 | 721 | | if (code.Contains('_', StringComparison.Ordinal)) |
| | | 722 | | { |
| | 10 | 723 | | bcp47Map[code.Replace('_', '-')] = code; |
| | | 724 | | } |
| | | 725 | | |
| | | 726 | | // Skip the base language file — en-US is added explicitly below |
| | 210 | 727 | | if (code.Equals(DefaultCulture, StringComparison.OrdinalIgnoreCase)) |
| | | 728 | | { |
| | | 729 | | continue; |
| | | 730 | | } |
| | | 731 | | |
| | 208 | 732 | | var displayName = GetDisplayName(code); |
| | 208 | 733 | | options.Add(new LocalizationOption(displayName, code)); |
| | | 734 | | } |
| | | 735 | | |
| | | 736 | | // Ensure en-US is always present |
| | 2 | 737 | | options.Add(new LocalizationOption("English", DefaultCulture)); |
| | | 738 | | |
| | 2 | 739 | | options.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); |
| | 2 | 740 | | return (options, bcp47Map.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase)); |
| | | 741 | | } |
| | | 742 | | |
| | | 743 | | private static string GetDisplayName(string cultureCode) |
| | | 744 | | { |
| | | 745 | | // Custom/novelty codes like "pr" (Pirate) — fall back to code itself |
| | 208 | 746 | | return TryGetCultureInfo(cultureCode, out var cultureInfo) |
| | 208 | 747 | | ? cultureInfo.NativeName |
| | 208 | 748 | | : cultureCode; |
| | | 749 | | } |
| | | 750 | | |
| | | 751 | | /// <inheritdoc /> |
| | | 752 | | public bool TryGetISO6392TFromB(string isoB, [NotNullWhen(true)] out string? isoT) |
| | | 753 | | { |
| | | 754 | | // Unlikely case the dictionary is not (yet) initialized properly |
| | 3 | 755 | | if (_iso6392BtoT is null) |
| | | 756 | | { |
| | 0 | 757 | | isoT = null; |
| | 0 | 758 | | return false; |
| | | 759 | | } |
| | | 760 | | |
| | 3 | 761 | | var result = _iso6392BtoT.TryGetValue(isoB, out isoT) && !string.IsNullOrEmpty(isoT); |
| | | 762 | | |
| | | 763 | | // Ensure the ISO code being null if the result is false |
| | 3 | 764 | | if (!result) |
| | | 765 | | { |
| | 1 | 766 | | isoT = null; |
| | | 767 | | } |
| | | 768 | | |
| | 3 | 769 | | return result; |
| | | 770 | | } |
| | | 771 | | } |
| | | 772 | | } |