CustomPosterEngine.cs 2.3 KB

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