DbFactory.cs 18 KB

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