DbFactory.cs 17 KB

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