fixed ratings. moved them to static text files

This commit is contained in:
Luke Pulverenti 2013-06-10 13:46:11 -04:00
parent c174859b52
commit d2933cab73
17 changed files with 264 additions and 438 deletions

View File

@ -202,6 +202,7 @@ namespace MediaBrowser.Api.UserLibrary
/// </summary>
private readonly ILibraryManager _libraryManager;
private readonly ILibrarySearchEngine _searchEngine;
private readonly ILocalizationManager _localization;
/// <summary>
/// Initializes a new instance of the <see cref="ItemsService" /> class.
@ -451,17 +452,47 @@ namespace MediaBrowser.Api.UserLibrary
// Min official rating
if (!string.IsNullOrEmpty(request.MinOfficialRating))
{
var level = Ratings.Level(request.MinOfficialRating);
var level = _localization.GetRatingLevel(request.MinOfficialRating);
items = items.Where(i => Ratings.Level(i.CustomRating ?? i.OfficialRating) >= level);
if (level.HasValue)
{
items = items.Where(i =>
{
var rating = i.CustomRating ?? i.OfficialRating;
if (string.IsNullOrEmpty(rating))
{
return true;
}
var itemLevel = _localization.GetRatingLevel(rating);
return !itemLevel.HasValue || itemLevel.Value >= level.Value;
});
}
}
// Max official rating
if (!string.IsNullOrEmpty(request.MaxOfficialRating))
{
var level = Ratings.Level(request.MaxOfficialRating);
var level = _localization.GetRatingLevel(request.MinOfficialRating);
items = items.Where(i => Ratings.Level(i.CustomRating ?? i.OfficialRating) <= level);
if (level.HasValue)
{
items = items.Where(i =>
{
var rating = i.CustomRating ?? i.OfficialRating;
if (string.IsNullOrEmpty(rating))
{
return true;
}
var itemLevel = _localization.GetRatingLevel(rating);
return !itemLevel.HasValue || itemLevel.Value <= level.Value;
});
}
}
// Exclude item types

View File

@ -143,6 +143,7 @@ namespace MediaBrowser.Controller.Entities
public static ILibraryManager LibraryManager { get; set; }
public static IServerConfigurationManager ConfigurationManager { get; set; }
public static IProviderManager ProviderManager { get; set; }
public static ILocalizationManager LocalizationManager { get; set; }
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
@ -1081,9 +1082,10 @@ namespace MediaBrowser.Controller.Entities
/// Determines if a given user has access to this item
/// </summary>
/// <param name="user">The user.</param>
/// <param name="localizationManager">The localization manager.</param>
/// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
/// <exception cref="System.ArgumentNullException"></exception>
public bool IsParentalAllowed(User user)
/// <exception cref="System.ArgumentNullException">user</exception>
public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
{
if (user == null)
{
@ -1095,12 +1097,22 @@ namespace MediaBrowser.Controller.Entities
return true;
}
if (user.Configuration.BlockNotRated && string.IsNullOrEmpty(CustomRating ?? OfficialRating))
var rating = CustomRating ?? OfficialRating;
if (user.Configuration.BlockNotRated && string.IsNullOrEmpty(rating))
{
return false;
}
return Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating.Value;
var value = localizationManager.GetRatingLevel(rating);
// Could not determine the integer value
if (!value.HasValue)
{
return true;
}
return value.Value <= user.Configuration.MaxParentalRating.Value;
}
/// <summary>
@ -1117,7 +1129,7 @@ namespace MediaBrowser.Controller.Entities
throw new ArgumentNullException("user");
}
return IsParentalAllowed(user);
return IsParentalAllowed(user, LocalizationManager);
}
/// <summary>

View File

@ -1,23 +0,0 @@
using System.Collections.Generic;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class AURatingsDictionary
/// </summary>
public class AURatingsDictionary : Dictionary<string, int>
{
/// <summary>
/// Initializes a new instance of the <see cref="AURatingsDictionary" /> class.
/// </summary>
public AURatingsDictionary()
{
Add("AU-G", 1);
Add("AU-PG", 5);
Add("AU-M", 6);
Add("AU-M15+", 7);
Add("AU-R18+", 9);
Add("AU-X18+", 10);
}
}
}

View File

