Refactor LocalizationManager and remove dead method

pull/6025/head
David Ullmer 4 years ago
parent 88bfd1bcf4
commit db2b53a4b5

@ -25,18 +25,18 @@ namespace Emby.Server.Implementations.Localization
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;
private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
private readonly IServerConfigurationManager _configurationManager;
private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
private List<CultureDto> _cultures;
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
private readonly ILogger<LocalizationManager> _logger;
private List<CultureDto> _cultures;
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationManager" /> class.
@ -51,6 +51,153 @@ namespace Emby.Server.Implementations.Localization
_logger = logger;
}
/// <summary>
/// Gets the cultures.
/// </summary>
/// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
public IEnumerable<CultureDto> GetCultures()
=> _cultures;
/// <inheritdoc />
public CultureDto FindLanguageInfo(string language)
=> GetCultures()
.FirstOrDefault(i =>
string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase)
|| string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase)
|| i.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)
|| string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
/// <inheritdoc />
public IEnumerable<CountryInfo> GetCountries()
{
using StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json"));
return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions);
}
/// <inheritdoc />
public IEnumerable<ParentalRating> GetParentalRatings()
=> GetParentalRatingsDictionary().Values;
/// <inheritdoc />
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
{
throw new ArgumentNullException(nameof(rating));
}
if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase))
{
return null;
}
// Fairly common for some users to have "Rated R" in their rating field
rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
var ratingsDictionary = GetParentalRatingsDictionary();
if (ratingsDictionary.TryGetValue(rating, out ParentalRating value))
{
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))
{
return value.Value;
}
}
// Try splitting by : to handle "Germany: FSK 18"
var index = rating.IndexOf(':', StringComparison.Ordinal);
if (index != -1)
{
rating = rating.Substring(index + 1).Trim();
if (!string.IsNullOrWhiteSpace(rating))
{
return GetRatingLevel(rating);
}
}
// TODO: Further improve by normalizing out all spaces and dashes
return null;
}
/// <inheritdoc />
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
/// <inheritdoc />
public string GetLocalizedString(string phrase, string culture)
{
if (string.IsNullOrEmpty(culture))
{
culture = _configurationManager.Configuration.UICulture;
}
if (string.IsNullOrEmpty(culture))
{
culture = DefaultCulture;
}
var dictionary = GetLocalizationDictionary(culture);
if (dictionary.TryGetValue(phrase, out var value))
{
return value;
}
return phrase;
}
/// <inheritdoc />
public IEnumerable<LocalizationOption> GetLocalizationOptions()
{
yield return new LocalizationOption("Arabic", "ar");
yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG");
yield return new LocalizationOption("Catalan", "ca");
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");
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");
yield return new LocalizationOption("Italian", "it");
yield return new LocalizationOption("Kazakh", "kk");
yield return new LocalizationOption("Korean", "ko");
yield return new LocalizationOption("Lithuanian", "lt-LT");
yield return new LocalizationOption("Malay", "ms");
yield return new LocalizationOption("Norwegian Bokmål", "nb");
yield return new LocalizationOption("Persian", "fa");
yield return new LocalizationOption("Polish", "pl");
yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR");
yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT");
yield return new LocalizationOption("Russian", "ru");
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");
yield return new LocalizationOption("Spanish (Mexico)", "es-MX");
yield return new LocalizationOption("Swedish", "sv");
yield return new LocalizationOption("Swiss German", "gsw");
yield return new LocalizationOption("Turkish", "tr");
yield return new LocalizationOption("Tiếng Việt", "vi");
}
/// <summary>
/// Loads all resources into memory.
/// </summary>
@ -70,9 +217,8 @@ namespace Emby.Server.Implementations.Localization
string countryCode = resource.Substring(RatingsResource.Length, 2);
var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
using (var str = _assembly.GetManifestResourceStream(resource))
using (var reader = new StreamReader(str))
{
await using var str = _assembly.GetManifestResourceStream(resource);
using var reader = new StreamReader(str);
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
if (string.IsNullOrWhiteSpace(line))
@ -94,7 +240,6 @@ namespace Emby.Server.Implementations.Localization
}
#endif
}
}
_allParentalRatings[countryCode] = dict;
}
@ -102,22 +247,14 @@ namespace Emby.Server.Implementations.Localization
await LoadCultures().ConfigureAwait(false);
}
/// <summary>
/// Gets the cultures.
/// </summary>
/// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
public IEnumerable<CultureDto> GetCultures()
=> _cultures;
private async Task LoadCultures()
{
List<CultureDto> list = new List<CultureDto>();
const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt";
using (var stream = _assembly.GetManifestResourceStream(ResourcePath))
using (var reader = new StreamReader(stream))
{
await using var stream = _assembly.GetManifestResourceStream(ResourcePath);
using var reader = new StreamReader(stream);
await foreach (var line in reader.ReadAllLinesAsync().ConfigureAwait(false))
{
if (string.IsNullOrWhiteSpace(line))
@ -160,32 +297,10 @@ namespace Emby.Server.Implementations.Localization
});
}
}
}
_cultures = list;
}
/// <inheritdoc />
public CultureDto FindLanguageInfo(string language)
=> GetCultures()
.FirstOrDefault(i =>
string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase)
|| string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase)
|| i.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)
|| string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
/// <inheritdoc />
public IEnumerable<CountryInfo> GetCountries()
{
using StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json"));
return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions);
}
/// <inheritdoc />
public IEnumerable<ParentalRating> GetParentalRatings()
=> GetParentalRatingsDictionary().Values;
/// <summary>
/// Gets the parental ratings dictionary.
/// </summary>
@ -214,97 +329,6 @@ namespace Emby.Server.Implementations.Localization
return value;
}
/// <inheritdoc />
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
{
throw new ArgumentNullException(nameof(rating));
}
if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase))
{
return null;
}
// Fairly common for some users to have "Rated R" in their rating field
rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
var ratingsDictionary = GetParentalRatingsDictionary();
if (ratingsDictionary.TryGetValue(rating, out ParentalRating value))
{
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))
{
return value.Value;
}
}
// Try splitting by : to handle "Germany: FSK 18"
var index = rating.IndexOf(':', StringComparison.Ordinal);
if (index != -1)
{
rating = rating.Substring(index).TrimStart(':').Trim();
if (!string.IsNullOrWhiteSpace(rating))
{
return GetRatingLevel(rating);
}
}
// TODO: Further improve by normalizing out all spaces and dashes
return null;
}
/// <inheritdoc />
public bool HasUnicodeCategory(string value, UnicodeCategory category)
{
foreach (var chr in value)
{
if (char.GetUnicodeCategory(chr) == category)
{
return true;
}
}
return false;
}
/// <inheritdoc />
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
/// <inheritdoc />
public string GetLocalizedString(string phrase, string culture)
{
if (string.IsNullOrEmpty(culture))
{
culture = _configurationManager.Configuration.UICulture;
}
if (string.IsNullOrEmpty(culture))
{
culture = DefaultCulture;
}
var dictionary = GetLocalizationDictionary(culture);
if (dictionary.TryGetValue(phrase, out var value))
{
return value;
}
return phrase;
}
private Dictionary<string, string> GetLocalizationDictionary(string culture)
{
if (string.IsNullOrEmpty(culture))
@ -316,7 +340,7 @@ namespace Emby.Server.Implementations.Localization
return _dictionaries.GetOrAdd(
culture,
f => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult());
_ => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult());
}
private async Task<Dictionary<string, string>> GetDictionary(string prefix, string culture, string baseFilename)
@ -338,8 +362,7 @@ namespace Emby.Server.Implementations.Localization
private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
{
using (var stream = _assembly.GetManifestResourceStream(resourcePath))
{
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
if (stream != null)
{
@ -355,7 +378,6 @@ namespace Emby.Server.Implementations.Localization
_logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
}
}
}
private static string GetResourceFilename(string culture)
{
@ -372,47 +394,5 @@ namespace Emby.Server.Implementations.Localization
return culture + ".json";
}
/// <inheritdoc />
public IEnumerable<LocalizationOption> GetLocalizationOptions()
{
yield return new LocalizationOption("Arabic", "ar");
yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG");
yield return new LocalizationOption("Catalan", "ca");
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");
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");
yield return new LocalizationOption("Italian", "it");
yield return new LocalizationOption("Kazakh", "kk");
yield return new LocalizationOption("Korean", "ko");
yield return new LocalizationOption("Lithuanian", "lt-LT");
yield return new LocalizationOption("Malay", "ms");
yield return new LocalizationOption("Norwegian Bokmål", "nb");
yield return new LocalizationOption("Persian", "fa");
yield return new LocalizationOption("Polish", "pl");
yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR");
yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT");
yield return new LocalizationOption("Russian", "ru");
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");
yield return new LocalizationOption("Spanish (Mexico)", "es-MX");
yield return new LocalizationOption("Swedish", "sv");
yield return new LocalizationOption("Swiss German", "gsw");
yield return new LocalizationOption("Turkish", "tr");
yield return new LocalizationOption("Tiếng Việt", "vi");
}
}
}

@ -56,14 +56,6 @@ namespace MediaBrowser.Model.Globalization
/// <returns><see cref="IEnumerable{LocalizatonOption}" />.</returns>
IEnumerable<LocalizationOption> GetLocalizationOptions();
/// <summary>
/// Checks if the string contains a character with the specified unicode category.
/// </summary>
/// <param name="value">The string.</param>
/// <param name="category">The unicode category.</param>
/// <returns>Wether or not the string contains a character with the specified unicode category.</returns>
bool HasUnicodeCategory(string value, UnicodeCategory category);
/// <summary>
/// Returns the correct <see cref="CultureInfo" /> for the given language.
/// </summary>

Loading…
Cancel
Save