LocalizationManager.cs 15 KB

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