BaseItemResolver.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Controller.Events;
  5. using MediaBrowser.Model.Entities;
  6. namespace MediaBrowser.Controller.Resolvers
  7. {
  8. public abstract class BaseItemResolver<T> : IBaseItemResolver
  9. where T : BaseItem, new()
  10. {
  11. protected virtual T Resolve(ItemResolveEventArgs args)
  12. {
  13. return null;
  14. }
  15. public virtual ResolverPriority Priority
  16. {
  17. get
  18. {
  19. return ResolverPriority.First;
  20. }
  21. }
  22. /// <summary>
  23. /// Sets initial values on the newly resolved item
  24. /// </summary>
  25. protected virtual void SetInitialItemValues(T item, ItemResolveEventArgs args)
  26. {
  27. // If the subclass didn't specify this
  28. if (string.IsNullOrEmpty(item.Path))
  29. {
  30. item.Path = args.Path;
  31. }
  32. // If the subclass didn't specify this
  33. if (args.Parent != null)
  34. {
  35. item.Parent = args.Parent;
  36. }
  37. item.Id = Kernel.GetMD5(item.Path);
  38. }
  39. public async Task<BaseItem> ResolvePath(ItemResolveEventArgs args)
  40. {
  41. T item = Resolve(args);
  42. if (item != null)
  43. {
  44. // Set initial values on the newly resolved item
  45. SetInitialItemValues(item, args);
  46. // Make sure the item has a name
  47. EnsureName(item);
  48. // Make sure DateCreated and DateModified have values
  49. EnsureDates(item);
  50. await Kernel.Instance.ExecuteMetadataProviders(item, args);
  51. }
  52. return item;
  53. }
  54. private void EnsureName(T item)
  55. {
  56. // If the subclass didn't supply a name, add it here
  57. if (string.IsNullOrEmpty(item.Name))
  58. {
  59. item.Name = Path.GetFileNameWithoutExtension(item.Path);
  60. }
  61. }
  62. /// <summary>
  63. /// Ensures DateCreated and DateModified have values
  64. /// </summary>
  65. private void EnsureDates(T item)
  66. {
  67. // If the subclass didn't supply dates, add them here
  68. if (item.DateCreated == DateTime.MinValue)
  69. {
  70. item.DateCreated = Path.IsPathRooted(item.Path) ? File.GetCreationTime(item.Path) : DateTime.Now;
  71. }
  72. if (item.DateModified == DateTime.MinValue)
  73. {
  74. item.DateModified = Path.IsPathRooted(item.Path) ? File.GetLastWriteTime(item.Path) : DateTime.Now;
  75. }
  76. }
  77. }
  78. /// <summary>
  79. /// Weed this to keep a list of resolvers, since Resolvers are built with generics
  80. /// </summary>
  81. public interface IBaseItemResolver
  82. {
  83. Task<BaseItem> ResolvePath(ItemResolveEventArgs args);
  84. ResolverPriority Priority { get; }
  85. }
  86. public enum ResolverPriority
  87. {
  88. First,
  89. Second,
  90. Third,
  91. Last
  92. }
  93. }