PosterEngine.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using InABox.Configuration;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace InABox.Core
  7. {
  8. public interface IPosterEngine<TPostable>
  9. where TPostable : Entity, IPostable
  10. {
  11. bool Process(IEnumerable<TPostable> posts);
  12. }
  13. public abstract class PosterEngine<TPostable, TPoster, TSettings> : IPosterEngine<TPostable>
  14. where TPostable : Entity, IPostable
  15. where TPoster : IPoster<TPostable, TSettings>
  16. where TSettings : PosterSettings<TPostable>, new()
  17. {
  18. protected static TPoster Poster = GetPoster();
  19. private static Type[]? _posters;
  20. private static TPoster GetPoster()
  21. {
  22. _posters ??= CoreUtils.TypeList(
  23. AppDomain.CurrentDomain.GetAssemblies(),
  24. x => x.IsClass
  25. && !x.IsAbstract
  26. && !x.IsGenericType
  27. && x.HasInterface(typeof(IPoster<,>))
  28. ).ToArray();
  29. var type = _posters.Where(x => typeof(TPoster).IsAssignableFrom(x)).FirstOrDefault()
  30. ?? throw new Exception($"No poster of type {typeof(TPoster)}.");
  31. return (TPoster)Activator.CreateInstance(type);
  32. }
  33. protected static TSettings GetSettings()
  34. {
  35. return new GlobalConfiguration<TSettings>(typeof(TPostable).Name).Load();
  36. }
  37. protected static string? GetScript()
  38. {
  39. return GetSettings().Script;
  40. }
  41. public abstract bool Process(IEnumerable<TPostable> posts);
  42. }
  43. }