using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Localization;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Serialization;
using MoreLinq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using MediaBrowser.Common.Extensions;
namespace MediaBrowser.Server.Implementations.Localization
{
///
/// Class LocalizationManager
///
public class LocalizationManager : ILocalizationManager
{
///
/// The _configuration manager
///
private readonly IServerConfigurationManager _configurationManager;
///
/// The us culture
///
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
private readonly ConcurrentDictionary> _allParentalRatings =
new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
private readonly IFileSystem _fileSystem;
private readonly IJsonSerializer _jsonSerializer;
///
/// Initializes a new instance of the class.
///
/// The configuration manager.
public LocalizationManager(IServerConfigurationManager configurationManager, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
{
_configurationManager = configurationManager;
_fileSystem = fileSystem;
_jsonSerializer = jsonSerializer;
ExtractAll();
}
private void ExtractAll()
{
var type = GetType();
var resourcePath = type.Namespace + ".Ratings.";
var localizationPath = LocalizationPath;
Directory.CreateDirectory(localizationPath);
var existingFiles = Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly)
.Select(Path.GetFileName)
.ToList();
// Extract from the assembly
foreach (var resource in type.Assembly
.GetManifestResourceNames()
.Where(i => i.StartsWith(resourcePath)))
{
var filename = "ratings-" + resource.Substring(resourcePath.Length);
if (!existingFiles.Contains(filename))
{
using (var stream = type.Assembly.GetManifestResourceStream(resource))
{
using (var fs = _fileSystem.GetFileStream(Path.Combine(localizationPath, filename), FileMode.Create, FileAccess.Write, FileShare.Read))
{
stream.CopyTo(fs);
}
}
}
}
foreach (var file in Directory.EnumerateFiles(localizationPath, "ratings-*.txt", SearchOption.TopDirectoryOnly))
{
LoadRatings(file);
}
}
///
/// Gets the localization path.
///
/// The localization path.
public string LocalizationPath
{
get
{
return Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
}
}
///
/// Gets the cultures.
///
/// IEnumerable{CultureDto}.
public IEnumerable GetCultures()
{
return CultureInfo.GetCultures(CultureTypes.AllCultures)
.OrderBy(c => c.DisplayName)
.DistinctBy(c => c.TwoLetterISOLanguageName + c.ThreeLetterISOLanguageName)
.Select(c => new CultureDto
{
Name = c.Name,
DisplayName = c.DisplayName,
ThreeLetterISOLanguageName = c.ThreeLetterISOLanguageName,
TwoLetterISOLanguageName = c.TwoLetterISOLanguageName
});
}
///
/// Gets the countries.
///
/// IEnumerable{CountryInfo}.
public IEnumerable GetCountries()
{
return CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Select(c => new RegionInfo(c.LCID))
.OrderBy(c => c.DisplayName)
.DistinctBy(c => c.TwoLetterISORegionName)
.Select(c => new CountryInfo
{
Name = c.Name,
DisplayName = c.DisplayName,
TwoLetterISORegionName = c.TwoLetterISORegionName,
ThreeLetterISORegionName = c.ThreeLetterISORegionName
});
}
///
/// Gets the parental ratings.
///
/// IEnumerable{ParentalRating}.
public IEnumerable GetParentalRatings()
{
return GetParentalRatingsDictionary().Values.ToList();
}
///
/// Gets the parental ratings dictionary.
///
/// Dictionary{System.StringParentalRating}.
private Dictionary GetParentalRatingsDictionary()
{
var countryCode = _configurationManager.Configuration.MetadataCountryCode;
if (string.IsNullOrEmpty(countryCode))
{
countryCode = "us";
}
var ratings = GetRatings(countryCode);
if (ratings == null)
{
ratings = GetRatings("us");
}
return ratings;
}
///
/// Gets the ratings.
///
/// The country code.
private Dictionary GetRatings(string countryCode)
{
Dictionary value;
_allParentalRatings.TryGetValue(countryCode, out value);
return value;
}
///
/// Loads the ratings.
///
/// The file.
/// Dictionary{System.StringParentalRating}.
private void LoadRatings(string file)
{
var dict = File.ReadAllLines(file).Select(i =>
{
if (!string.IsNullOrWhiteSpace(i))
{
var parts = i.Split(',');
if (parts.Length == 2)
{
int value;
if (int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out value))
{
return new ParentalRating { Name = parts[0], Value = value };
}
}
}
return null;
})
.Where(i => i != null)
.ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);
var countryCode = Path.GetFileNameWithoutExtension(file).Split('-').Last();
_allParentalRatings.TryAdd(countryCode, dict);
}
///
/// Gets the rating level.
///
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
{
throw new ArgumentNullException("rating");
}
var ratingsDictionary = GetParentalRatingsDictionary();
ParentalRating value;
if (!ratingsDictionary.TryGetValue(rating, out value))
{
// If we don't find anything check all ratings systems
foreach (var dictionary in _allParentalRatings.Values)
{
if (dictionary.TryGetValue(rating, out value))
{
return value.Value;
}
}
}
return value == null ? (int?)null : value.Value;
}
public string GetLocalizedString(string phrase)
{
return GetLocalizedString(phrase, _configurationManager.Configuration.UICulture);
}
public string GetLocalizedString(string phrase, string culture)
{
var dictionary = GetLocalizationDictionary(culture);
string value;
if (dictionary.TryGetValue(phrase, out value))
{
return value;
}
return phrase;
}
private readonly ConcurrentDictionary> _dictionaries =
new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
public Dictionary GetLocalizationDictionary(string culture)
{
const string prefix = "Server";
var key = prefix + culture;
return _dictionaries.GetOrAdd(key, k => GetDictionary(prefix, culture, "server.json"));
}
public Dictionary GetJavaScriptLocalizationDictionary(string culture)
{
const string prefix = "JavaScript";
var key = prefix + culture;
return _dictionaries.GetOrAdd(key, k => GetDictionary(prefix, culture, "javascript.json"));
}
private Dictionary GetDictionary(string prefix, string culture, string baseFilename)
{
var dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
var assembly = GetType().Assembly;
var namespaceName = GetType().Namespace + "." + prefix;
CopyInto(dictionary, namespaceName + "." + baseFilename, assembly);
CopyInto(dictionary, namespaceName + "." + GetResourceFilename(culture), assembly);
return dictionary;
}
private void CopyInto(IDictionary dictionary, string resourcePath, Assembly assembly)
{
using (var stream = assembly.GetManifestResourceStream(resourcePath))
{
if (stream != null)
{
var dict = _jsonSerializer.DeserializeFromStream>(stream);
foreach (var key in dict.Keys)
{
dictionary[key] = dict[key];
}
}
}
}
private string GetResourceFilename(string culture)
{
var parts = culture.Split('-');
if (parts.Length == 2)
{
culture = parts[0].ToLower() + "_" + parts[1].ToUpper();
}
else
{
culture = culture.ToLower();
}
return culture + ".json";
}
public IEnumerable GetLocalizationOptions()
{
return new List
{
new LocalizatonOption{ Name="English (United States)", Value="en-us"},
new LocalizatonOption{ Name="German", Value="de"},
new LocalizatonOption{ Name="Portuguese (Portugal)", Value="pt-PT"},
new LocalizatonOption{ Name="Russian", Value="ru"}
}.OrderBy(i => i.Name);
}
public string LocalizeDocument(string document, string culture, Func tokenBuilder)
{
foreach (var pair in GetLocalizationDictionary(culture).ToList())
{
var token = tokenBuilder(pair.Key);
document = document.Replace(token, pair.Value, StringComparison.Ordinal);
}
return document;
}
}
}