DbFactory.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. using System.Reflection;
  2. using FluentResults;
  3. using InABox.Clients;
  4. using InABox.Configuration;
  5. using InABox.Core;
  6. using InABox.Mail;
  7. using InABox.Scripting;
  8. namespace InABox.Database;
  9. public class DatabaseMetadata : BaseObject, IGlobalConfigurationSettings
  10. {
  11. public Guid DatabaseID { get; set; } = Guid.NewGuid();
  12. }
  13. public class DbLockedException : Exception
  14. {
  15. public DbLockedException(): base("Database is read-only due to PRS license expiry.") { }
  16. }
  17. public static class DbFactory
  18. {
  19. public static Dictionary<string, ScriptDocument> LoadedScripts = new();
  20. private static DatabaseMetadata MetaData { get; set; } = new();
  21. public static Guid ID
  22. {
  23. get => MetaData.DatabaseID;
  24. set
  25. {
  26. MetaData.DatabaseID = value;
  27. SaveMetadata();
  28. }
  29. }
  30. private static IProviderFactory? _providerFactory;
  31. public static IProviderFactory ProviderFactory
  32. {
  33. get => _providerFactory ?? throw new Exception("Provider is not set");
  34. set => _providerFactory = value;
  35. }
  36. public static bool IsProviderSet => _providerFactory is not null;
  37. public static string? ColorScheme { get; set; }
  38. public static byte[]? Logo { get; set; }
  39. public static Type DefaultStore { get; set; } = typeof(Store<>);
  40. // See notes in Request.DatabaseInfo class
  41. // Once RPC transport is stable, these settings need
  42. // to be removed
  43. public static int RestPort { get; set; }
  44. public static int RPCPort { get; set; }
  45. /// <summary>
  46. /// Return every <see cref="IPersistent"/> entity in <see cref="CoreUtils.Entities"/>.
  47. /// </summary>
  48. public static IEnumerable<Type> Entities => CoreUtils.Entities.Where(x => x.HasInterface<IPersistent>());
  49. public static Type[] Stores
  50. {
  51. get => stores;
  52. set => SetStoreTypes(value);
  53. }
  54. public static ICoreMailer? Mailer { get; set; }
  55. public static DateTime Expiry { get; set; }
  56. public static IProvider NewProvider(Logger logger) => ProviderFactory.NewProvider(logger);
  57. public static void Start(Type[]? types = null)
  58. {
  59. CoreUtils.CheckLicensing();
  60. if(types is not null)
  61. {
  62. ProviderFactory.Types = types.Concat(CoreUtils.IterateTypes(typeof(CoreUtils).Assembly).Where(x => !x.IsAbstract))
  63. .Where(x => x.IsClass && !x.IsGenericType && x.IsSubclassOf(typeof(Entity)))
  64. .ToArray();
  65. }
  66. else
  67. {
  68. ProviderFactory.Types = Entities.Where(x =>
  69. x.IsClass
  70. && !x.IsGenericType
  71. && x.IsSubclassOf(typeof(Entity))
  72. ).ToArray();
  73. }
  74. // Start the provider
  75. ProviderFactory.Start();
  76. CheckMetadata();
  77. if (!DataUpdater.MigrateDatabase())
  78. {
  79. throw new Exception("Database migration failed. Aborting startup");
  80. }
  81. AssertLicense();
  82. BeginLicenseCheckTimer();
  83. InitStores();
  84. LoadScripts();
  85. }
  86. public static DatabaseVersion GetVersionSettings()
  87. {
  88. var provider = ProviderFactory.NewProvider(Logger.New());
  89. var result = provider.Query(new Filter<GlobalSettings>(x => x.Section).IsEqualTo(nameof(DatabaseVersion)))
  90. .Rows.FirstOrDefault()?.ToObject<GlobalSettings>();
  91. if(result != null)
  92. {
  93. return Serialization.Deserialize<DatabaseVersion>(result.Contents);
  94. }
  95. var settings = new GlobalSettings() { Section = nameof(DatabaseVersion), Key = "" };
  96. var dbVersion = new DatabaseVersion() { Version = "6.30b" };
  97. settings.Contents = Serialization.Serialize(dbVersion);
  98. DbFactory.NewProvider(Logger.Main).Save(settings);
  99. return dbVersion;
  100. }
  101. public static VersionNumber GetDatabaseVersion()
  102. {
  103. var dbVersion = GetVersionSettings();
  104. return VersionNumber.Parse(dbVersion.Version);
  105. }
  106. private static VersionNumber? _versionNumber;
  107. public static VersionNumber VersionNumber
  108. {
  109. get
  110. {
  111. _versionNumber ??= GetDatabaseVersion();
  112. return _versionNumber;
  113. }
  114. }
  115. #region MetaData
  116. private static void SaveMetadata()
  117. {
  118. var settings = new GlobalSettings
  119. {
  120. Section = nameof(DatabaseMetadata),
  121. Key = "",
  122. Contents = Serialization.Serialize(MetaData)
  123. };
  124. ProviderFactory.NewProvider(Logger.Main).Save(settings);
  125. }
  126. private static void CheckMetadata()
  127. {
  128. var result = ProviderFactory.NewProvider(Logger.Main).Query(new Filter<GlobalSettings>(x => x.Section).IsEqualTo(nameof(DatabaseMetadata)))
  129. .Rows.FirstOrDefault()?.ToObject<GlobalSettings>();
  130. var data = result is not null ? Serialization.Deserialize<DatabaseMetadata>(result.Contents) : null;
  131. if (data is null)
  132. {
  133. MetaData = new DatabaseMetadata();
  134. SaveMetadata();
  135. }
  136. else
  137. {
  138. MetaData = data;
  139. }
  140. }
  141. #endregion
  142. #region License
  143. private enum LicenseValidation
  144. {
  145. Valid,
  146. Missing,
  147. Expired,
  148. Corrupt,
  149. Tampered
  150. }
  151. private static LicenseValidation CheckLicenseValidity(out DateTime expiry)
  152. {
  153. var provider = ProviderFactory.NewProvider(Logger.New());
  154. expiry = DateTime.MinValue;
  155. var license = provider.Load<License>().FirstOrDefault();
  156. if (license is null)
  157. return LicenseValidation.Missing;
  158. if (!LicenseUtils.TryDecryptLicense(license.Data, out var licenseData, out var error))
  159. return LicenseValidation.Corrupt;
  160. if (!LicenseUtils.ValidateMacAddresses(licenseData.Addresses))
  161. return LicenseValidation.Tampered;
  162. var userTrackingItems = provider.Query(
  163. new Filter<UserTracking>(x => x.ID).InList(licenseData.UserTrackingItems),
  164. Columns.None<UserTracking>().Add(x => x.ID)
  165. , log: false
  166. ).Rows
  167. .Select(r => r.Get<UserTracking, Guid>(c => c.ID))
  168. .ToArray();
  169. foreach(var item in licenseData.UserTrackingItems)
  170. {
  171. if (!userTrackingItems.Contains(item))
  172. return LicenseValidation.Tampered;
  173. }
  174. expiry = licenseData.Expiry;
  175. if (licenseData.Expiry < DateTime.Now)
  176. return LicenseValidation.Expired;
  177. return LicenseValidation.Valid;
  178. }
  179. private static int _expiredLicenseCounter = 0;
  180. private static TimeSpan LicenseCheckInterval = TimeSpan.FromMinutes(10);
  181. private static bool _readOnly;
  182. public static bool IsReadOnly { get => _readOnly; }
  183. private static System.Timers.Timer LicenseTimer = new System.Timers.Timer(LicenseCheckInterval.TotalMilliseconds) { AutoReset = true };
  184. private static void LogRenew(string message)
  185. {
  186. LogImportant($"{message} Please renew your license before then, or your database will go into read-only mode; it will be locked for saving anything until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  187. }
  188. public static void LogReadOnly()
  189. {
  190. LogImportant($"Your database is in read-only mode; please renew your license to enable database updates.");
  191. }
  192. private static void LogLicenseExpiry(DateTime expiry)
  193. {
  194. if (expiry.Date == DateTime.Today)
  195. {
  196. LogRenew($"Your database license is expiring today at {expiry.TimeOfDay:HH:mm}!");
  197. return;
  198. }
  199. var diffInDays = (expiry - DateTime.Now).TotalDays;
  200. if(diffInDays < 1)
  201. {
  202. LogRenew($"Your database license will expire in less than a day, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  203. }
  204. else if(diffInDays < 3 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 1)
  205. {
  206. LogRenew($"Your database license will expire in less than three days, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  207. _expiredLicenseCounter = 0;
  208. }
  209. else if(diffInDays < 7 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 2)
  210. {
  211. LogRenew($"Your database license will expire in less than a week, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  212. _expiredLicenseCounter = 0;
  213. }
  214. ++_expiredLicenseCounter;
  215. }
  216. private static void BeginReadOnly()
  217. {
  218. if (!IsReadOnly)
  219. {
  220. LogImportant(
  221. "Your database is now in read-only mode, since your license is invalid; you will be unable to save any records to the database until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  222. _readOnly = true;
  223. }
  224. }
  225. private static void EndReadOnly()
  226. {
  227. if (IsReadOnly)
  228. {
  229. LogImportant("Valid license found; the database is no longer read-only.");
  230. _readOnly = false;
  231. }
  232. }
  233. private static void BeginLicenseCheckTimer()
  234. {
  235. LicenseTimer.Elapsed += LicenseTimer_Elapsed;
  236. LicenseTimer.Start();
  237. }
  238. private static void LicenseTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
  239. {
  240. AssertLicense();
  241. }
  242. public static void AssertLicense()
  243. {
  244. if (String.Equals(CoreUtils.GetVersion(),"???"))
  245. return;
  246. var result = CheckLicenseValidity(out DateTime expiry);
  247. switch (result)
  248. {
  249. case LicenseValidation.Valid:
  250. LogLicenseExpiry(expiry);
  251. EndReadOnly();
  252. break;
  253. case LicenseValidation.Missing:
  254. LogImportant("Database is unlicensed!");
  255. BeginReadOnly();
  256. break;
  257. case LicenseValidation.Expired:
  258. LogImportant("Database license has expired!");
  259. BeginReadOnly();
  260. break;
  261. case LicenseValidation.Corrupt:
  262. LogImportant("Database license is corrupt - you will need to renew your license.");
  263. BeginReadOnly();
  264. break;
  265. case LicenseValidation.Tampered:
  266. LogImportant("Database license has been tampered with - you will need to renew your license.");
  267. BeginReadOnly();
  268. break;
  269. }
  270. }
  271. #endregion
  272. #region Logging
  273. private static void LogInfo(string message)
  274. {
  275. Logger.Send(LogType.Information, "", message);
  276. }
  277. private static void LogImportant(string message)
  278. {
  279. Logger.Send(LogType.Important, "", message);
  280. }
  281. private static void LogError(string message)
  282. {
  283. Logger.Send(LogType.Error, "", message);
  284. }
  285. #endregion
  286. public static void InitStores()
  287. {
  288. foreach (var storetype in stores)
  289. {
  290. var store = (Activator.CreateInstance(storetype) as IStore)!;
  291. store.Provider = ProviderFactory.NewProvider(Logger.Main);
  292. store.Logger = Logger.Main;
  293. store.Init();
  294. }
  295. }
  296. public static IStore FindStore(Type type, Guid userguid, string userid, Platform platform, string version, Logger logger)
  297. {
  298. var anyType = typeof(Store<>).MakeGenericType(type);
  299. Type? subType = Stores.Where(myType => myType.IsSubclassOf(anyType)).FirstOrDefault();
  300. var store = (Activator.CreateInstance(subType ?? DefaultStore.MakeGenericType(type)) as IStore)!;
  301. store.Provider = ProviderFactory.NewProvider(logger);
  302. store.UserGuid = userguid;
  303. store.UserID = userid;
  304. store.Platform = platform;
  305. store.Version = version;
  306. store.Logger = logger;
  307. return store;
  308. }
  309. public static IStore<TEntity> FindStore<TEntity>(Guid userguid, string userid, Platform platform, string version, Logger logger)
  310. where TEntity : Entity, new()
  311. {
  312. return (FindStore(typeof(TEntity), userguid, userid, platform, version, logger) as IStore<TEntity>)!;
  313. }
  314. private static CoreTable DoQueryMultipleQuery<TEntity>(
  315. IQueryDef query,
  316. Guid userguid, string userid, Platform platform, string version, Logger logger)
  317. where TEntity : Entity, new()
  318. {
  319. var store = FindStore<TEntity>(userguid, userid, platform, version, logger);
  320. return store.Query(query.Filter as Filter<TEntity>, query.Columns as Columns<TEntity>, query.SortOrder as SortOrder<TEntity>);
  321. }
  322. public static Dictionary<string, CoreTable> QueryMultiple(
  323. Dictionary<string, IQueryDef> queries,
  324. Guid userguid, string userid, Platform platform, string version, Logger logger)
  325. {
  326. var result = new Dictionary<string, CoreTable>();
  327. var queryMethod = typeof(DbFactory).GetMethod(nameof(DoQueryMultipleQuery), BindingFlags.NonPublic | BindingFlags.Static)!;
  328. var tasks = new List<Task>();
  329. foreach (var item in queries)
  330. tasks.Add(Task.Run(() =>
  331. {
  332. result[item.Key] = (queryMethod.MakeGenericMethod(item.Value.Type).Invoke(ProviderFactory, new object[]
  333. {
  334. item.Value,
  335. userguid, userid, platform, version, logger
  336. }) as CoreTable)!;
  337. }));
  338. Task.WaitAll(tasks.ToArray());
  339. return result;
  340. }
  341. #region Supported Types
  342. private class ModuleConfiguration : Dictionary<string, bool>, ILocalConfigurationSettings
  343. {
  344. }
  345. private static Type[]? _dbtypes;
  346. public static IEnumerable<string> SupportedTypes()
  347. {
  348. _dbtypes ??= LoadSupportedTypes();
  349. return _dbtypes.Select(x => x.EntityName().Replace(".", "_"));
  350. }
  351. private static Type[] LoadSupportedTypes()
  352. {
  353. var result = new List<Type>();
  354. var path = ProviderFactory.URL.ToLower();
  355. var config = new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Load();
  356. var bChanged = false;
  357. foreach (var type in Entities)
  358. {
  359. var key = type.EntityName();
  360. if (config.TryGetValue(key, out bool value))
  361. {
  362. if (value)
  363. //Logger.Send(LogType.Information, "", String.Format("{0} is enabled", key));
  364. result.Add(type);
  365. else
  366. Logger.Send(LogType.Information, "", string.Format("Entity [{0}] is disabled", key));
  367. }
  368. else
  369. {
  370. //Logger.Send(LogType.Information, "", String.Format("{0} does not exist - enabling", key));
  371. config[key] = true;
  372. result.Add(type);
  373. bChanged = true;
  374. }
  375. }
  376. if (bChanged)
  377. new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Save(config);
  378. return result.ToArray();
  379. }
  380. public static bool IsSupported<T>() where T : Entity
  381. {
  382. _dbtypes ??= LoadSupportedTypes();
  383. return _dbtypes.Contains(typeof(T));
  384. }
  385. #endregion
  386. //public static void OpenSession(bool write)
  387. //{
  388. // Provider.OpenSession(write);
  389. //}
  390. //public static void CloseSession()
  391. //{
  392. // Provider.CloseSession();
  393. //}
  394. #region Private Methods
  395. public static void LoadScripts()
  396. {
  397. Logger.Send(LogType.Information, "", "Loading Script Cache...");
  398. LoadedScripts.Clear();
  399. var scripts = ProviderFactory.NewProvider(Logger.Main).Load(
  400. new Filter<Script>
  401. (x => x.ScriptType).IsEqualTo(ScriptType.BeforeQuery)
  402. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterQuery)
  403. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeSave)
  404. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterSave)
  405. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeDelete)
  406. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterDelete)
  407. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterLoad)
  408. );
  409. foreach (var script in scripts)
  410. {
  411. var key = string.Format("{0} {1}", script.Section, script.ScriptType.ToString());
  412. var doc = new ScriptDocument(script.Code);
  413. if (doc.Compile())
  414. {
  415. Logger.Send(LogType.Information, "",
  416. string.Format("- {0}.{1} Compiled Successfully", script.Section, script.ScriptType.ToString()));
  417. LoadedScripts[key] = doc;
  418. }
  419. else
  420. {
  421. Logger.Send(LogType.Error, "",
  422. string.Format("- {0}.{1} Compile Exception:\n{2}", script.Section, script.ScriptType.ToString(), doc.Result));
  423. }
  424. }
  425. Logger.Send(LogType.Information, "", "Loading Script Cache Complete");
  426. }
  427. //private static Type[] entities = null;
  428. //private static void SetEntityTypes(Type[] types)
  429. //{
  430. // foreach (Type type in types)
  431. // {
  432. // if (!type.IsSubclassOf(typeof(Entity)))
  433. // throw new Exception(String.Format("{0} is not a valid entity", type.Name));
  434. // }
  435. // entities = types;
  436. //}
  437. private static Type[] stores = { };
  438. private static void SetStoreTypes(Type[] types)
  439. {
  440. types = types.Where(
  441. myType => myType.IsClass
  442. && !myType.IsAbstract
  443. && !myType.IsGenericType).ToArray();
  444. foreach (var type in types)
  445. if (!type.GetInterfaces().Contains(typeof(IStore)))
  446. throw new Exception(string.Format("{0} is not a valid store", type.Name));
  447. stores = types;
  448. }
  449. #endregion
  450. }