@ -1,24 +0,0 @@
using System.Collections.Generic;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class GBRatingsDictionary
/// </summary>
public class GBRatingsDictionary : Dictionary<string, int>
{
/// <summary>
/// Initializes a new instance of the <see cref="GBRatingsDictionary" /> class.
/// </summary>
public GBRatingsDictionary()
{
Add("GB-U", 1);
Add("GB-PG", 5);
Add("GB-12", 6);
Add("GB-12A", 7);
Add("GB-15", 8);
Add("GB-18", 9);
Add("GB-R18", 15);
}
}
}

View File

@ -24,5 +24,11 @@ namespace MediaBrowser.Controller.Localization
/// </summary>
/// <returns>IEnumerable{ParentalRating}.</returns>
IEnumerable<ParentalRating> GetParentalRatings();
/// <summary>
/// Gets the rating level.
/// </summary>
/// <param name="rating">The rating.</param>
/// <returns>System.Int32.</returns>
int? GetRatingLevel(string rating);
}
}

View File

@ -1,23 +0,0 @@
using System.Collections.Generic;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class NLRatingsDictionary
/// </summary>
public class NLRatingsDictionary : Dictionary<string, int>
{
/// <summary>
/// Initializes a new instance of the <see cref="NLRatingsDictionary" /> class.
/// </summary>
public NLRatingsDictionary()
{
Add("NL-AL", 1);
Add("NL-MG6", 2);
Add("NL-6", 3);
Add("NL-9", 5);
Add("NL-12", 6);
Add("NL-16", 8);
}
}
}

View File

@ -1,184 +0,0 @@
using System.Globalization;
using MediaBrowser.Controller.Configuration;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class Ratings
/// </summary>
public static class Ratings
{
public static IServerConfigurationManager ConfigurationManager;
/// <summary>
/// The ratings def
/// </summary>
private static RatingsDefinition ratingsDef;
/// <summary>
/// The _ratings dict
/// </summary>
private static Dictionary<string, int> _ratingsDict;
/// <summary>
/// Gets the ratings dict.
/// </summary>
/// <value>The ratings dict.</value>
public static Dictionary<string, int> RatingsDict
{
get { return _ratingsDict ?? (_ratingsDict = Initialize(false, ConfigurationManager)); }
}
/// <summary>
/// The ratings strings
/// </summary>
private static readonly Dictionary<int, string> ratingsStrings = new Dictionary<int, string>();
/// <summary>
/// Tries the add.
/// </summary>
/// <typeparam name="TKey">The type of the T key.</typeparam>
/// <typeparam name="TValue">The type of the T value.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
private static void TryAdd<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key))
{
return;
}
dictionary.Add(key, value);
}
/// <summary>
/// Initializes the specified block unrated.
/// </summary>
/// <param name="blockUnrated">if set to <c>true</c> [block unrated].</param>
/// <returns>Dictionary{System.StringSystem.Int32}.</returns>
public static Dictionary<string, int> Initialize(bool blockUnrated, IServerConfigurationManager configurationManager)
{
//build our ratings dictionary from the combined local one and us one
ratingsDef = new RatingsDefinition(Path.Combine(configurationManager.ApplicationPaths.LocalizationPath, "Ratings-" + configurationManager.Configuration.MetadataCountryCode + ".txt"), configurationManager);
//global value of None
var dict = new Dictionary<string, int> { { "None", -1 } };
foreach (var pair in ratingsDef.RatingsDict)
{
TryAdd(dict, pair.Key, pair.Value);
}
if (configurationManager.Configuration.MetadataCountryCode.ToUpper() != "US")
{
foreach (var pair in new USRatingsDictionary())
{
TryAdd(dict, pair.Key, pair.Value);
}
}
//global values of CS
TryAdd(dict, "CS", 1000);
TryAdd(dict, "", blockUnrated ? 1000 : 0);
//and rating reverse lookup dictionary (non-redundant ones)
ratingsStrings.Clear();
var lastLevel = -10;
ratingsStrings.Add(-1, LocalizedStrings.Instance.GetString("Any"));
foreach (var pair in ratingsDef.RatingsDict.OrderBy(p => p.Value))
{
if (pair.Value > lastLevel)
{
lastLevel = pair.Value;
TryAdd(ratingsStrings, pair.Value, pair.Key);
}
}
TryAdd(ratingsStrings, 999, "CS");
return dict;
}
/// <summary>
/// Switches the unrated.
/// </summary>
/// <param name="block">if set to <c>true</c> [block].</param>
public static void SwitchUnrated(bool block)
{
RatingsDict.Remove("");
RatingsDict.Add("", block ? 1000 : 0);
}
/// <summary>
/// Levels the specified rating STR.
/// </summary>
/// <param name="ratingStr">The rating STR.</param>
/// <returns>System.Int32.</returns>
public static int Level(string ratingStr)
{
if (ratingStr == null) ratingStr = "";
if (RatingsDict.ContainsKey(ratingStr))
return RatingsDict[ratingStr];
string stripped = StripCountry(ratingStr);
if (RatingsDict.ContainsKey(stripped))
return RatingsDict[stripped];
return RatingsDict[""]; //return "unknown" level
}
/// <summary>
/// Strips the country.
/// </summary>
/// <param name="rating">The rating.</param>
/// <returns>System.String.</returns>
private static string StripCountry(string rating)
{
int start = rating.IndexOf('-');
return start > 0 ? rating.Substring(start + 1) : rating;
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <param name="level">The level.</param>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public static string ToString(int level)
{
//return the closest one
while (level > 0)
{
if (ratingsStrings.ContainsKey(level))
return ratingsStrings[level];
level--;
}
return ratingsStrings.Values.FirstOrDefault(); //default to first one
}
/// <summary>
/// To the strings.
/// </summary>
/// <returns>List{System.String}.</returns>
public static List<string> ToStrings()
{
//return the whole list of ratings strings
return ratingsStrings.Values.ToList();
}
/// <summary>
/// To the values.
/// </summary>
/// <returns>List{System.Int32}.</returns>
public static List<int> ToValues()
{
//return the whole list of ratings values
return ratingsStrings.Keys.ToList();
}
//public Microsoft.MediaCenter.UI.Image RatingImage(string rating)
//{
// return Helper.GetMediaInfoImage("Rated_" + rating);
//}
}
}

