LocalizationManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. using MediaBrowser.Model.Extensions;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Globalization;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Text;
  14. using MediaBrowser.Common.IO;
  15. using MediaBrowser.Controller.IO;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Logging;
  18. namespace MediaBrowser.Server.Implementations.Localization
  19. {
  20. /// <summary>
  21. /// Class LocalizationManager
  22. /// </summary>
  23. public class LocalizationManager : ILocalizationManager
  24. {
  25. /// <summary>
  26. /// The _configuration manager
  27. /// </summary>
  28. private readonly IServerConfigurationManager _configurationManager;
  29. /// <summary>
  30. /// The us culture
  31. /// </summary>
  32. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  33. private readonly ConcurrentDictionary<string, Dictionary<string, ParentalRating>> _allParentalRatings =
  34. new ConcurrentDictionary<string, Dictionary<string, ParentalRating>>(StringComparer.OrdinalIgnoreCase);
  35. private readonly IFileSystem _fileSystem;
  36. private readonly IJsonSerializer _jsonSerializer;
  37. private readonly ILogger _logger;
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="LocalizationManager" /> class.
  40. /// </summary>
  41. /// <param name="configurationManager">The configuration manager.</param>
  42. /// <param name="fileSystem">The file system.</param>
  43. /// <param name="jsonSerializer">The json serializer.</param>
  44. public LocalizationManager(IServerConfigurationManager configurationManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer, ILogger logger)
  45. {
  46. _configurationManager = configurationManager;
  47. _fileSystem = fileSystem;
  48. _jsonSerializer = jsonSerializer;
  49. _logger = logger;
  50. ExtractAll();
  51. }
  52. private void ExtractAll()
  53. {
  54. var type = GetType();
  55. var resourcePath = type.Namespace + ".Ratings.";
  56. var localizationPath = LocalizationPath;
  57. _fileSystem.CreateDirectory(localizationPath);
  58. var existingFiles = Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly)
  59. .Select(Path.GetFileName)
  60. .ToList();
  61. // Extract from the assembly
  62. foreach (var resource in type.Assembly
  63. .GetManifestResourceNames()
  64. .Where(i => i.StartsWith(resourcePath)))
  65. {
  66. var filename = "ratings-" + resource.Substring(resourcePath.Length);
  67. if (!existingFiles.Contains(filename))
  68. {
  69. using (var stream = type.Assembly.GetManifestResourceStream(resource))
  70. {
  71. var target = Path.Combine(localizationPath, filename);
  72. _logger.Info("Extracting ratings to {0}", target);
  73. using (var fs = _fileSystem.GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  74. {
  75. stream.CopyTo(fs);
  76. }
  77. }
  78. }
  79. }
  80. foreach (var file in Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly))
  81. {
  82. LoadRatings(file);
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the localization path.
  87. /// </summary>
  88. /// <value>The localization path.</value>
  89. public string LocalizationPath
  90. {
  91. get
  92. {
  93. return Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
  94. }
  95. }
  96. public string RemoveDiacritics(string text)
  97. {
  98. return String.Concat(
  99. text.Normalize(NormalizationForm.FormD)
  100. .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
  101. UnicodeCategory.NonSpacingMark)
  102. ).Normalize(NormalizationForm.FormC);
  103. }
  104. /// <summary>
  105. /// Gets the cultures.
  106. /// </summary>
  107. /// <returns>IEnumerable{CultureDto}.</returns>
  108. public IEnumerable<CultureDto> GetCultures()
  109. {
  110. var type = GetType();
  111. var path = type.Namespace + ".iso6392.txt";
  112. var list = new List<CultureDto>();
  113. using (var stream = type.Assembly.GetManifestResourceStream(path))
  114. {
  115. using (var reader = new StreamReader(stream))
  116. {
  117. while (!reader.EndOfStream)
  118. {
  119. var line = reader.ReadLine();
  120. if (!string.IsNullOrWhiteSpace(line))
  121. {
  122. var parts = line.Split('|');
  123. if (parts.Length == 5)
  124. {
  125. list.Add(new CultureDto
  126. {
  127. DisplayName = parts[3],
  128. Name = parts[3],
  129. ThreeLetterISOLanguageName = parts[0],
  130. TwoLetterISOLanguageName = parts[2]
  131. });
  132. }
  133. }
  134. }
  135. }
  136. }
  137. return list.Where(i => !string.IsNullOrWhiteSpace(i.Name) &&
  138. !string.IsNullOrWhiteSpace(i.DisplayName) &&
  139. !string.IsNullOrWhiteSpace(i.ThreeLetterISOLanguageName) &&
  140. !string.IsNullOrWhiteSpace(i.TwoLetterISOLanguageName));
  141. }
  142. /// <summary>
  143. /// Gets the countries.
  144. /// </summary>
  145. /// <returns>IEnumerable{CountryInfo}.</returns>
  146. public IEnumerable<CountryInfo> GetCountries()
  147. {
  148. var type = GetType();
  149. var path = type.Namespace + ".countries.json";
  150. using (var stream = type.Assembly.GetManifestResourceStream(path))
  151. {
  152. return _jsonSerializer.DeserializeFromStream<List<CountryInfo>>(stream);
  153. }
  154. }
  155. /// <summary>
  156. /// Gets the parental ratings.
  157. /// </summary>
  158. /// <returns>IEnumerable{ParentalRating}.</returns>
  159. public IEnumerable<ParentalRating> GetParentalRatings()
  160. {
  161. return GetParentalRatingsDictionary().Values.ToList();
  162. }
  163. /// <summary>
  164. /// Gets the parental ratings dictionary.
  165. /// </summary>
  166. /// <returns>Dictionary{System.StringParentalRating}.</returns>
  167. private Dictionary<string, ParentalRating> GetParentalRatingsDictionary()
  168. {
  169. var countryCode = _configurationManager.Configuration.MetadataCountryCode;
  170. if (string.IsNullOrEmpty(countryCode))
  171. {
  172. countryCode = "us";
  173. }
  174. var ratings = GetRatings(countryCode);
  175. if (ratings == null)
  176. {
  177. ratings = GetRatings("us");
  178. }
  179. return ratings;
  180. }
  181. /// <summary>
  182. /// Gets the ratings.
  183. /// </summary>
  184. /// <param name="countryCode">The country code.</param>
  185. private Dictionary<string, ParentalRating> GetRatings(string countryCode)
  186. {
  187. Dictionary<string, ParentalRating> value;
  188. _allParentalRatings.TryGetValue(countryCode, out value);
  189. return value;
  190. }
  191. /// <summary>
  192. /// Loads the ratings.
  193. /// </summary>
  194. /// <param name="file">The file.</param>
  195. /// <returns>Dictionary{System.StringParentalRating}.</returns>
  196. private void LoadRatings(string file)
  197. {
  198. var dict = File.ReadAllLines(file).Select(i =>
  199. {
  200. if (!string.IsNullOrWhiteSpace(i))
  201. {
  202. var parts = i.Split(',');
  203. if (parts.Length == 2)
  204. {
  205. int value;
  206. if (int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out value))
  207. {
  208. return new ParentalRating { Name = parts[0], Value = value };
  209. }
  210. }
  211. }
  212. return null;
  213. })
  214. .Where(i => i != null)
  215. .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
  216. var countryCode = _fileSystem.GetFileNameWithoutExtension(file)
  217. .Split('-')
  218. .Last();
  219. _allParentalRatings.TryAdd(countryCode, dict);
  220. }
  221. private readonly string[] _unratedValues = {"n/a", "unrated", "not rated"};
  222. /// <summary>
  223. /// Gets the rating level.
  224. /// </summary>
  225. public int? GetRatingLevel(string rating)
  226. {
  227. if (string.IsNullOrEmpty(rating))
  228. {
  229. throw new ArgumentNullException("rating");
  230. }
  231. if (_unratedValues.Contains(rating, StringComparer.OrdinalIgnoreCase))
  232. {
  233. return null;
  234. }
  235. // Fairly common for some users to have "Rated R" in their rating field
  236. rating = rating.Replace("Rated ", string.Empty, StringComparison.OrdinalIgnoreCase);
  237. var ratingsDictionary = GetParentalRatingsDictionary();
  238. ParentalRating value;
  239. if (!ratingsDictionary.TryGetValue(rating, out value))
  240. {
  241. // If we don't find anything check all ratings systems
  242. foreach (var dictionary in _allParentalRatings.Values)
  243. {
  244. if (dictionary.TryGetValue(rating, out value))
  245. {
  246. return value.Value;
  247. }
  248. }
  249. }
  250. return value == null ? (int?)null : value.Value;
  251. }
  252. public string GetLocalizedString(string phrase)
  253. {
  254. return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
  255. }
  256. public string GetLocalizedString(string phrase, string culture)
  257. {
  258. var dictionary = GetLocalizationDictionary(culture);
  259. string value;
  260. if (dictionary.TryGetValue(phrase, out value))
  261. {
  262. return value;
  263. }
  264. return phrase;
  265. }
  266. private readonly ConcurrentDictionary<string, Dictionary<string, string>> _dictionaries =
  267. new ConcurrentDictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
  268. public Dictionary<string, string> GetLocalizationDictionary(string culture)
  269. {
  270. const string prefix = "Core";
  271. var key = prefix + culture;
  272. return _dictionaries.GetOrAdd(key, k => GetDictionary(prefix, culture, "core.json"));
  273. }
  274. private Dictionary<string, string> GetDictionary(string prefix, string culture, string baseFilename)
  275. {
  276. var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  277. var assembly = GetType().Assembly;
  278. var namespaceName = GetType().Namespace + "." + prefix;
  279. CopyInto(dictionary, namespaceName + "." + baseFilename, assembly);
  280. CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture), assembly);
  281. return dictionary;
  282. }
  283. private void CopyInto(IDictionary<string, string> dictionary, string resourcePath, Assembly assembly)
  284. {
  285. using (var stream = assembly.GetManifestResourceStream(resourcePath))
  286. {
  287. if (stream != null)
  288. {
  289. var dict = _jsonSerializer.DeserializeFromStream<Dictionary<string, string>>(stream);
  290. foreach (var key in dict.Keys)
  291. {
  292. dictionary[key] = dict[key];
  293. }
  294. }
  295. }
  296. }
  297. private string GetResourceFilename(string culture)
  298. {
  299. var parts = culture.Split('-');
  300. if (parts.Length == 2)
  301. {
  302. culture = parts[0].ToLower() + "-" + parts[1].ToUpper();
  303. }
  304. else
  305. {
  306. culture = culture.ToLower();
  307. }
  308. return culture + ".json";
  309. }
  310. public IEnumerable<LocalizatonOption> GetLocalizationOptions()
  311. {
  312. return new List<LocalizatonOption>
  313. {
  314. new LocalizatonOption{ Name="Arabic", Value="ar"},
  315. new LocalizatonOption{ Name="Bulgarian (Bulgaria)", Value="bg-BG"},
  316. new LocalizatonOption{ Name="Catalan", Value="ca"},
  317. new LocalizatonOption{ Name="Chinese Simplified", Value="zh-CN"},
  318. new LocalizatonOption{ Name="Chinese Traditional", Value="zh-TW"},
  319. new LocalizatonOption{ Name="Croatian", Value="hr"},
  320. new LocalizatonOption{ Name="Czech", Value="cs"},
  321. new LocalizatonOption{ Name="Danish", Value="da"},
  322. new LocalizatonOption{ Name="Dutch", Value="nl"},
  323. new LocalizatonOption{ Name="English (United Kingdom)", Value="en-GB"},
  324. new LocalizatonOption{ Name="English (United States)", Value="en-us"},
  325. new LocalizatonOption{ Name="Finnish", Value="fi"},
  326. new LocalizatonOption{ Name="French", Value="fr"},
  327. new LocalizatonOption{ Name="French (Canada)", Value="fr-CA"},
  328. new LocalizatonOption{ Name="German", Value="de"},
  329. new LocalizatonOption{ Name="Greek", Value="el"},
  330. new LocalizatonOption{ Name="Hebrew", Value="he"},
  331. new LocalizatonOption{ Name="Hungarian", Value="hu"},
  332. new LocalizatonOption{ Name="Indonesian", Value="id"},
  333. new LocalizatonOption{ Name="Italian", Value="it"},
  334. new LocalizatonOption{ Name="Kazakh", Value="kk"},
  335. new LocalizatonOption{ Name="Norwegian Bokmål", Value="nb"},
  336. new LocalizatonOption{ Name="Polish", Value="pl"},
  337. new LocalizatonOption{ Name="Portuguese (Brazil)", Value="pt-BR"},
  338. new LocalizatonOption{ Name="Portuguese (Portugal)", Value="pt-PT"},
  339. new LocalizatonOption{ Name="Russian", Value="ru"},
  340. new LocalizatonOption{ Name="Slovenian (Slovenia)", Value="sl-SI"},
  341. new LocalizatonOption{ Name="Spanish", Value="es-ES"},
  342. new LocalizatonOption{ Name="Spanish (Mexico)", Value="es-MX"},
  343. new LocalizatonOption{ Name="Swedish", Value="sv"},
  344. new LocalizatonOption{ Name="Turkish", Value="tr"},
  345. new LocalizatonOption{ Name="Ukrainian", Value="uk"},
  346. new LocalizatonOption{ Name="Vietnamese", Value="vi"}
  347. }.OrderBy(i => i.Name);
  348. }
  349. }
  350. }