PosterUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. // Allow type-specific and generic engines
  131. && x.GetTypeInfo().GenericTypeParameters.Length <= 1
  132. && x.HasInterface(typeof(IPosterEngine<,,>))
  133. ).Select(x =>
  134. {
  135. var poster = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[1];
  136. return new EngineType
  137. {
  138. Engine = x,
  139. Entity = x.GetInterfaceDefinition(typeof(IPosterEngine<,,>))!.GenericTypeArguments[0],
  140. Poster = poster.IsGenericType ? poster.GetGenericTypeDefinition() : poster
  141. };
  142. }).ToArray();
  143. return _posterEngines;
  144. }
  145. /// <summary>
  146. /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <paramref name="T"/>
  147. /// based on the current <see cref="PostableSettings"/> for <paramref name="T"/>.
  148. /// </summary>
  149. /// <returns></returns>
  150. public static Result<Type, Exception> GetEngine(Type T)
  151. {
  152. var settings = LoadPostableSettings(T);
  153. if (string.IsNullOrWhiteSpace(settings.PosterType))
  154. {
  155. return Result.Error<Exception>(new MissingSettingsException(T));
  156. }
  157. var poster = GetPoster(settings.PosterType);
  158. if(poster is null)
  159. {
  160. return Result.Error(new Exception($"No poster of type {settings.PosterType}."));
  161. }
  162. var engines = GetPosterEngines().Where(x =>
  163. {
  164. return x.Poster.IsInterface ? poster.HasInterface(x.Poster) : poster.IsSubclassOfRawGeneric(x.Poster);
  165. }).ToList();
  166. if (!engines.Any())
  167. {
  168. return Result.Error(new Exception("No poster for the given settings"));
  169. }
  170. else
  171. {
  172. var engineType = engines.Count == 1 ? engines[0] : engines.Single(x => x.Entity == T);
  173. if (engineType.Engine.IsGenericType)
  174. {
  175. // If the engine is generic, we need to specify for the entity type.
  176. return Result.Ok(engineType.Engine.MakeGenericType(T));
  177. }
  178. else
  179. {
  180. // If the engine has already been specified for a given entity type, we just return the engine type straight up.
  181. return Result.Ok(engineType.Engine);
  182. }
  183. }
  184. }
  185. /// <summary>
  186. /// Get the <see cref="IPosterEngine{TPostable,TPoster,TSettings}"/> for <typeparamref name="T"/>
  187. /// based on the current <see cref="PostableSettings"/> for <typeparamref name="T"/>.
  188. /// </summary>
  189. /// <typeparam name="T"></typeparam>
  190. /// <returns></returns>
  191. public static Type GetEngine<T>()
  192. where T : Entity, IPostable, IRemotable, IPersistent, new()
  193. {
  194. if (GetEngine(typeof(T)).Get(out var engineType, out var e))
  195. {
  196. return engineType;
  197. }
  198. else
  199. {
  200. throw e;
  201. }
  202. }
  203. public static IPosterEngine<T> CreateEngine<T>()
  204. where T : Entity, IPostable, IRemotable, IPersistent, new()
  205. {
  206. var engine = GetEngine<T>();
  207. return (Activator.CreateInstance(engine) as IPosterEngine<T>)!;
  208. }
  209. #endregion
  210. #region Auto-Refresh
  211. /// <summary>
  212. /// Check if <paramref name="item"/> needs to be reposted; if it does, <see cref="IPostable.PostedStatus"/> will be set to
  213. /// <see cref="PostedStatus.RequiresRepost"/> once this function is finished.
  214. /// </summary>
  215. /// <remarks>
  216. /// This will only do something if the currently set poster for this type has the <see cref="IAutoRefreshPoster{TEntity}"/> interface.
  217. /// </remarks>
  218. /// <typeparam name="T"></typeparam>
  219. /// <returns><see langword="true"/> if the item's status has been updated and needs to be reposted.</returns>
  220. public static bool CheckPostedStatus<T>(PostableSettings settings, T item)
  221. where T : BaseObject
  222. {
  223. if (!(item is IPostable postable))
  224. {
  225. return false;
  226. }
  227. if (postable.PostedStatus != PostedStatus.Posted || item?.HasOriginalValue(nameof(IPostable.PostedStatus)) == true)
  228. {
  229. return false;
  230. }
  231. settings = FixPostableSettings(typeof(T), settings);
  232. if (settings.PosterType.IsNullOrWhiteSpace())
  233. {
  234. return false;
  235. }
  236. var poster = GetPoster(settings.PosterType);
  237. if (poster is null)
  238. {
  239. return false;
  240. }
  241. var iautoRefresh = poster.GetInterfaceDefinition(typeof(IAutoRefreshPoster<,>));
  242. if(iautoRefresh != null)
  243. {
  244. var autoRefresher = Activator.CreateInstance(iautoRefresh.GenericTypeArguments[1]) as IAutoRefresher<T>;
  245. if (autoRefresher != null && autoRefresher.ShouldRepost(item!))
  246. {
  247. postable.PostedStatus = PostedStatus.RequiresRepost;
  248. return true;
  249. }
  250. }
  251. return false;
  252. }
  253. #endregion
  254. #region Process
  255. /// <summary>
  256. /// Process <paramref name="model"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>
  257. /// for <typeparamref name="T"/>.
  258. /// </summary>
  259. /// <typeparam name="T">The type of <paramref name="model"/> that needs to be processed.</typeparam>
  260. /// <param name="model"></param>
  261. /// <exception cref="EmptyPostException">If there are no items to post. In this case, nothing happens.</exception>
  262. /// <exception cref="RepostedException">If any of the <typeparamref name="T"/> have already been processed. In this case, nothing happens.</exception>
  263. /// <exception cref="MissingSettingsException">If the <see cref="PostableSettings"/> for <typeparamref name="T"/> do not exist.</exception>
  264. /// <exception cref="PostCancelledException">If the post has been cancelled by the user.</exception>
  265. /// <returns><see langword="null"/> if post was unsuccessful.</returns>
  266. ///
  267. public static IPostResult<T>? Process<T>(IDataModel<T> model)
  268. where T : Entity, IPostable, IRemotable, IPersistent, new()
  269. {
  270. return CreateEngine<T>().Process(model);
  271. }
  272. /// <summary>
  273. /// Import <typeparamref name="T"/> with the currently set <see cref="IPosterEngine{TPostable, TPoster, TSettings}"/>.
  274. /// </summary>
  275. /// <typeparam name="T"></typeparam>
  276. /// <returns><see langword="null"/> if post was unsuccessful.</returns>
  277. /// <exception cref="InvalidPullerException">If the engine is not a <see cref="IPullerEngine{TPostable,TPoster}"/></exception>
  278. public static IPullResult<T>? Pull<T>()
  279. where T : Entity, IPostable, IRemotable, IPersistent, new()
  280. {
  281. var engine = CreateEngine<T>();
  282. if(engine is IPullerEngine<T> puller)
  283. {
  284. return puller.Pull();
  285. }
  286. else
  287. {
  288. var intDef = engine.GetType().GetInterfaceDefinition(typeof(IPosterEngine<,,>));
  289. if(intDef != null)
  290. {
  291. throw new InvalidPullerException(typeof(T), intDef.GenericTypeArguments[1]);
  292. }
  293. else
  294. {
  295. throw new InvalidPullerException(typeof(T));
  296. }
  297. }
  298. }
  299. #endregion
  300. }
  301. }