LocalizationManager.cs 13 KB

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