NameUtils.cs 3.0 KB

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