PosterEngine.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. using InABox.Clients;
  2. using InABox.Configuration;
  3. using InABox.Core.Postable;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. namespace InABox.Core
  10. {
  11. public interface IPosterEngine<TPostable>
  12. where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
  13. {
  14. bool Process(IDataModel<TPostable> model);
  15. }
  16. public interface IPosterEngine<TPostable, TPoster, TSettings> : IPosterEngine<TPostable>
  17. where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
  18. where TPoster : IPoster<TPostable, TSettings>
  19. where TSettings : PosterSettings, new()
  20. {
  21. }
  22. internal static class PosterEngineUtils
  23. {
  24. private static Type[]? _posters;
  25. public static Type GetPoster(Type TPoster)
  26. {
  27. _posters ??= CoreUtils.TypeList(
  28. AppDomain.CurrentDomain.GetAssemblies(),
  29. x => x.IsClass
  30. && !x.IsAbstract
  31. && !x.IsGenericType
  32. && x.HasInterface(typeof(IPoster<,>))
  33. ).ToArray();
  34. return _posters.Where(x => TPoster.IsAssignableFrom(x)).FirstOrDefault()
  35. ?? throw new Exception($"No poster of type {TPoster}.");
  36. }
  37. }
  38. /// <summary>
  39. /// A base class for all <see cref="IPosterEngine{TPostable}"/>. A concrete instance of this will be loaded by
  40. /// <see cref="PosterUtils.Process{T}(IDataModel{T})"/>; a new instance is guaranteed to be created each time that method is called.
  41. /// </summary>
  42. /// <typeparam name="TPostable"></typeparam>
  43. /// <typeparam name="TPoster"></typeparam>
  44. /// <typeparam name="TSettings"></typeparam>
  45. public abstract class PosterEngine<TPostable, TPoster, TSettings> : IPosterEngine<TPostable, TPoster, TSettings>
  46. where TPostable : Entity, IPostable, IRemotable, IPersistent, new()
  47. where TPoster : class, IPoster<TPostable, TSettings>
  48. where TSettings : PosterSettings, new()
  49. {
  50. protected TPoster Poster;
  51. /// <summary>
  52. /// A set of fragments that also need to be saved along with the <see cref="IPostable"/> entities.
  53. /// </summary>
  54. private Dictionary<Type, List<IPostableFragment>> Fragments = new Dictionary<Type, List<IPostableFragment>>();
  55. public PosterEngine()
  56. {
  57. Poster = CreatePoster();
  58. }
  59. private static readonly Type? PosterType = PosterEngineUtils.GetPoster(typeof(TPoster));
  60. protected virtual TPoster CreatePoster()
  61. {
  62. var poster = (Activator.CreateInstance(PosterType!) as TPoster)!;
  63. poster.Settings = GetSettings();
  64. return poster;
  65. }
  66. private TSettings _settings;
  67. protected TSettings GetSettings()
  68. {
  69. _settings ??= PosterUtils.LoadPosterSettings<TPostable, TSettings>();
  70. return _settings;
  71. }
  72. protected void SaveSettings(TSettings settings)
  73. {
  74. _settings = settings;
  75. PosterUtils.SavePosterSettings<TPostable, TSettings>(_settings);
  76. }
  77. /// <summary>
  78. /// Returns the <see cref="TSettings.Script"/>, if <see cref="TSettings.ScriptEnabled"/> is <see langword="true"/>;
  79. /// otherwise, returns <see langword="null"/>.
  80. /// </summary>
  81. protected string? GetScript()
  82. {
  83. var settings = GetSettings();
  84. return settings.ScriptEnabled ? settings.Script : null;
  85. }
  86. protected abstract bool DoProcess(IDataModel<TPostable> model);
  87. /// <summary>
  88. /// Process the <paramref name="model"/> before loading;
  89. /// </summary>
  90. /// <param name="model"></param>
  91. /// <returns><see langword="false"/> if the processing must be cancelled.</returns>
  92. public abstract bool BeforePost(IDataModel<TPostable> model);
  93. /// <summary>
  94. /// Prior to saving the <typeparamref name="TPostable"/> entities, make any necessary changes to those entities.
  95. /// This is only called if <see cref="Process(IDataModel{TPostable})"/> returned <see langword="true"/>.
  96. /// </summary>
  97. /// <param name="model"></param>
  98. public abstract void AfterPost(IDataModel<TPostable> model);
  99. private static void SetFailed(IList<TPostable> entities)
  100. {
  101. foreach (var post in entities)
  102. {
  103. post.PostedStatus = PostedStatus.PostFailed;
  104. post.PostedNote = "Post failed.";
  105. }
  106. new Client<TPostable>().Save(entities, "Post failed by user.");
  107. }
  108. protected void AddFragment(IPostableFragment fragment)
  109. {
  110. var type = fragment.GetType();
  111. if(!Fragments.TryGetValue(type, out var fragments))
  112. {
  113. fragments = new List<IPostableFragment>();
  114. Fragments[type] = fragments;
  115. }
  116. fragments.Add(fragment);
  117. }
  118. public bool Process(IDataModel<TPostable> model)
  119. {
  120. if (!BeforePost(model))
  121. {
  122. return false;
  123. }
  124. // Add posted flags; if the columns is null, then we don't need to worry, because it will be loaded.
  125. model.GetColumns<TPostable>()?.Add(x => x.PostedStatus)
  126. .Add(x => x.Posted)
  127. .Add(x => x.PostedNote);
  128. model.LoadModel();
  129. var data = model.GetTable<TPostable>();
  130. if (!data.Rows.Any())
  131. {
  132. throw new EmptyPostException();
  133. }
  134. if(data.Rows.Any(x => x.Get<TPostable, PostedStatus>(x => x.PostedStatus) == PostedStatus.Posted))
  135. {
  136. throw new RepostedException();
  137. }
  138. try
  139. {
  140. var success = DoProcess(model);
  141. if (success)
  142. {
  143. AfterPost(model);
  144. }
  145. var entities = data.ToObjects<TPostable>().ToList();
  146. if (success)
  147. {
  148. foreach (var post in entities)
  149. {
  150. post.Posted = DateTime.Now;
  151. post.PostedStatus = PostedStatus.Posted;
  152. post.PostedNote = "";
  153. }
  154. new Client<TPostable>().Save(entities, "Posted by user.");
  155. foreach(var (type, fragments) in Fragments)
  156. {
  157. Client.Create(type).Save(fragments.Cast<Entity>(), "");
  158. }
  159. }
  160. else
  161. {
  162. SetFailed(entities);
  163. }
  164. return success;
  165. }
  166. catch (PostCancelledException)
  167. {
  168. var entities = data.ToObjects<TPostable>().ToList();
  169. SetFailed(entities);
  170. throw;
  171. }
  172. catch(Exception e)
  173. {
  174. Logger.Send(LogType.Error, "", $"Post Failed: {CoreUtils.FormatException(e)}");
  175. var entities = data.ToObjects<TPostable>().ToList();
  176. SetFailed(entities);
  177. throw;
  178. }
  179. }
  180. }
  181. }