PosterUtils.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. using InABox.Configuration;
  2. using InABox.Core.Postable;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace InABox.Core
  11. {
  12. public interface IPosterDispatcher
  13. {
  14. public static IPosterDispatcher Default { get; } = new DefaultDispatcher();
  15. Task ExecuteAsync(Action action);
  16. Task<T> ExecuteAsync<T>(Func<T> func);
  17. void Execute(Action action) => ExecuteAsync(action).Wait();
  18. T Execute<T>(Func<T> func) => ExecuteAsync(func).Result;
  19. void Report(string report);
  20. private class DefaultDispatcher : IPosterDispatcher
  21. {
  22. public Task ExecuteAsync(Action action)
  23. {
  24. action();
  25. return Task.CompletedTask;
  26. }
  27. public Task<T> ExecuteAsync<T>(Func<T> func)
  28. {
  29. return Task.FromResult(func());
  30. }
  31. public void Report(string report)
  32. {
  33. }
  34. }
  35. }
  36. public static class PosterUtils
  37. {
  38. #region Postable Settings
  39. private static PostableSettings FixPostableSettings(Type TPostable, PostableSettings settings)
  40. {
  41. if (string.IsNullOrWhiteSpace(settings.PostableType))
  42. {
  43. settings.PostableType = TPostable.EntityName();
  44. }
  45. return settings;
  46. }
  47. private static PostableSettings LoadPostableSettings(Type T)
  48. {
  49. return FixPostableSettings(T, new GlobalConfiguration<PostableSettings>(T.Name).Load());
  50. }
  51. public static PostableSettings LoadPostableSettings<T>()
  52. where T : Entity, IPostable
  53. {
  54. return LoadPostableSettings(typeof(T));
  55. }
  56. public static void SavePostableSettings<T>(PostableSettings settings)
  57. where T : Entity, IPostable
  58. {
  59. new GlobalConfiguration<PostableSettings>(typeof(T).Name).Save(FixPostableSettings(typeof(T), settings));
  60. }
  61. #endregion
  62. #region Poster Settings
  63. private static TSettings FixPosterSettings<TPostable, TSettings>(TSettings settings)
  64. where TPostable : IPostable
  65. where TSettings : PosterSettings, new()
  66. {
  67. if (string.IsNullOrWhiteSpace(settings.PostableType))
  68. {
  69. settings.PostableType = typeof(TPostable).EntityName();
  70. }
  71. return settings;
  72. }
  73. private static MethodInfo _loadPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
  74. .Where(x => x.Name == nameof(LoadPosterSettings) && x.IsGenericMethod)
  75. .Single();
  76. private static MethodInfo _savePosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
  77. .Where(x => x.Name == nameof(SavePosterSettings) && x.IsGenericMethod)
  78. .Single();
  79. public static TSettings LoadPosterSettings<TPostable, TSettings>()
  80. where TPostable : IPostable
  81. where TSettings : PosterSettings, new()
  82. {
  83. return FixPosterSettings<TPostable, TSettings>(new GlobalConfiguration<TSettings>(typeof(TPostable).Name).Load());
  84. }
  85. public static PosterSettings LoadPosterSettings(Type TPostable, Type TSettings)
  86. {
  87. return (_loadPosterSettingsMethod.MakeGenericMethod(TPostable, TSettings).Invoke(null, Array.Empty<object>()) as PosterSettings)!;
  88. }
  89. public static void SavePosterSettings<TPostable, TSettings>(TSettings settings)
  90. where TPostable : IPostable
  91. where TSettings : PosterSettings, new()
  92. {
  93. new GlobalConfiguration<TSettings>(typeof(TPostable).Name).Save(FixPosterSettings<TPostable, TSettings>(settings));
  94. }
  95. public static void SavePosterSettings(Type TPostable, Type TSettings, PosterSettings settings)
  96. {
  97. _savePosterSettingsMethod.MakeGenericMethod(TPostable, TSettings).Invoke(null, new object[] { settings });
  98. }
  99. #endregion
  100. #region Global Poster Settings
  101. private static MethodInfo _loadGlobalPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
  102. .Where(x => x.Name == nameof(LoadGlobalPosterSettings) && x.IsGenericMethod)
  103. .Single();
  104. private static MethodInfo _saveGlobalPosterSettingsMethod = typeof(PosterUtils).GetMethods(BindingFlags.Static | BindingFlags.Public)
  105. .Where(x => x.Name == nameof(SaveGlobalPosterSettings) && x.IsGenericMethod)
  106. .Single();
  107. public static IGlobalPosterSettings LoadGlobalPosterSettings(Type TGlobalSettings)
  108. {
  109. return (_loadGlobalPosterSettingsMethod.MakeGenericMethod(TGlobalSettings).Invoke(null, Array.Empty<object>()) as IGlobalPosterSettings)!;
  110. }
  111. public static TGlobalSettings LoadGlobalPosterSettings<TGlobalSettings>()
  112. where TGlobalSettings : BaseObject, IGlobalPosterSettings, new()
  113. {
  114. return new GlobalConfiguration<TGlobalSettings>().Load();
  115. }
  116. public static void SaveGlobalPosterSettings<TGlobalSettings>(TGlobalSettings settings)
  117. where TGlobalSettings : BaseObject, IGlobalPosterSettings, new()
  118. {
  119. new GlobalConfiguration<TGlobalSettings>().Save(settings);
  120. }
  121. public static void SaveGlobalPosterSettings(Type TGlobalSettings, IGlobalPosterSettings settings)
  122. {
  123. _saveGlobalPosterSettingsMethod.MakeGenericMethod(TGlobalSettings).Invoke(null, new object[] { settings });
  124. }
  125. #endregion
  126. #region Poster Engines
  127. private class EngineType
  128. {
  129. public Type Engine { get; set; }
  130. public Type Entity { get; set; }
  131. public Type Poster { get; set; }
  132. }
  133. private static EngineType[]? _posterEngines;
  134. private static Type[]? _posters = null;
  135. public static Type[] GetPosters()
  136. {
  137. _posters ??= CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.HasInterface(typeof(IPoster<,>))).ToArray();
  138. return _posters;
  139. }
  140. public static Type GetPoster(Type TPoster)
  141. {
  142. return GetPosters().Where(x => TPoster.IsAssignableFrom(x)).FirstOrDefault()
  143. ?? throw new Exception($"No poster of type {TPoster}.");
  144. }
  145. public static Type? GetPoster(string posterType)
  146. {
  147. return GetPosters()?.FirstOrDefault(x => x.EntityName() == posterType)!;
  148. }
  149. private static EngineType[] GetPosterEngines()
  150. {
  151. _posterEngines ??= CoreUtils.TypeList(
  152. AppDomain.CurrentDomain.GetAssemblies(),
  153. x => x.IsClass
  154. && !x.IsAbstract
  155. // Allow type-specific and generic engines
  156. && x.GetTypeInfo().GenericTypeParameters.Length <= 1
  157. && x.HasInterface(typeof(IPosterEngine<,,>))
  158. ).Select(x =>
  159. {
  160. var poster = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[1];
  161. return new EngineType
  162. {
  163. Engine = x,
  164. Entity = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[0],
  165. Poster = poster.IsGenericType ? poster.GetGenericTypeDefinition() : poster
  166. };
  167. }).ToArray();
  168. return _posterEngines;
  169. }
  170. /// <summary>
  171. /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <paramref name="T"/>
  172. /// based on the current <see cref="PostableSettings"/> for <paramref name="T"/>.
  173. /// </summary>
  174. /// <returns></returns>
  175. public static Result<Type, Exception> GetEngine(Type T)
  176. {
  177. var settings = LoadPostableSettings(T);
  178. if (string.IsNullOrWhiteSpace(settings.PosterType))
  179. {
  180. return Result.Error<Exception>(new MissingSettingsException(T));
  181. }
  182. var poster = GetPoster(settings.PosterType);
  183. if(poster is null)
  184. {
  185. return Result.Error(new Exception($"No poster of type {settings.PosterType}."));
  186. }
  187. var engines = GetPosterEngines().Where(x =>
  188. {
  189. return x.Poster.IsInterface ? poster.HasInterface(x.Poster) : poster.IsSubclassOfRawGeneric(x.Poster);
  190. }).ToList();
  191. if (!engines.Any())
  192. {
  193. return Result.Error(new Exception("No poster for the given settings"));
  194. }
  195. else
  196. {
  197. var engineType = engines.Count == 1 ? engines[0] : engines.Single(x => x.Entity == T);
  198. if (engineType.Engine.IsGenericType)
  199. {
  200. // If the engine is generic, we need to specify for the entity type.
  201. return Result.Ok(engineType.Engine.MakeGenericType(T));
  202. }
  203. else
  204. {
  205. // If the engine has already been specified for a given entity type, we just return the engine type straight up.
  206. return Result.Ok(engineType.Engine);
  207. }
  208. }
  209. }
  210. /// <summary>
  211. /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <typeparamref name="T"/>
  212. /// based on the current <see cref="PostableSettings"/> for <typeparamref name="T"/>.
  213. /// </summary>
  214. /// <typeparam name="T"></typeparam>
  215. /// <returns></returns>
  216. public static Type GetEngine<T>()
  217. where T : Entity, IPostable, IRemotable, IPersistent, new()
  218. {
  219. if (GetEngine(typeof(T)).Get(out var engineType, out var e))
  220. {
  221. return engineType;
  222. }
  223. else
  224. {
  225. throw e;
  226. }
  227. }
  228. public static IPosterEngine<T> CreateEngine<T>()
  229. where T : Entity, IPostable, IRemotable, IPersistent, new()
  230. {
  231. var engineType = GetEngine<T>();
  232. return (Activator.CreateInstance(engineType) as IPosterEngine<T>)!;
  233. }
  234. #endregion
  235. #region Auto-Refresh
  236. /// <summary>
  237. /// Check if <paramref name="item"/> needs to be reposted; if it does, <see cref="IPostable.PostedStatus"/> will be set to
  238. /// <see cref="PostedStatus.RequiresRepost"/> once this function is finished.
  239. /// </summary>
  240. /// <remarks>
  241. /// This will only do something if the currently set poster for this type has the <see cref="IAutoRefreshPoster{TEntity}"/> interface.
  242. /// </remarks>
  243. /// <typeparam name="T"></typeparam>
  244. /// <returns><see langword="true"/> if the item's status has been updated and needs to be reposted.</returns>
  245. public static bool CheckPostedStatus<T>(PostableSettings settings, T item)
  246. where T : BaseObject
  247. {
  248. if (!(item is IPostable postable))
  249. {
  250. return false;
  251. }
  252. if (postable.PostedStatus != PostedStatus.Posted || item?.HasOriginalValue(nameof(IPostable.PostedStatus)) == true)
  253. {
  254. return false;
  255. }
  256. settings = FixPostableSettings(typeof(T), settings);
  257. if (settings.PosterType.IsNullOrWhiteSpace())
  258. {
  259. return false;
  260. }
  261. var poster = GetPoster(settings.PosterType);
  262. if (poster is null)
  263. {
  264. return false;
  265. }
  266. var iautoRefresh = poster.GetInterfaceDefinition(typeof(IAutoRefreshPoster<,>));
  267. if(iautoRefresh != null)
  268. {
  269. var autoRefresher = Activator.CreateInstance(iautoRefresh.GenericTypeArguments[1]) as IAutoRefresher<T>;
  270. if (autoRefresher != null && autoRefresher.ShouldRepost(item!))
  271. {
  272. postable.PostedStatus = PostedStatus.RequiresRepost;
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. #endregion
  279. #region Process
  280. /// <summary>
  281. /// Process <paramref name="model"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>
  282. /// for <typeparamref name="T"/>.
  283. /// </summary>
  284. /// <typeparam name="T">The type of <paramref name="model"/> that needs to be processed.</typeparam>
  285. /// <param name="model"></param>
  286. /// <exception cref="EmptyPostException">If there are no items to post. In this case, nothing happens.</exception>
  287. /// <exception cref="RepostedException">If any of the <typeparamref name="T"/> have already been processed. In this case, nothing happens.</exception>
  288. /// <exception cref="MissingSettingsException">If the <see cref="PostableSettings"/> for <typeparamref name="T"/> do not exist.</exception>
  289. /// <exception cref="PostCancelledException">If the post has been cancelled by the user.</exception>
  290. /// <returns><see langword="null"/> if post was unsuccessful.</returns>
  291. ///
  292. public static IPostResult<T>? Process<T>(IDataModel<T> model, Action<IPosterEngine<T>>? beforeProcess, Action<IPosterEngine<T>>? afterProcess)
  293. where T : Entity, IPostable, IRemotable, IPersistent, new()
  294. {
  295. var engine = CreateEngine<T>();
  296. beforeProcess?.Invoke(engine);
  297. IPostResult<T>? result;
  298. try
  299. {
  300. result = engine.Process(model);
  301. }
  302. finally
  303. {
  304. afterProcess?.Invoke(engine);
  305. }
  306. return result;
  307. }
  308. /// <summary>
  309. /// Import <typeparamref name="T"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>.
  310. /// </summary>
  311. /// <typeparam name="T"></typeparam>
  312. /// <returns><see langword="null"/> if post was unsuccessful.</returns>
  313. /// <exception cref="InvalidPullerException">If the engine is not a <see cref="IPullerEngine{TPostable,TPoster}"/></exception>
  314. public static IPullResult<T>? Pull<T>()
  315. where T : Entity, IPostable, IRemotable, IPersistent, new()
  316. {
  317. var engine = CreateEngine<T>();
  318. if(engine is IPullerEngine<T> puller)
  319. {
  320. return puller.Pull();
  321. }
  322. else
  323. {
  324. var intDef = engine.GetType().GetInterfaceDefinition(typeof(IPosterEngine<,,>));
  325. if(intDef != null)
  326. {
  327. throw new InvalidPullerException(typeof(T), intDef.GenericTypeArguments[1]);
  328. }
  329. else
  330. {
  331. throw new InvalidPullerException(typeof(T));
  332. }
  333. }
  334. }
  335. #endregion
  336. }
  337. }