CustomPosterEngine.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using InABox.Core;
  2. using InABox.Scripting;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace InABox.Poster.Custom
  9. {
  10. public class CustomPosterEngine<TPostable> : PosterEngine<TPostable, ICustomPoster<TPostable>, CustomPosterSettings>
  11. where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
  12. {
  13. private ScriptDocument? _script;
  14. private bool _hasCheckedScript;
  15. private ScriptDocument? GetScriptDocument()
  16. {
  17. if (_hasCheckedScript)
  18. {
  19. return _script;
  20. }
  21. var settings = GetSettings();
  22. if (settings.ScriptEnabled && !string.IsNullOrWhiteSpace(settings.Script))
  23. {
  24. var document = new ScriptDocument(settings.Script);
  25. if (!document.Compile())
  26. {
  27. throw new Exception("Script failed to compile!");
  28. }
  29. _script = document;
  30. }
  31. else
  32. {
  33. _script = null;
  34. }
  35. _hasCheckedScript = true;
  36. return _script;
  37. }
  38. public override bool BeforePost(IDataModel<TPostable> model)
  39. {
  40. if (GetScriptDocument() is ScriptDocument script)
  41. {
  42. return script.Execute(methodname: "BeforePost", parameters: new object[] { model });
  43. }
  44. return false;
  45. }
  46. protected override IPostResult<TPostable> DoProcess(IDataModel<TPostable> model)
  47. {
  48. if (GetScriptDocument() is ScriptDocument script)
  49. {
  50. if(!script.Execute(methodname: "Process", parameters: new object[] { model }))
  51. {
  52. throw new Exception("Post Failed.");
  53. }
  54. var resultsObject = script.GetValue("Results");
  55. return (resultsObject as IPostResult<TPostable>)
  56. ?? throw new Exception($"Script 'Results' property expected to be IPostResult<{typeof(TPostable)}>, got {resultsObject}");
  57. }
  58. else
  59. {
  60. throw new Exception("Post Failed.");
  61. }
  62. }
  63. public override void AfterPost(IDataModel<TPostable> model, IPostResult<TPostable> result)
  64. {
  65. if (GetScriptDocument() is ScriptDocument script)
  66. {
  67. script.Execute(methodname: "AfterPost", parameters: new object[] { model });
  68. }
  69. }
  70. }
  71. }