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

433 lines
17 KiB
C#
Raw Normal View History

using System;
2013-06-11 02:34:55 +00:00
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
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-05 02:17:18 +00:00
namespace Emby.Server.Implementations.Localization
{
/// <summary>
2019-08-16 15:31:47 +00:00
/// Class LocalizationManager.
/// </summary>
public class LocalizationManager : ILocalizationManager
{
2019-08-16 15:31:47 +00:00
private const string DefaultCulture = "en-US";
2021-08-10 12:03:15 +00: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 15:31:47 +00:00
private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
private readonly IServerConfigurationManager _configurationManager;
private readonly ILogger<LocalizationManager> _logger;
2018-09-12 17:26:21 +00:00
private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
2013-06-11 02:34:55 +00:00
2019-08-16 15:31:47 +00: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 15:20:07 +00:00
private List<CultureDto> _cultures = new List<CultureDto>();
/// <summary>
2014-06-05 02:32:40 +00:00
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
2019-08-16 15:31:47 +00:00
/// <param name="logger">The logger.</param>
public LocalizationManager(
IServerConfigurationManager configurationManager,
2019-08-16 15:31:47 +00:00
ILogger<LocalizationManager> logger)
{
_configurationManager = configurationManager;
2019-08-16 15:31:47 +00:00
_logger = logger;
2013-06-18 20:54:32 +00: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 12:03:15 +00:00
if (!resource.StartsWith(RatingsPath, StringComparison.Ordinal))
{
continue;
}
2021-08-10 12:03:15 +00:00
string countryCode = resource.Substring(RatingsPath.Length, 2);
var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
2021-08-15 15:20:07 +00:00
await using var stream = _assembly.GetManifestResourceStream(resource);
using var reader = new StreamReader(stream!); // shouldn't be null here, we just got the resource path from Assembly.GetManifestResourceNames()
2021-08-10 12:03:15 +00:00
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
2021-08-10 12:03:15 +00:00
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
string[] parts = line.Split(',');
if (parts.Length == 2
&& int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
2021-08-10 12:03:15 +00:00
var name = parts[0];
dict.Add(name, new ParentalRating(name, value));
}
#if DEBUG
2021-08-10 12:03:15 +00:00
else
{
_logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
}
2021-08-10 12:03:15 +00:00
#endif
}
_allParentalRatings[countryCode] = dict;
}
await LoadCultures().ConfigureAwait(false);
}
/// <summary>
/// Gets the cultures.
/// </summary>
2019-08-16 15:31:47 +00: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 15:20:07 +00:00
await using var stream = _assembly.GetManifestResourceStream(CulturesPath)
?? throw new InvalidOperationException($"Invalid resource path: '{CulturesPath}'");
2021-08-10 12:03:15 +00:00
using var reader = new StreamReader(stream);
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
2021-08-10 12:03:15 +00:00
if (string.IsNullOrWhiteSpace(line))
{
2021-08-10 12:03:15 +00:00
continue;
}
var parts = line.Split('|');
if (parts.Length == 5)
{
string name = parts[3];
if (string.IsNullOrWhiteSpace(name))
{
continue;
}
2021-08-10 12:03:15 +00:00
string twoCharName = parts[2];
if (string.IsNullOrWhiteSpace(twoCharName))
{
continue;
}
2021-08-10 12:03:15 +00:00
string[] threeletterNames;
if (string.IsNullOrWhiteSpace(parts[1]))
{
threeletterNames = new[] { parts[0] };
}
else
{
2021-08-10 12:03:15 +00:00
threeletterNames = new[] { parts[0], parts[1] };
}
2021-08-10 12:03:15 +00:00
list.Add(new CultureDto
{
DisplayName = name,
Name = name,
ThreeLetterISOLanguageNames = threeletterNames,
TwoLetterISOLanguageName = twoCharName
});
}
}
_cultures = list;
}
2019-08-16 15:31:47 +00:00
/// <inheritdoc />
2021-08-15 15:20:07 +00:00
public CultureDto? FindLanguageInfo(string language)
2021-05-23 22:30:41 +00: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 17:26:21 +00:00
2019-08-16 15:31:47 +00:00
/// <inheritdoc />
public IEnumerable<CountryInfo> GetCountries()
{
2021-08-15 15:20:07 +00: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 15:31:47 +00:00
/// <inheritdoc />
public IEnumerable<ParentalRating> GetParentalRatings()
=> GetParentalRatingsDictionary().Values;
2013-06-11 02:34:55 +00:00
/// <summary>
/// Gets the parental ratings dictionary.
/// </summary>
/// <returns><see cref="Dictionary{String, ParentalRating}" />.</returns>
private Dictionary<string, ParentalRating> GetParentalRatingsDictionary()
{
var countryCode = _configurationManager.Configuration.MetadataCountryCode;
if (string.IsNullOrEmpty(countryCode))
{
countryCode = "us";
}
2021-08-15 15:20:07 +00:00
return GetRatings(countryCode)
?? GetRatings("us")
?? throw new InvalidOperationException($"Invalid resource path: '{CountriesPath}'");
}
/// <summary>
/// Gets the ratings.
/// </summary>
/// <param name="countryCode">The country code.</param>
/// <returns>The ratings.</returns>
2021-08-15 15:20:07 +00:00
private Dictionary<string, ParentalRating>? GetRatings(string countryCode)
{
_allParentalRatings.TryGetValue(countryCode, out var value);
return value;
}
2019-03-13 21:32:52 +00:00
/// <inheritdoc />
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
{
throw new ArgumentNullException(nameof(rating));
}
2021-05-23 22:30:41 +00:00
if (_unratedValues.Contains(rating.AsSpan(), StringComparison.OrdinalIgnoreCase))
2015-11-06 15:02:22 +00:00
{
return null;
}
2015-05-11 16:32:15 +00:00
// Fairly common for some users to have "Rated R" in their rating field
rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
2013-06-11 02:34:55 +00:00
var ratingsDictionary = GetParentalRatingsDictionary();
2021-08-15 15:20:07 +00:00
if (ratingsDictionary.TryGetValue(rating, out ParentalRating? value))
2013-06-11 02:34:55 +00:00
{
2018-09-12 17:26:21 +00:00
return value.Value;
}
// If we don't find anything check all ratings systems
foreach (var dictionary in _allParentalRatings.Values)
{
if (dictionary.TryGetValue(rating, out value))
2013-06-18 20:54:32 +00:00
{
2018-09-12 17:26:21 +00:00
return value.Value;
}
}
// Try splitting by : to handle "Germany: FSK 18"
var index = rating.IndexOf(':', StringComparison.Ordinal);
2018-09-12 17:26:21 +00:00
if (index != -1)
{
2021-05-23 22:30:41 +00:00
var trimmedRating = rating.AsSpan(index).TrimStart(':').Trim();
2018-09-12 17:26:21 +00:00
2021-05-23 22:30:41 +00:00
if (!trimmedRating.IsEmpty)
2018-09-12 17:26:21 +00:00
{
2021-05-23 22:30:41 +00:00
return GetRatingLevel(trimmedRating.ToString());
2013-06-18 20:54:32 +00:00
}
2013-06-11 02:34:55 +00:00
}
2018-09-12 17:26:21 +00:00
// TODO: Further improve by normalizing out all spaces and dashes
return null;
}
2014-03-31 01:00:47 +00:00
2019-08-16 15:31:47 +00:00
/// <inheritdoc />
2014-03-31 01:00:47 +00:00
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
2019-08-16 15:31:47 +00:00
/// <inheritdoc />
2014-03-31 01:00:47 +00:00
public string GetLocalizedString(string phrase, string culture)
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(culture))
2017-10-20 16:16:56 +00:00
{
culture = _configurationManager.Configuration.UICulture;
}
2019-03-13 21:32:52 +00:00
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(culture))
2017-10-21 16:39:52 +00:00
{
culture = DefaultCulture;
}
2017-10-20 16:16:56 +00:00
2014-03-31 01:00:47 +00:00
var dictionary = GetLocalizationDictionary(culture);
if (dictionary.TryGetValue(phrase, out var value))
2014-03-31 01:00:47 +00:00
{
return value;
}
return phrase;
}
2019-08-16 15:31:47 +00:00
private Dictionary<string, string> GetLocalizationDictionary(string culture)
2014-03-31 01:00:47 +00:00
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(culture))
2017-10-21 16:39:52 +00:00
{
throw new ArgumentNullException(nameof(culture));
2017-10-21 16:39:52 +00:00
}
const string Prefix = "Core";
2014-03-31 01:00:47 +00:00
2019-08-16 15:31:47 +00:00
return _dictionaries.GetOrAdd(
culture,
2021-05-23 22:30:41 +00:00
(key, localizationManager) => localizationManager.GetDictionary(Prefix, key, DefaultCulture + ".json").GetAwaiter().GetResult(),
this);
2014-03-31 01:00:47 +00:00
}
private async Task<Dictionary<string, string>> GetDictionary(string prefix, string culture, string baseFilename)
2014-03-31 01:00:47 +00:00
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(culture))
2017-10-21 16:39:52 +00:00
{
throw new ArgumentNullException(nameof(culture));
2017-10-21 16:39:52 +00:00
}
2014-03-31 01:00:47 +00:00
var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var namespaceName = GetType().Namespace + "." + prefix;
2019-03-13 21:32:52 +00:00
await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
2014-03-31 01:00:47 +00:00
return dictionary;
}
private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
2014-03-31 01:00:47 +00:00
{
2021-08-10 12:03:15 +00: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
2021-08-15 15:20:07 +00:00
if (stream == null)
2014-03-31 01:00:47 +00:00
{
2021-08-15 15:20:07 +00:00
_logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
return;
}
2021-08-15 15:20:07 +00:00
var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false);
if (dict == null)
{
throw new InvalidOperationException($"Resource contains invalid data: '{stream}'");
2014-03-31 01:00:47 +00:00
}
2021-08-15 15:20:07 +00:00
foreach (var key in dict.Keys)
2021-08-10 12:03:15 +00:00
{
2021-08-15 15:20:07 +00:00
dictionary[key] = dict[key];
2021-08-10 12:03:15 +00:00
}
2014-03-31 01:00:47 +00:00
}
private static string GetResourceFilename(string culture)
2014-03-31 01:00:47 +00:00
{
var parts = culture.Split('-');
if (parts.Length == 2)
{
2019-01-27 11:03:43 +00:00
culture = parts[0].ToLowerInvariant() + "-" + parts[1].ToUpperInvariant();
2014-03-31 01:00:47 +00:00
}
else
{
2019-01-27 11:03:43 +00:00
culture = culture.ToLowerInvariant();
2014-03-31 01:00:47 +00:00
}
return culture + ".json";
}
/// <inheritdoc />
public IEnumerable<LocalizationOption> GetLocalizationOptions()
{
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Afrikaans", "af");
yield return new LocalizationOption("Arabic", "ar");
yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG");
yield return new LocalizationOption("Catalan", "ca");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Chinese (Hong Kong)", "zh-HK");
yield return new LocalizationOption("Chinese Simplified", "zh-CN");
yield return new LocalizationOption("Chinese Traditional", "zh-TW");
yield return new LocalizationOption("Croatian", "hr");
yield return new LocalizationOption("Czech", "cs");
yield return new LocalizationOption("Danish", "da");
yield return new LocalizationOption("Dutch", "nl");
yield return new LocalizationOption("English (United Kingdom)", "en-GB");
yield return new LocalizationOption("English (United States)", "en-US");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Esperanto", "eo");
yield return new LocalizationOption("Estonian", "et");
yield return new LocalizationOption("Finnish", "fi");
yield return new LocalizationOption("French", "fr");
yield return new LocalizationOption("French (Canada)", "fr-CA");
yield return new LocalizationOption("German", "de");
yield return new LocalizationOption("Greek", "el");
yield return new LocalizationOption("Hebrew", "he");
yield return new LocalizationOption("Hungarian", "hu");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Icelandic", "is");
yield return new LocalizationOption("Indonesian", "id");
yield return new LocalizationOption("Italian", "it");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Japanese", "ja");
yield return new LocalizationOption("Kazakh", "kk");
yield return new LocalizationOption("Korean", "ko");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Latvian", "lv");
yield return new LocalizationOption("Lithuanian", "lt-LT");
yield return new LocalizationOption("Malay", "ms");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Malayalam", "ml");
yield return new LocalizationOption("Norwegian Bokmål", "nb");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Norwegian Nynorsk", "nn");
yield return new LocalizationOption("Persian", "fa");
yield return new LocalizationOption("Polish", "pl");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Portuguese", "pt");
yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR");
yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Romanian", "ro");
yield return new LocalizationOption("Russian", "ru");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Serbian", "sr");
yield return new LocalizationOption("Slovak", "sk");
yield return new LocalizationOption("Slovenian (Slovenia)", "sl-SI");
yield return new LocalizationOption("Spanish", "es");
yield return new LocalizationOption("Spanish (Argentina)", "es-AR");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Spanish (Latin America)", "es-419");
yield return new LocalizationOption("Spanish (Mexico)", "es-MX");
yield return new LocalizationOption("Swedish", "sv");
yield return new LocalizationOption("Swiss German", "gsw");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Tamil", "ta");
yield return new LocalizationOption("Telugu", "te");
yield return new LocalizationOption("Turkish", "tr");
yield return new LocalizationOption("Tiếng Việt", "vi");
2021-11-01 19:22:16 +00:00
yield return new LocalizationOption("Ukrainian", "uk");
}
}
}