2
0

NameUtils.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using MediaBrowser.Controller.Entities;
  2. using System;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace MediaBrowser.Server.Implementations.FileOrganization
  7. {
  8. public static class NameUtils
  9. {
  10. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  11. internal static Tuple<T, int> GetMatchScore<T>(string sortedName, int? year, T series)
  12. where T : BaseItem
  13. {
  14. var score = 0;
  15. var seriesNameWithoutYear = series.Name;
  16. if (series.ProductionYear.HasValue)
  17. {
  18. seriesNameWithoutYear = seriesNameWithoutYear.Replace(series.ProductionYear.Value.ToString(UsCulture), String.Empty);
  19. }
  20. if (IsNameMatch(sortedName, seriesNameWithoutYear))
  21. {
  22. score++;
  23. if (year.HasValue && series.ProductionYear.HasValue)
  24. {
  25. if (year.Value == series.ProductionYear.Value)
  26. {
  27. score++;
  28. }
  29. else
  30. {
  31. // Regardless of name, return a 0 score if the years don't match
  32. return new Tuple<T, int>(series, 0);
  33. }
  34. }
  35. }
  36. return new Tuple<T, int>(series, score);
  37. }
  38. private static bool IsNameMatch(string name1, string name2)
  39. {
  40. name1 = GetComparableName(name1);
  41. name2 = GetComparableName(name2);
  42. return String.Equals(name1, name2, StringComparison.OrdinalIgnoreCase);
  43. }
  44. private static string GetComparableName(string name)
  45. {
  46. // TODO: Improve this - should ignore spaces, periods, underscores, most likely all symbols and
  47. // possibly remove sorting words like "the", "and", etc.
  48. name = RemoveDiacritics(name);
  49. name = " " + name.ToLower() + " ";
  50. name = name.Replace(".", " ")
  51. .Replace("_", " ")
  52. .Replace("&", " ")
  53. .Replace("!", " ")
  54. .Replace("(", " ")
  55. .Replace(")", " ")
  56. .Replace(",", " ")
  57. .Replace("-", " ")
  58. .Replace(" a ", String.Empty)
  59. .Replace(" the ", String.Empty)
  60. .Replace(" ", String.Empty);
  61. return name.Trim();
  62. }
  63. /// <summary>
  64. /// Removes the diacritics.
  65. /// </summary>
  66. /// <param name="text">The text.</param>
  67. /// <returns>System.String.</returns>
  68. private static string RemoveDiacritics(string text)
  69. {
  70. return String.Concat(
  71. text.Normalize(NormalizationForm.FormD)
  72. .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
  73. UnicodeCategory.NonSpacingMark)
  74. ).Normalize(NormalizationForm.FormC);
  75. }
  76. }
  77. }