BaseItemResolver.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. /// <summary>
  16. /// Sets initial values on the newly resolved item
  17. /// </summary>
  18. protected virtual void SetInitialItemValues(T item, ItemResolveEventArgs args)
  19. {
  20. // If the subclass didn't specify this
  21. if (string.IsNullOrEmpty(item.Path))
  22. {
  23. item.Path = args.Path;
  24. }
  25. // If the subclass didn't specify this
  26. if (args.Parent != null)
  27. {
  28. item.Parent = args.Parent;
  29. }
  30. item.Id = Kernel.GetMD5(item.Path);
  31. }
  32. public async Task<BaseItem> ResolvePath(ItemResolveEventArgs args)
  33. {
  34. T item = Resolve(args);
  35. if (item != null)
  36. {
  37. // Set initial values on the newly resolved item
  38. SetInitialItemValues(item, args);
  39. // Make sure the item has a name
  40. EnsureName(item);
  41. // Make sure DateCreated and DateModified have values
  42. EnsureDates(item);
  43. await Kernel.Instance.ExecuteMetadataProviders(item, args);
  44. }
  45. return item;
  46. }
  47. private void EnsureName(T item)
  48. {
  49. // If the subclass didn't supply a name, add it here
  50. if (string.IsNullOrEmpty(item.Name))
  51. {
  52. item.Name = Path.GetFileNameWithoutExtension(item.Path);
  53. }
  54. }
  55. /// <summary>
  56. /// Ensures DateCreated and DateModified have values
  57. /// </summary>
  58. private void EnsureDates(T item)
  59. {
  60. // If the subclass didn't supply dates, add them here
  61. if (item.DateCreated == DateTime.MinValue)
  62. {
  63. item.DateCreated = Path.IsPathRooted(item.Path) ? File.GetCreationTime(item.Path) : DateTime.Now;
  64. }
  65. if (item.DateModified == DateTime.MinValue)
  66. {
  67. item.DateModified = Path.IsPathRooted(item.Path) ? File.GetLastWriteTime(item.Path) : DateTime.Now;
  68. }
  69. }
  70. }
  71. /// <summary>
  72. /// Weed this to keep a list of resolvers, since Resolvers are built with generics
  73. /// </summary>
  74. public interface IBaseItemResolver
  75. {
  76. Task<BaseItem> ResolvePath(ItemResolveEventArgs args);
  77. }
  78. }