PosterUtils.cs 13 KB

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