View File

@ -1,122 +0,0 @@
using MediaBrowser.Controller.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class RatingsDefinition
/// </summary>
public class RatingsDefinition
{
/// <summary>
/// Initializes a new instance of the <see cref="RatingsDefinition" /> class.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="configurationManager">The configuration manager.</param>
public RatingsDefinition(string file, IServerConfigurationManager configurationManager)
{
this.file = file;
if (!Load())
{
Init(configurationManager.Configuration.MetadataCountryCode.ToUpper());
}
}
/// <summary>
/// Inits the specified country.
/// </summary>
/// <param name="country">The country.</param>
protected void Init(string country)
{
//intitialze based on country
switch (country)
{
case "US":
RatingsDict = new USRatingsDictionary();
break;
case "GB":
RatingsDict = new GBRatingsDictionary();
break;
case "NL":
RatingsDict = new NLRatingsDictionary();
break;
case "AU":
RatingsDict = new AURatingsDictionary();
break;
default:
RatingsDict = new USRatingsDictionary();
break;
}
Save();
}
/// <summary>
/// The file
/// </summary>
readonly string file;
/// <summary>
/// Save to file
/// </summary>
public void Save()
{
// Use simple text serialization - no need for xml
using (var fs = new StreamWriter(file))
{
foreach (var pair in RatingsDict)
{
fs.WriteLine(pair.Key + "," + pair.Value);
}
}
}
/// <summary>
/// Load from file
/// </summary>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
protected bool Load()
{
// Read back in our simple serialized format
RatingsDict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
try
{
using (var fs = new StreamReader(file))
{
while (!fs.EndOfStream)
{
var line = fs.ReadLine() ?? "";
var values = line.Split(',');
if (values.Length == 2)
{
int value;
if (int.TryParse(values[1], out value))
{
RatingsDict[values[0].Trim()] = value;
}
else
{
//Logger.Error("Invalid line in ratings file " + file + "(" + line + ")");
}
}
}
}
}
catch
{
// Couldn't load - probably just not there yet
return false;
}
return true;
}
/// <summary>
/// The ratings dict
/// </summary>
public Dictionary<string, int> RatingsDict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
}
}

View File

