LocalizationManager.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text.Json;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Json;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.Globalization;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.Localization
  16. {
  17. /// <summary>
  18. /// Class LocalizationManager.
  19. /// </summary>
  20. public class LocalizationManager : ILocalizationManager
  21. {
  22. private const string DefaultCulture = "en-US";
  23. private static readonly Assembly _assembly = typeof(LocalizationManager).Assembly;
  24. private static readonly string[] _unratedValues = { "n/a", "unrated", "not rated" };
  25. private readonly IServerConfigurationManager _configurationManager;
  26. private readonly ILogger<LocalizationManager> _logger;
  27. private readonly Dictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
  28. new Dictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
  29. private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
  30. new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
  31. private List<CultureDto> _cultures;
  32. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="LocalizationManager" /> class.
  35. /// </summary>
  36. /// <param name="configurationManager">The configuration manager.</param>
  37. /// <param name="logger">The logger.</param>
  38. public LocalizationManager(
  39. IServerConfigurationManager configurationManager,
  40. ILogger<LocalizationManager> logger)
  41. {
  42. _configurationManager = configurationManager;
  43. _logger = logger;
  44. }
  45. /// <summary>
  46. /// Loads all resources into memory.
  47. /// </summary>
  48. /// <returns><see cref="Task" />.</returns>
  49. public async Task LoadAll()
  50. {
  51. const string RatingsResource = "Emby.Server.Implementations.Localization.Ratings.";
  52. // Extract from the assembly
  53. foreach (var resource in _assembly.GetManifestResourceNames())
  54. {
  55. if (!resource.StartsWith(RatingsResource, StringComparison.Ordinal))
  56. {
  57. continue;
  58. }
  59. string countryCode = resource.Substring(RatingsResource.Length, 2);
  60. var dict = new Dictionary<string, ParentalRating>(StringComparer.OrdinalIgnoreCase);
  61. using (var str = _assembly.GetManifestResourceStream(resource))
  62. using (var reader = new StreamReader(str))
  63. {
  64. string line;
  65. while ((line = await reader.ReadLineAsync().ConfigureAwait(false)) != null)
  66. {
  67. if (string.IsNullOrWhiteSpace(line))
  68. {
  69. continue;
  70. }
  71. string[] parts = line.Split(',');
  72. if (parts.Length == 2
  73. && int.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
  74. {
  75. var name = parts[0];
  76. dict.Add(name, new ParentalRating(name, value));
  77. }
  78. #if DEBUG
  79. else
  80. {
  81. _logger.LogWarning("Malformed line in ratings file for country {CountryCode}", countryCode);
  82. }
  83. #endif
  84. }
  85. }
  86. _allParentalRatings[countryCode] = dict;
  87. }
  88. await LoadCultures().ConfigureAwait(false);
  89. }
  90. /// <summary>
  91. /// Gets the cultures.
  92. /// </summary>
  93. /// <returns><see cref="IEnumerable{CultureDto}" />.</returns>
  94. public IEnumerable<CultureDto> GetCultures()
  95. => _cultures;
  96. private async Task LoadCultures()
  97. {
  98. List<CultureDto> list = new List<CultureDto>();
  99. const string ResourcePath = "Emby.Server.Implementations.Localization.iso6392.txt";
  100. using (var stream = _assembly.GetManifestResourceStream(ResourcePath))
  101. using (var reader = new StreamReader(stream))
  102. {
  103. while (!reader.EndOfStream)
  104. {
  105. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  106. if (string.IsNullOrWhiteSpace(line))
  107. {
  108. continue;
  109. }
  110. var parts = line.Split('|');
  111. if (parts.Length == 5)
  112. {
  113. string name = parts[3];
  114. if (string.IsNullOrWhiteSpace(name))
  115. {
  116. continue;
  117. }
  118. string twoCharName = parts[2];
  119. if (string.IsNullOrWhiteSpace(twoCharName))
  120. {
  121. continue;
  122. }
  123. string[] threeletterNames;
  124. if (string.IsNullOrWhiteSpace(parts[1]))
  125. {
  126. threeletterNames = new[] { parts[0] };
  127. }
  128. else
  129. {
  130. threeletterNames = new[] { parts[0], parts[1] };
  131. }
  132. list.Add(new CultureDto
  133. {
  134. DisplayName = name,
  135. Name = name,
  136. ThreeLetterISOLanguageNames = threeletterNames,
  137. TwoLetterISOLanguageName = twoCharName
  138. });
  139. }
  140. }
  141. }
  142. _cultures = list;
  143. }
  144. /// <inheritdoc />
  145. public CultureDto FindLanguageInfo(string language)
  146. => GetCultures()
  147. .FirstOrDefault(i =>
  148. string.Equals(i.DisplayName, language, StringComparison.OrdinalIgnoreCase)
  149. || string.Equals(i.Name, language, StringComparison.OrdinalIgnoreCase)
  150. || i.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)
  151. || string.Equals(i.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase));
  152. /// <inheritdoc />
  153. public IEnumerable<CountryInfo> GetCountries()
  154. {
  155. StreamReader reader = new StreamReader(_assembly.GetManifestResourceStream("Emby.Server.Implementations.Localization.countries.json"));
  156. return JsonSerializer.Deserialize<IEnumerable<CountryInfo>>(reader.ReadToEnd(), _jsonOptions);
  157. }
  158. /// <inheritdoc />
  159. public IEnumerable<ParentalRating> GetParentalRatings()
  160. => GetParentalRatingsDictionary().Values;
  161. /// <summary>
  162. /// Gets the parental ratings dictionary.
  163. /// </summary>
  164. /// <returns><see cref="Dictionary{String, ParentalRating}" />.</returns>
  165. private Dictionary<string, ParentalRating> GetParentalRatingsDictionary()
  166. {
  167. var countryCode = _configurationManager.Configuration.MetadataCountryCode;
  168. if (string.IsNullOrEmpty(countryCode))
  169. {
  170. countryCode = "us";
  171. }
  172. return GetRatings(countryCode) ?? GetRatings("us");
  173. }
  174. /// <summary>
  175. /// Gets the ratings.
  176. /// </summary>
  177. /// <param name="countryCode">The country code.</param>
  178. /// <returns>The ratings.</returns>
  179. private Dictionary<string, ParentalRating> GetRatings(string countryCode)
  180. {
  181. _allParentalRatings.TryGetValue(countryCode, out var value);
  182. return value;
  183. }
  184. /// <inheritdoc />
  185. public int? GetRatingLevel(string rating)
  186. {
  187. if (string.IsNullOrEmpty(rating))
  188. {
  189. throw new ArgumentNullException(nameof(rating));
  190. }
  191. if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase))
  192. {
  193. return null;
  194. }
  195. // Fairly common for some users to have "Rated R" in their rating field
  196. rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
  197. var ratingsDictionary = GetParentalRatingsDictionary();
  198. if (ratingsDictionary.TryGetValue(rating, out ParentalRating value))
  199. {
  200. return value.Value;
  201. }
  202. // If we don't find anything check all ratings systems
  203. foreach (var dictionary in _allParentalRatings.Values)
  204. {
  205. if (dictionary.TryGetValue(rating, out value))
  206. {
  207. return value.Value;
  208. }
  209. }
  210. // Try splitting by : to handle "Germany: FSK 18"
  211. var index = rating.IndexOf(':', StringComparison.Ordinal);
  212. if (index != -1)
  213. {
  214. rating = rating.Substring(index).TrimStart(':').Trim();
  215. if (!string.IsNullOrWhiteSpace(rating))
  216. {
  217. return GetRatingLevel(rating);
  218. }
  219. }
  220. // TODO: Further improve by normalizing out all spaces and dashes
  221. return null;
  222. }
  223. /// <inheritdoc />
  224. public bool HasUnicodeCategory(string value, UnicodeCategory category)
  225. {
  226. foreach (var chr in value)
  227. {
  228. if (char.GetUnicodeCategory(chr) == category)
  229. {
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. /// <inheritdoc />
  236. public string GetLocalizedString(string phrase)
  237. {
  238. return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
  239. }
  240. /// <inheritdoc />
  241. public string GetLocalizedString(string phrase, string culture)
  242. {
  243. if (string.IsNullOrEmpty(culture))
  244. {
  245. culture = _configurationManager.Configuration.UICulture;
  246. }
  247. if (string.IsNullOrEmpty(culture))
  248. {
  249. culture = DefaultCulture;
  250. }
  251. var dictionary = GetLocalizationDictionary(culture);
  252. if (dictionary.TryGetValue(phrase, out var value))
  253. {
  254. return value;
  255. }
  256. return phrase;
  257. }
  258. private Dictionary<string, string> GetLocalizationDictionary(string culture)
  259. {
  260. if (string.IsNullOrEmpty(culture))
  261. {
  262. throw new ArgumentNullException(nameof(culture));
  263. }
  264. const string Prefix = "Core";
  265. var key = Prefix + culture;
  266. return _dictionaries.GetOrAdd(
  267. key,
  268. f => GetDictionary(Prefix, culture, DefaultCulture + ".json").GetAwaiter().GetResult());
  269. }
  270. private async Task<Dictionary<string, string>> GetDictionary(string prefix, string culture, string baseFilename)
  271. {
  272. if (string.IsNullOrEmpty(culture))
  273. {
  274. throw new ArgumentNullException(nameof(culture));
  275. }
  276. var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  277. var namespaceName = GetType().Namespace + "." + prefix;
  278. await CopyInto(dictionary, namespaceName + "." + baseFilename).ConfigureAwait(false);
  279. await CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture)).ConfigureAwait(false);
  280. return dictionary;
  281. }
  282. private async Task CopyInto(IDictionary<string, string> dictionary, string resourcePath)
  283. {
  284. using (var stream = _assembly.GetManifestResourceStream(resourcePath))
  285. {
  286. // If a Culture doesn't have a translation the stream will be null and it defaults to en-us further up the chain
  287. if (stream != null)
  288. {
  289. var dict = await JsonSerializer.DeserializeAsync<Dictionary<string, string>>(stream, _jsonOptions).ConfigureAwait(false);
  290. foreach (var key in dict.Keys)
  291. {
  292. dictionary[key] = dict[key];
  293. }
  294. }
  295. else
  296. {
  297. _logger.LogError("Missing translation/culture resource: {ResourcePath}", resourcePath);
  298. }
  299. }
  300. }
  301. private static string GetResourceFilename(string culture)
  302. {
  303. var parts = culture.Split('-');
  304. if (parts.Length == 2)
  305. {
  306. culture = parts[0].ToLowerInvariant() + "-" + parts[1].ToUpperInvariant();
  307. }
  308. else
  309. {
  310. culture = culture.ToLowerInvariant();
  311. }
  312. return culture + ".json";
  313. }
  314. /// <inheritdoc />
  315. public IEnumerable<LocalizationOption> GetLocalizationOptions()
  316. {
  317. yield return new LocalizationOption("Arabic", "ar");
  318. yield return new LocalizationOption("Bulgarian (Bulgaria)", "bg-BG");
  319. yield return new LocalizationOption("Catalan", "ca");
  320. yield return new LocalizationOption("Chinese Simplified", "zh-CN");
  321. yield return new LocalizationOption("Chinese Traditional", "zh-TW");
  322. yield return new LocalizationOption("Croatian", "hr");
  323. yield return new LocalizationOption("Czech", "cs");
  324. yield return new LocalizationOption("Danish", "da");
  325. yield return new LocalizationOption("Dutch", "nl");
  326. yield return new LocalizationOption("English (United Kingdom)", "en-GB");
  327. yield return new LocalizationOption("English (United States)", "en-US");
  328. yield return new LocalizationOption("French", "fr");
  329. yield return new LocalizationOption("French (Canada)", "fr-CA");
  330. yield return new LocalizationOption("German", "de");
  331. yield return new LocalizationOption("Greek", "el");
  332. yield return new LocalizationOption("Hebrew", "he");
  333. yield return new LocalizationOption("Hungarian", "hu");
  334. yield return new LocalizationOption("Italian", "it");
  335. yield return new LocalizationOption("Kazakh", "kk");
  336. yield return new LocalizationOption("Korean", "ko");
  337. yield return new LocalizationOption("Lithuanian", "lt-LT");
  338. yield return new LocalizationOption("Malay", "ms");
  339. yield return new LocalizationOption("Norwegian Bokmål", "nb");
  340. yield return new LocalizationOption("Persian", "fa");
  341. yield return new LocalizationOption("Polish", "pl");
  342. yield return new LocalizationOption("Portuguese (Brazil)", "pt-BR");
  343. yield return new LocalizationOption("Portuguese (Portugal)", "pt-PT");
  344. yield return new LocalizationOption("Russian", "ru");
  345. yield return new LocalizationOption("Slovak", "sk");
  346. yield return new LocalizationOption("Slovenian (Slovenia)", "sl-SI");
  347. yield return new LocalizationOption("Spanish", "es");
  348. yield return new LocalizationOption("Spanish (Argentina)", "es-AR");
  349. yield return new LocalizationOption("Spanish (Mexico)", "es-MX");
  350. yield return new LocalizationOption("Swedish", "sv");
  351. yield return new LocalizationOption("Swiss German", "gsw");
  352. yield return new LocalizationOption("Turkish", "tr");
  353. yield return new LocalizationOption("Tiếng Việt", "vi");
  354. }
  355. }
  356. }