LocalizationManager.cs 14 KB

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