@ -1,39 +0,0 @@
using System.Collections.Generic;
namespace MediaBrowser.Controller.Localization
{
/// <summary>
/// Class USRatingsDictionary
/// </summary>
public class USRatingsDictionary : Dictionary<string,int>
{
/// <summary>
/// Initializes a new instance of the <see cref="USRatingsDictionary" /> class.
/// </summary>
public USRatingsDictionary()
{
Add("G", 1);
Add("E", 1);
Add("EC", 1);
Add("TV-G", 1);
Add("TV-Y", 2);
Add("TV-Y7", 3);
Add("TV-Y7-FV", 4);
Add("PG", 5);
Add("TV-PG", 5);
Add("PG-13", 7);
Add("T", 7);
Add("TV-14", 8);
Add("R", 9);
Add("M", 9);
Add("TV-MA", 9);
Add("NC-17", 10);
Add("AO", 15);
Add("RP", 15);
Add("UR", 15);
Add("NR", 15);
Add("X", 15);
Add("XXX", 100);
}
}
}

View File

@ -131,15 +131,9 @@
<Compile Include="Library\ILibraryManager.cs" />
<Compile Include="Library\IUserManager.cs" />
<Compile Include="Library\Profiler.cs" />
<Compile Include="Localization\AURatingsDictionary.cs" />
<Compile Include="Localization\BaseStrings.cs" />
<Compile Include="Localization\GBRatingsDictionary.cs" />
<Compile Include="Localization\LocalizedStringData.cs" />
<Compile Include="Localization\LocalizedStrings.cs" />
<Compile Include="Localization\NLRatingsDictionary.cs" />
<Compile Include="Localization\Ratings.cs" />
<Compile Include="Localization\RatingsDefinition.cs" />
<Compile Include="Localization\USRatingsDictionary.cs" />
<Compile Include="MediaInfo\FFMpegManager.cs" />
<Compile Include="Persistence\IDisplayPreferencesRepository.cs" />
<Compile Include="Persistence\IItemRepository.cs" />

View File

@ -1,10 +1,15 @@
using MediaBrowser.Controller.Localization;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Localization;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MoreLinq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Localization
{
@ -13,6 +18,37 @@ namespace MediaBrowser.Server.Implementations.Localization
/// </summary>
public class LocalizationManager : ILocalizationManager
{
/// <summary>
/// The _configuration manager
/// </summary>
private readonly IServerConfigurationManager _configurationManager;
/// <summary>
/// The us culture
/// </summary>
private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
/// <summary>
/// Initializes a new instance of the <see cref="LocalizationManager"/> class.
/// </summary>
/// <param name="configurationManager">The configuration manager.</param>
public LocalizationManager(IServerConfigurationManager configurationManager)
{
_configurationManager = configurationManager;
}
/// <summary>
/// Gets the localization path.
/// </summary>
/// <value>The localization path.</value>
public string LocalizationPath
{
get
{
return Path.Combine(_configurationManager.ApplicationPaths.ProgramDataPath, "localization");
}
}
/// <summary>
/// Gets the cultures.
/// </summary>
@ -56,10 +92,125 @@ namespace MediaBrowser.Server.Implementations.Localization
/// <returns>IEnumerable{ParentalRating}.</returns>
public IEnumerable<ParentalRating> GetParentalRatings()
{
return Ratings.RatingsDict
.Select(k => new ParentalRating {Name = k.Key, Value = k.Value})
.OrderBy(p => p.Value)
.Where(p => p.Value > 0);
var path = GetRatingsFile();
return File.ReadAllLines(path).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)
.OrderBy(p => p.Value);
}
/// <summary>
/// Gets the ratings file.
/// </summary>
/// <returns>System.String.</returns>
private string GetRatingsFile()
{
var countryCode = _configurationManager.Configuration.MetadataCountryCode;
if (string.IsNullOrEmpty(countryCode))
{
countryCode = "us";
}
return GetRatingsFile(countryCode).Result ?? GetRatingsFile("us").Result;
}
/// <summary>
/// Gets the ratings file.
/// </summary>
/// <param name="countryCode">The country code.</param>
/// <returns>Task{System.String}.</returns>
private async Task<string> GetRatingsFile(string countryCode)
{
countryCode = countryCode.ToLower();
var path = Path.Combine(LocalizationPath, "ratings-" + countryCode + ".txt");
if (!File.Exists(path))
{
// Extract embedded resource
var type = GetType();
var resourcePath = type.Namespace + ".Ratings." + countryCode + ".txt";
using (var stream = type.Assembly.GetManifestResourceStream(resourcePath))
{
if (stream == null)
{
return null;
}
var parentPath = Path.GetDirectoryName(path);
if (!Directory.Exists(parentPath))
{
Directory.CreateDirectory(parentPath);
}
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, true))
{
await stream.CopyToAsync(fs).ConfigureAwait(false);
}
}
}
return path;
}
/// <summary>
/// Gets the rating level.
/// </summary>
/// <param name="rating">The rating.</param>
/// <returns>System.Int32.</returns>
/// <exception cref="System.ArgumentNullException">rating</exception>
public int? GetRatingLevel(string rating)
{
if (string.IsNullOrEmpty(rating))
{
throw new ArgumentNullException("rating");
}
var ratingsDictionary = GetParentalRatings().ToDictionary(i => i.Name);
if (ratingsDictionary.ContainsKey(rating))
return ratingsDictionary[rating].Value;
var stripped = StripCountry(rating);
if (ratingsDictionary.ContainsKey(stripped))
return ratingsDictionary[stripped].Value;
return null;
}
/// <summary>
/// Strips the country.
/// </summary>
/// <param name="rating">The rating.</param>
/// <returns>System.String.</returns>
private static string StripCountry(string rating)
{
int start = rating.IndexOf('-');
return start > 0 ? rating.Substring(start + 1) : rating;
}
}
}

