jellyfin/Emby.Server.Implementations/Localization/LocalizationManager.cs

505 lines
21 KiB
C#
Raw Normal View History

using System;
2013-06-10 19:34:55 -07:00
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
2022-10-09 13:56:23 -07:00
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using Jellyfin.Extensions;
using Jellyfin.Extensions.Json;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using Microsoft.Extensions.Logging;
2016-11-04 19:17:18 -07:00
namespace Emby.Server.Implementations.Localization
{
/// <summary>
2019-08-16 08:31:47 -07:00
/// Class LocalizationManager.
/// </summary>
public class LocalizationManager : ILocalizationManager
{
2019-08-16 08:31:47 -07:00
private const string DefaultCulture = "en-US";
2021-08-10 05:03:15 -07:00
private const string RatingsPath = "Emby.Server.Implementations.Localization.Ratings.";
private const string CulturesPath = "Emby.Server.Implementations.Localization.iso6392.txt";
private const string CountriesPath = "Emby.Server.Implementations.Localization.countries.json";
2019-08-16 08:31:47 -07:00
private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
2022-10-09 13:56:23 -07:00
private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated", "nr" };
private readonly IServerConfigurationManager _configurationManager;
private readonly ILogger<LocalizationManager> _logger;
2018-09-12 10:26:21 -07:00
private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
2013-06-10 19:34:55 -07:00
2019-08-16 08:31:47 -07:00
private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
2021-08-15 08:20:07 -07:00
private List<CultureDto> _cultures = new List<CultureDto>();
/// <summary>
2014-06-04 19:32:40 -07:00
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
2019-08-16 08:31:47 -07:00
/// <param name="logger">The logger.</param>
public LocalizationManager(
IServerConfigurationManager configurationManager,
2019-08-16 08:31:47 -07:00
ILogger<LocalizationManager> logger)
{
_configurationManager = configurationManager;
2019-08-16 08:31:47 -07:00
_logger = logger;
2013-06-18 13:54:32 -07:00
}
/// <summary>
/// Loads all resources into memory.
/// </summary>
/// <returns><see cref="Task" />.</returns>
public async Task LoadAll()
{
// Extract from the assembly
foreach (var resource in _assembly.GetManifestResourceNames())
{
2021-08-10 05:03:15 -07:00
if (!resource.StartsWith(RatingsPath, StringComparison.Ordinal))
{
continue;
}
2021-08-10 05:03:15 -07:00
string countryCode = resource.Substring(RatingsPath.Length, 2);
var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
var stream = _assembly.GetManifestResourceStream(resource);
await using (stream!.ConfigureAwait(false)) // shouldn't be null here, we just got the resource path from Assembly.GetManifestResourceNames()
{
using var reader = new StreamReader(stream!);
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
2021-08-10 05:03:15 -07:00
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
2021-08-10 05:03:15 -07:00
string[] parts = line.Split(',');
if (parts.Length == 2
&& int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
var name = parts[0];
dict.Add(name, new ParentalRating(name, value));
}
else
{
_logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
}
}
}
_allParentalRatings[countryCode] = dict;
}
await LoadCultures().ConfigureAwait(false);
}
/// <summary>
/// Gets the cultures.
/// </summary>
2019-08-16 08:31:47 -07:00
/// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
public IEnumerable<CultureDto> GetCultures()
=> _cultures;
private async Task LoadCultures()
{
List<CultureDto> list = new List<CultureDto>();
2021-08-15 08:20:07 -07:00
await using var stream = _assembly.GetManifestResourceStream(CulturesPath)
?? throw new InvalidOperationException($"Invalid resource path: '{CulturesPath}'");
2021-08-10 05:03:15 -07:00
using var reader = new StreamReader(stream);
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
2021-08-10 05:03:15 -07:00
if (string.IsNullOrWhiteSpace(line))
{
2021-08-10 05:03:15 -07:00
continue;
}
var parts = line.Split('|');
if (parts.Length == 5)
{
string name = parts[3];
if (string.IsNullOrWhiteSpace(name))
{
continue;
}
2021-08-10 05:03:15 -07:00
string twoCharName = parts[2];
if (string.IsNullOrWhiteSpace(twoCharName))
{
continue;
}
2021-08-10 05:03:15 -07:00
string[] threeletterNames;
if (string.IsNullOrWhiteSpace(parts[1]))
{
threeletterNames = new[] { parts[0] };
}
else
{
2021-08-10 05:03:15 -07:00
threeletterNames = new[] { parts[0], parts[1] };
}
2021-08-10 05:03:15 -07:00
2022-01-22 07:40:05 -07:00
list.Add(new CultureDto(name, name, twoCharName, threeletterNames));
}
}
_cultures = list;
}
2019-08-16 08:31:47 -07:00
/// <inheritdoc />
2021-08-15 08:20:07 -07:00
public CultureDto? FindLanguageInfo(string language)
2021-05-23 15:30:41 -07:00
{
// TODO language should ideally be a ReadOnlySpan but moq cannot mock ref structs
for (var i = 0; i < _cultures.Count; i++)
{
var culture = _cultures[i];
if (language.Equals(culture.DisplayName, StringComparison.OrdinalIgnoreCase)
|| language.Equals(culture.Name, StringComparison.OrdinalIgnoreCase)
|| culture.ThreeLetterISOLanguageNames.Contains(language, StringComparison.OrdinalIgnoreCase)
|| language.Equals(culture.TwoLetterISOLanguageName, StringComparison.OrdinalIgnoreCase))
{
return culture;
}
}
return default;
}
2018-09-12 10:26:21 -07:00
2019-08-16 08:31:47 -07:00
/// <inheritdoc />
public IEnumerable<CountryInfo> GetCountries()
{
2021-08-15 08:20:07 -07:00
using StreamReader reader = new StreamReader(
_assembly.GetManifestResourceStream(CountriesPath) ?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'"));
return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions)
?? throw new InvalidOperationException($"Resource contains invalid data: '{CountriesPath}'");
}
2019-08-16 08:31:47 -07:00
/// <inheritdoc />
public IEnumerable<ParentalRating> GetParentalRatings()
2022-11-29 14:04:28 -07:00
{
2023-03-09 06:13:57 -07:00
// Use server default language for ratings
// Fall back to empty list if there are no parental ratings for that language
var ratings = GetParentalRatingsDictionary()?.Values.ToList()
?? new List<ParentalRating>();
2022-11-29 14:04:28 -07:00
2023-03-09 06:13:57 -07:00
// Add common ratings to ensure them being available for selection
2022-11-29 14:04:28 -07:00
// Based on the US rating system due to it being the main source of rating in the metadata providers
2023-03-09 06:13:57 -07:00
// Unrated
if (!ratings.Any(x => x.Value is null))
{
ratings.Add(new ParentalRating("Unrated", null));
}
2022-11-29 14:04:28 -07:00
// Minimum rating possible
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 0))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("Approved", 0));
}
2022-12-08 08:15:26 -07:00
// Matches PG (this has different age restrictions depending on country)
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 10))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("10", 10));
}
// Matches PG-13
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 13))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("13", 13));
}
// Matches TV-14
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 14))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("14", 14));
}
// Catchall if max rating of country is less than 21
// Using 21 instead of 18 to be sure to allow access to all rated content except adult and banned
if (!ratings.Any(x => x.Value >= 21))
{
ratings.Add(new ParentalRating("21", 21));
}
// A lot of countries don't excplicitly have a seperate rating for adult content
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 1000))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("XXX", 1000));
}
// A lot of countries don't excplicitly have a seperate rating for banned content
2023-04-06 10:27:57 -07:00
if (ratings.All(x => x.Value != 1001))
2022-11-29 14:04:28 -07:00
{
ratings.Add(new ParentalRating("Banned", 1001));
}
return ratings.OrderBy(r => r.Value);
}
2013-06-10 19:34:55 -07:00
/// <summary>
/// Gets the parental ratings dictionary.
/// </summary>
2023-03-09 06:13:57 -07:00
/// <param name="countryCode">The optional two letter ISO language string.</param>
/// <returns><see cref="Dictionary{String, ParentalRating}" />.</returns>
2023-03-09 06:13:57 -07:00
private Dictionary<string, ParentalRating>? GetParentalRatingsDictionary(string? countryCode = null)
{
2023-03-09 06:13:57 -07:00
// Fallback to server default if no country code is specified.
if (string.IsNullOrEmpty(countryCode))
{
2023-03-09 06:13:57 -07:00
countryCode = _configurationManager.Configuration.MetadataCountryCode;
}
2023-03-09 06:13:57 -07:00
if (_allParentalRatings.TryGetValue(countryCode, out var countryValue))
{
return countryValue;
}
2023-03-09 06:13:57 -07:00
return null;
}
2019-03-13 14:32:52 -07:00
/// <inheritdoc />
2023-03-09 06:13:57 -07:00
public int? GetRatingLevel(string rating, string? countryCode = null)
{
ArgumentException.ThrowIfNullOrEmpty(rating);
2022-10-09 13:56:23 -07:00
// Handle unrated content
2021-05-23 15:30:41 -07:00
if (_unratedValues.Contains(rating.AsSpan(), StringComparison.OrdinalIgnoreCase))
2015-11-06 08:02:22 -07:00
{
return null;
}
2015-05-11 09:32:15 -07:00
// Fairly common for some users to have "Rated R" in their rating field
2022-10-09 13:56:23 -07:00
rating = rating.Replace("Rated :", string.Empty, StringComparison.OrdinalIgnoreCase);
2015-05-11 09:32:15 -07:00
rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
2023-03-09 06:13:57 -07:00
// Use rating system matching the language
if (!string.IsNullOrEmpty(countryCode))
2013-06-10 19:34:55 -07:00
{
2023-03-09 06:13:57 -07:00
var ratingsDictionary = GetParentalRatingsDictionary(countryCode);
if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
{
return value.Value;
}
}
else
{
// Fall back to server default language for ratings check
// If it has no ratings, use the US ratings
var ratingsDictionary = GetParentalRatingsDictionary() ?? GetParentalRatingsDictionary("us");
if (ratingsDictionary is not null && ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
{
return value.Value;
}
2018-09-12 10:26:21 -07:00
}
2023-03-09 06:13:57 -07:00
// If we don't find anything, check all ratings systems
2018-09-12 10:26:21 -07:00
foreach (var dictionary in _allParentalRatings.Values)
{
2023-03-09 06:13:57 -07:00
if (dictionary.TryGetValue(rating, out var value))
2013-06-18 13:54:32 -07:00
{
2018-09-12 10:26:21 -07:00
return value.Value;
}
}
2023-03-09 06:13:57 -07:00
// Try splitting by : to handle "Germany: FSK-18"
2023-01-27 07:49:08 -07:00
if (rating.Contains(':', StringComparison.OrdinalIgnoreCase))
2018-09-12 10:26:21 -07:00
{
2023-01-27 07:49:08 -07:00
return GetRatingLevel(rating.AsSpan().RightPart(':').ToString());
2013-06-10 19:34:55 -07:00
}
2023-03-09 06:13:57 -07:00
// Handle prefix country code to handle "DE-18"
2023-01-27 07:49:08 -07:00
if (rating.Contains('-', StringComparison.OrdinalIgnoreCase))
2022-10-09 13:56:23 -07:00
{
2023-03-09 06:13:57 -07:00
var ratingSpan = rating.AsSpan();
// Extract culture from country prefix
var culture = FindLanguageInfo(ratingSpan.LeftPart('-').ToString());
// Check rating system of culture
return GetRatingLevel(ratingSpan.RightPart('-').ToString(), culture?.TwoLetterISOLanguageName);
2022-10-09 13:56:23 -07:00
}
2018-09-12 10:26:21 -07:00
return null;
}
2014-03-30 18:00:47 -07:00
2019-08-16 08:31:47 -07:00
/// <inheritdoc />
2014-03-30 18:00:47 -07:00
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
2019-08-16 08:31:47 -07:00
/// <inheritdoc />
2014-03-30 18:00:47 -07:00
public string GetLocalizedString(string phrase, string culture)
{
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(culture))
2017-10-20 09:16:56 -07:00
{
culture = _configurationManager.Configuration.UICulture;
}
2019-03-13 14:32:52 -07:00
2018-09-12 10:26:21 -07:00
if (string.IsNullOrEmpty(culture))
2017-10-21 09:39:52 -07:00
{
culture = DefaultCulture;
}
2017-10-20 09:16:56 -07:00
2014-03-30 18:00:47 -07:00
var dictionary = GetLocalizationDictionary(culture);
if (dictionary.TryGetValue(phrase, out var value))
2014-03-30 18:00:47 -07:00
{
return value;
}
return phrase;
}
2019-08-16 08:31:47 -07:00
private Dictionary<string, string> GetLocalizationDictionary(string culture)
2014-03-30 18:00:47 -07:00
{
ArgumentException.ThrowIfNullOrEmpty(culture);
2017-10-21 09:39:52 -07:00
const string Prefix = "Core";
2014-03-30 18:00:47 -07:00
2019-08-16 08:31:47 -07:00
return _dictionaries.GetOrAdd(
culture,
2021-12-19 02:27:57 -07:00
static (key, localizationManager) => localizationManager.GetDictionary(Prefix, key, DefaultCulture + ".json").GetAwaiter().GetResult(),
2021-05-23 15:30:41 -07:00
this);
2014-03-30 18:00:47 -07:00
}
private async Task<Dictionary<string, string>> GetDictionary(string prefix, string culture, string baseFilename)
2014-03-30 18:00:47 -07:00
{
ArgumentException.ThrowIfNullOrEmpty(culture);
2017-10-21 09:39:52 -07:00
2014-03-30 18:00:47 -07:00
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var namespaceName = GetType().Namespace + "." + prefix;
2019-03-13 14:32:52 -07:00
await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
2014-03-30 18:00:47 -07:00
return dictionary;
}
private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
2014-03-30 18:00:47 -07:00
{
2021-08-10 05:03:15 -07:00
await using var stream = _assembly.GetManifestResourceStream(resourcePath);
// If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
2022-12-05 07:00:20 -07:00
if (stream is null)
2014-03-30 18:00:47 -07:00
{
2021-08-15 08:20:07 -07:00
_logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
return;
}
2021-08-15 08:20:07 -07:00
var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false);
2022-12-05 07:00:20 -07:00
if (dict is null)
2021-08-15 08:20:07 -07:00
{
throw new InvalidOperationException($"Resource contains invalid data: '{stream}'");
2014-03-30 18:00:47 -07:00
}
2021-08-15 08:20:07 -07:00
foreach (var key in dict.Keys)
2021-08-10 05:03:15 -07:00
{
2021-08-15 08:20:07 -07:00
dictionary[key] = dict[key];
2021-08-10 05:03:15 -07:00
}
2014-03-30 18:00:47 -07:00
}
private static string GetResourceFilename(string culture)
2014-03-30 18:00:47 -07:00
{
var parts = culture.Split('-');
if (parts.Length == 2)
{
2019-01-27 04:03:43 -07:00
culture = parts[0].ToLowerInvariant() + "-" + parts[1].ToUpperInvariant();
2014-03-30 18:00:47 -07:00
}
else
{
2019-01-27 04:03:43 -07:00
culture = culture.ToLowerInvariant();
2014-03-30 18:00:47 -07:00
}
return culture + ".json";
}
/// <inheritdoc />
public IEnumerable<LocalizationOption> GetLocalizationOptions()
{
2021-11-01 12:22:16 -07:00
yield return new LocalizationOption("Afrikaans", "af");
2021-11-19 10:00:20 -07:00
yield return new LocalizationOption("العربية", "ar");
yield return new LocalizationOption("Беларуская", "be");
yield return new LocalizationOption("Български", "bg-BG");
yield return new LocalizationOption("বাংলা (বাংলাদেশ)", "bn");
yield return new LocalizationOption("Català", "ca");
yield return new LocalizationOption("Čeština", "cs");
yield return new LocalizationOption("Cymraeg", "cy");
yield return new LocalizationOption("Dansk", "da");
yield return new LocalizationOption("Deutsch", "de");
yield return new LocalizationOption("English (United Kingdom)", "en-GB");
2021-11-19 10:00:20 -07:00
yield return new LocalizationOption("English", "en-US");
yield return new LocalizationOption("Ελληνικά", "el");
2021-11-01 12:22:16 -07:00
yield return new LocalizationOption("Esperanto", "eo");
2021-11-19 10:00:20 -07:00
yield return new LocalizationOption("Español", "es");
yield return new LocalizationOption("Español americano", "es_419");
yield return new LocalizationOption("Español (Argentina)", "es-AR");
yield return new LocalizationOption("Español (Dominicana)", "es_DO");
yield return new LocalizationOption("Español (México)", "es-MX");
yield return new LocalizationOption("Eesti", "et");
yield return new LocalizationOption("Basque", "eu");
2021-11-19 10:00:20 -07:00
yield return new LocalizationOption("فارسی", "fa");
yield return new LocalizationOption("Suomi", "fi");
yield return new LocalizationOption("Filipino", "fil");
yield return new LocalizationOption("Français", "fr");
yield return new LocalizationOption("Français (Canada)", "fr-CA");
yield return new LocalizationOption("Galego", "gl");
yield return new LocalizationOption("Schwiizerdütsch", "gsw");
yield return new LocalizationOption("עִבְרִית", "he");
yield return new LocalizationOption("हिन्दी", "hi");
yield return new LocalizationOption("Hrvatski", "hr");
yield return new LocalizationOption("Magyar", "hu");
yield return new LocalizationOption("Bahasa Indonesia", "id");
yield return new LocalizationOption("Íslenska", "is");
yield return new LocalizationOption("Italiano", "it");
yield return new LocalizationOption("日本語", "ja");
yield return new LocalizationOption("Qazaqşa", "kk");
yield return new LocalizationOption("한국어", "ko");
yield return new LocalizationOption("Lietuvių", "lt");
yield return new LocalizationOption("Latviešu", "lv");
yield return new LocalizationOption("Македонски", "mk");
yield return new LocalizationOption("മലയാളം", "ml");
yield return new LocalizationOption("मराठी", "mr");
yield return new LocalizationOption("Bahasa Melayu", "ms");
yield return new LocalizationOption("Norsk bokmål", "nb");
yield return new LocalizationOption("नेपाली", "ne");
yield return new LocalizationOption("Nederlands", "nl");
yield return new LocalizationOption("Norsk nynorsk", "nn");
yield return new LocalizationOption("ਪੰਜਾਬੀ", "pa");
yield return new LocalizationOption("Polski", "pl");
yield return new LocalizationOption("Pirate", "pr");
yield return new LocalizationOption("Português", "pt");
yield return new LocalizationOption("Português (Brasil)", "pt-BR");
yield return new LocalizationOption("Português (Portugal)", "pt-PT");
yield return new LocalizationOption("Românește", "ro");
yield return new LocalizationOption("Русский", "ru");
yield return new LocalizationOption("Slovenčina", "sk");
yield return new LocalizationOption("Slovenščina", "sl-SI");
yield return new LocalizationOption("Shqip", "sq");
yield return new LocalizationOption("Српски", "sr");
yield return new LocalizationOption("Svenska", "sv");
yield return new LocalizationOption("தமிழ்", "ta");
yield return new LocalizationOption("తెలుగు", "te");
yield return new LocalizationOption("ภาษาไทย", "th");
yield return new LocalizationOption("Türkçe", "tr");
yield return new LocalizationOption("Українська", "uk");
yield return new LocalizationOption("اُردُو", "ur_PK");
yield return new LocalizationOption("Tiếng Việt", "vi");
yield return new LocalizationOption("汉语 (简体字)", "zh-CN");
yield return new LocalizationOption("漢語 (繁體字)", "zh-TW");
2021-11-19 10:00:20 -07:00
yield return new LocalizationOption("廣東話 (香港)", "zh-HK");
}
}
}