View File

@ -0,0 +1,6 @@
AU-G,1
AU-PG,5
AU-M,6
AU-M15+,8
AU-R18+,9
AU-X18+,10

View File

@ -0,0 +1,7 @@
GB-U,1
GB-PG,5
GB-12,6
GB-12A,7
GB-15,8
GB-18,9
GB-R18,15

View File

@ -0,0 +1,6 @@
NL-AL,1
NL-MG6,2
NL-6,3
NL-9,5
NL-12,6
NL-16,8

View File

@ -0,0 +1,22 @@
G,1
E,1
EC,1
TV-G,1
TV-Y,2
TV-Y7,3
TV-Y7-FV,4
PG,5
TV-PG,5
PG-13,7
T,7
TV-14,8
R,9
M,9
TV-MA,9
NC-17,10
AO,15
RP,15
UR,15
NR,15
X,15
XXX,100

View File

@ -204,6 +204,10 @@
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Localization\Ratings\us.txt" />
<EmbeddedResource Include="Localization\Ratings\au.txt" />
<EmbeddedResource Include="Localization\Ratings\gb.txt" />
<EmbeddedResource Include="Localization\Ratings\nl.txt" />
<Content Include="swagger-ui\css\hightlight.default.css">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>

View File

@ -172,6 +172,8 @@ namespace MediaBrowser.ServerApplication
/// <value>The media encoder.</value>
private IMediaEncoder MediaEncoder { get; set; }
private ILocalizationManager LocalizationManager { get; set; }
/// <summary>
/// Gets or sets the user data repository.
/// </summary>
@ -286,8 +288,8 @@ namespace MediaBrowser.ServerApplication
ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager);
RegisterSingleInstance(ServerManager);
var localizationManager = new LocalizationManager();
RegisterSingleInstance<ILocalizationManager>(localizationManager);
LocalizationManager = new LocalizationManager(ServerConfigurationManager);
RegisterSingleInstance(LocalizationManager);
var displayPreferencesTask = Task.Run(async () => await ConfigureDisplayPreferencesRepositories().ConfigureAwait(false));
var itemsTask = Task.Run(async () => await ConfigureItemRepositories().ConfigureAwait(false));
@ -367,9 +369,9 @@ namespace MediaBrowser.ServerApplication
BaseItem.ConfigurationManager = ServerConfigurationManager;
BaseItem.LibraryManager = LibraryManager;
BaseItem.ProviderManager = ProviderManager;
BaseItem.LocalizationManager = LocalizationManager;
User.XmlSerializer = XmlSerializer;
User.UserManager = UserManager;
Ratings.ConfigurationManager = ServerConfigurationManager;
LocalizedStrings.ApplicationPaths = ApplicationPaths;
}