DbFactory.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using System.Composition;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using InABox.Clients;
  6. using InABox.Configuration;
  7. using InABox.Core;
  8. using InABox.Scripting;
  9. using Microsoft.CodeAnalysis.CSharp;
  10. namespace InABox.Database
  11. {
  12. public static class DbFactory
  13. {
  14. public static Dictionary<string, ScriptDocument> LoadedScripts = new();
  15. private static string _deviceid = "";
  16. private static IProvider? _provider;
  17. public static IProvider Provider
  18. {
  19. get => _provider ?? throw new Exception("Provider is not set");
  20. set => _provider = value;
  21. }
  22. public static string? ColorScheme { get; set; }
  23. public static byte[]? Logo { get; set; }
  24. //public static Type[] Entities { get { return entities; } set { SetEntityTypes(value); } }
  25. public static IEnumerable<Type> Entities
  26. {
  27. get { return CoreUtils.Entities.Where(x => x.GetInterfaces().Contains(typeof(IPersistent))); }
  28. }
  29. public static Type[] Stores
  30. {
  31. get => stores;
  32. set => SetStoreTypes(value);
  33. }
  34. public static DateTime Expiry { get; set; }
  35. public static void Start(string deviceid)
  36. {
  37. CoreUtils.CheckLicensing();
  38. _deviceid = deviceid;
  39. var status = ValidateSchema();
  40. if (status.Equals(SchemaStatus.New))
  41. try
  42. {
  43. Provider.CreateSchema(ConsolidatedObjectModel().ToArray());
  44. SaveSchema();
  45. }
  46. catch (Exception err)
  47. {
  48. throw new Exception(string.Format("Unable to Create Schema\n\n{0}", err.Message));
  49. }
  50. else if (status.Equals(SchemaStatus.Changed))
  51. try
  52. {
  53. Provider.UpgradeSchema(ConsolidatedObjectModel().ToArray());
  54. SaveSchema();
  55. }
  56. catch (Exception err)
  57. {
  58. throw new Exception(string.Format("Unable to Update Schema\n\n{0}", err.Message));
  59. }
  60. // Start the provider
  61. Provider.Types = ConsolidatedObjectModel();
  62. Provider.OnLog += LogMessage;
  63. Provider.Start();
  64. if (!DataUpdater.MigrateDatabase())
  65. {
  66. throw new Exception("Database migration failed. Aborting startup");
  67. }
  68. //Load up your custom properties here!
  69. // Can't use clients (b/c were inside the database layer already
  70. // but we can simply access the store directly :-)
  71. //CustomProperty[] props = FindStore<CustomProperty>("", "", "", "").Load(new Filter<CustomProperty>(x=>x.ID).IsNotEqualTo(Guid.Empty),null);
  72. var props = Provider.Query<CustomProperty>().Rows.Select(x => x.ToObject<CustomProperty>()).ToArray();
  73. DatabaseSchema.Load(props);
  74. AssertLicense();
  75. BeginLicenseCheckTimer();
  76. InitStores();
  77. LoadScripts();
  78. }
  79. #region License
  80. private enum LicenseValidation
  81. {
  82. Valid,
  83. Missing,
  84. Expired,
  85. Corrupt,
  86. Tampered
  87. }
  88. private static LicenseValidation CheckLicenseValidity(out License? license, out LicenseData? licenseData)
  89. {
  90. license = Provider.Load<License>().FirstOrDefault();
  91. if (license is null)
  92. {
  93. licenseData = null;
  94. return LicenseValidation.Missing;
  95. }
  96. if (!LicenseUtils.TryDecryptLicense(license.Data, out licenseData, out var error))
  97. return LicenseValidation.Corrupt;
  98. if (licenseData.Expiry < DateTime.Now)
  99. return LicenseValidation.Expired;
  100. var userTrackingItems = Provider.Query(
  101. new Filter<UserTracking>(x => x.ID).InList(licenseData.UserTrackingItems),
  102. new Columns<UserTracking>(x => x.ID), log: false).Rows.Select(x => x.Get<UserTracking, Guid>(x => x.ID));
  103. foreach(var item in licenseData.UserTrackingItems)
  104. {
  105. if (!userTrackingItems.Contains(item))
  106. {
  107. return LicenseValidation.Tampered;
  108. }
  109. }
  110. return LicenseValidation.Valid;
  111. }
  112. private static int _expiredLicenseCounter = 0;
  113. private static TimeSpan LicenseCheckInterval = TimeSpan.FromMinutes(10);
  114. private static bool _readOnly;
  115. public static bool IsReadOnly { get => _readOnly; }
  116. private static System.Timers.Timer LicenseTimer = new System.Timers.Timer(LicenseCheckInterval.TotalMilliseconds) { AutoReset = true };
  117. private static void LogRenew(string message)
  118. {
  119. 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://prs-software.com.au/wiki/index.php/License_Renewal.");
  120. }
  121. private static void LogLicenseExpiry(DateTime expiry)
  122. {
  123. if (expiry.Date == DateTime.Today)
  124. {
  125. LogRenew($"Your database license is expiring today at {expiry.TimeOfDay:HH:mm}!");
  126. return;
  127. }
  128. var diffInDays = (expiry - DateTime.Now).TotalDays;
  129. if(diffInDays < 1)
  130. {
  131. LogRenew($"Your database license will expire in less than a day, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  132. }
  133. else if(diffInDays < 3 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 1)
  134. {
  135. LogRenew($"Your database license will expire in less than three days, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  136. _expiredLicenseCounter = 0;
  137. }
  138. else if(diffInDays < 7 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 2)
  139. {
  140. LogRenew($"Your database license will expire in less than a week, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  141. _expiredLicenseCounter = 0;
  142. }
  143. ++_expiredLicenseCounter;
  144. }
  145. public static void LogReadOnly()
  146. {
  147. LogError("Database is read-only because your license is invalid!");
  148. }
  149. private static void BeginReadOnly()
  150. {
  151. LogImportant("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://prs-software.com.au/wiki/index.php/License_Renewal.");
  152. _readOnly = true;
  153. }
  154. private static void EndReadOnly()
  155. {
  156. LogImportant("Valid license found; the database is no longer read-only.");
  157. _readOnly = false;
  158. }
  159. private static void BeginLicenseCheckTimer()
  160. {
  161. LicenseTimer.Elapsed += LicenseTimer_Elapsed;
  162. LicenseTimer.Start();
  163. }
  164. private static void LicenseTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
  165. {
  166. AssertLicense();
  167. }
  168. private static Random LicenseIDGenerate = new Random();
  169. private static void UpdateValidLicense(License license, LicenseData licenseData)
  170. {
  171. var ids = Provider.Query(
  172. new Filter<UserTracking>(x => x.Created).IsGreaterThanOrEqualTo(licenseData.LastRenewal),
  173. new Columns<UserTracking>(x => x.ID), log: false);
  174. var newIDList = new List<Guid>();
  175. if(ids.Rows.Count > 0)
  176. {
  177. for (int i = 0; i < 10; i++)
  178. {
  179. newIDList.Add(ids.Rows[LicenseIDGenerate.Next(0, ids.Rows.Count)].Get<UserTracking, Guid>(x => x.ID));
  180. }
  181. }
  182. licenseData.UserTrackingItems = newIDList.ToArray();
  183. if(LicenseUtils.TryEncryptLicense(licenseData, out var newData, out var error))
  184. {
  185. license.Data = newData;
  186. Provider.Save(license);
  187. }
  188. }
  189. private static void AssertLicense()
  190. {
  191. var result = CheckLicenseValidity(out var license, out var licenseData);
  192. if (IsReadOnly)
  193. {
  194. if(result == LicenseValidation.Valid)
  195. {
  196. EndReadOnly();
  197. }
  198. return;
  199. }
  200. // TODO: Switch to real system
  201. if(result != LicenseValidation.Valid)
  202. {
  203. var newLicense = LicenseUtils.GenerateNewLicense();
  204. if (LicenseUtils.TryEncryptLicense(newLicense, out var newData, out var error))
  205. {
  206. license.Data = newData;
  207. Provider.Save(license);
  208. }
  209. else
  210. {
  211. Logger.Send(LogType.Error, "", $"Error updating license: {error}");
  212. }
  213. return;
  214. }
  215. else
  216. {
  217. return;
  218. }
  219. switch (result)
  220. {
  221. case LicenseValidation.Valid:
  222. LogLicenseExpiry(licenseData!.Expiry);
  223. UpdateValidLicense(license, licenseData);
  224. break;
  225. case LicenseValidation.Missing:
  226. LogImportant("Database is unlicensed!");
  227. BeginReadOnly();
  228. break;
  229. case LicenseValidation.Expired:
  230. LogImportant("Database license has expired!");
  231. BeginReadOnly();
  232. break;
  233. case LicenseValidation.Corrupt:
  234. LogImportant("Database license is corrupt - you will need to renew your license.");
  235. BeginReadOnly();
  236. break;
  237. case LicenseValidation.Tampered:
  238. LogImportant("Database license has been tampered with - you will need to renew your license.");
  239. BeginReadOnly();
  240. break;
  241. }
  242. }
  243. #endregion
  244. #region Logging
  245. private static void LogMessage(LogType type, string message)
  246. {
  247. Logger.Send(type, "", message);
  248. }
  249. private static void LogInfo(string message)
  250. {
  251. Logger.Send(LogType.Information, "", message);
  252. }
  253. private static void LogImportant(string message)
  254. {
  255. Logger.Send(LogType.Important, "", message);
  256. }
  257. private static void LogError(string message)
  258. {
  259. Logger.Send(LogType.Error, "", message);
  260. }
  261. #endregion
  262. public static void InitStores()
  263. {
  264. foreach (var storetype in stores)
  265. {
  266. var store = Activator.CreateInstance(storetype) as IStore;
  267. store.Provider = Provider;
  268. store.Init();
  269. }
  270. }
  271. public static IStore<TEntity> FindStore<TEntity>(Guid userguid, string userid, string platform, string version)
  272. where TEntity : Entity, new()
  273. {
  274. var defType = typeof(Store<>).MakeGenericType(typeof(TEntity));
  275. Type? subType = Stores.Where(myType => myType.IsSubclassOf(defType)).FirstOrDefault();
  276. var store = (Store<TEntity>)Activator.CreateInstance(subType ?? defType)!;
  277. store.Provider = Provider;
  278. store.UserGuid = userguid;
  279. store.UserID = userid;
  280. store.Platform = platform;
  281. store.Version = version;
  282. return store;
  283. }
  284. private static CoreTable DoQueryMultipleQuery<TEntity>(
  285. IQueryDef query,
  286. Guid userguid, string userid, string platform, string version)
  287. where TEntity : Entity, new()
  288. {
  289. var store = FindStore<TEntity>(userguid, userid, platform, version);
  290. return store.Query(query.Filter as Filter<TEntity>, query.Columns as Columns<TEntity>, query.SortOrder as SortOrder<TEntity>);
  291. }
  292. public static Dictionary<string, CoreTable> QueryMultiple(
  293. Dictionary<string, IQueryDef> queries,
  294. Guid userguid, string userid, string platform, string version)
  295. {
  296. var result = new Dictionary<string, CoreTable>();
  297. var queryMethod = typeof(DbFactory).GetMethod(nameof(DoQueryMultipleQuery), BindingFlags.NonPublic | BindingFlags.Static)!;
  298. var tasks = new List<Task>();
  299. foreach (var item in queries)
  300. tasks.Add(Task.Run(() =>
  301. {
  302. result[item.Key] = (queryMethod.MakeGenericMethod(item.Value.Type).Invoke(Provider, new object[]
  303. {
  304. item.Value,
  305. userguid, userid, platform, version
  306. }) as CoreTable)!;
  307. }));
  308. Task.WaitAll(tasks.ToArray());
  309. return result;
  310. }
  311. #region Supported Types
  312. private class ModuleConfiguration : Dictionary<string, bool>, LocalConfigurationSettings
  313. {
  314. }
  315. private static Type[]? _dbtypes;
  316. public static IEnumerable<string> SupportedTypes()
  317. {
  318. _dbtypes ??= LoadSupportedTypes();
  319. return _dbtypes.Select(x => x.EntityName().Replace(".", "_"));
  320. }
  321. private static Type[] LoadSupportedTypes()
  322. {
  323. var result = new List<Type>();
  324. var path = Provider.URL.ToLower();
  325. var config = new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Load();
  326. var bChanged = false;
  327. foreach (var type in Entities)
  328. {
  329. var key = type.EntityName();
  330. if (config.ContainsKey(key))
  331. {
  332. if (config[key])
  333. //Logger.Send(LogType.Information, "", String.Format("{0} is enabled", key));
  334. result.Add(type);
  335. else
  336. Logger.Send(LogType.Information, "", string.Format("Entity [{0}] is disabled", key));
  337. }
  338. else
  339. {
  340. //Logger.Send(LogType.Information, "", String.Format("{0} does not exist - enabling", key));
  341. config[key] = true;
  342. result.Add(type);
  343. bChanged = true;
  344. }
  345. }
  346. if (bChanged)
  347. new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Save(config);
  348. return result.ToArray();
  349. }
  350. public static bool IsSupported<T>() where T : Entity
  351. {
  352. _dbtypes ??= LoadSupportedTypes();
  353. return _dbtypes.Contains(typeof(T));
  354. }
  355. #endregion
  356. //public static void OpenSession(bool write)
  357. //{
  358. // Provider.OpenSession(write);
  359. //}
  360. //public static void CloseSession()
  361. //{
  362. // Provider.CloseSession();
  363. //}
  364. #region Private Methods
  365. public static void LoadScripts()
  366. {
  367. Logger.Send(LogType.Information, "", "Loading Script Cache...");
  368. LoadedScripts.Clear();
  369. var scripts = Provider.Load(
  370. new Filter<Script>
  371. (x => x.ScriptType).IsEqualTo(ScriptType.BeforeQuery)
  372. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterQuery)
  373. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeSave)
  374. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterSave)
  375. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeDelete)
  376. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterDelete)
  377. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterLoad)
  378. );
  379. foreach (var script in scripts)
  380. {
  381. var key = string.Format("{0} {1}", script.Section, script.ScriptType.ToString());
  382. var doc = new ScriptDocument(script.Code);
  383. if (doc.Compile())
  384. {
  385. Logger.Send(LogType.Information, "",
  386. string.Format("- {0}.{1} Compiled Successfully", script.Section, script.ScriptType.ToString()));
  387. LoadedScripts[key] = doc;
  388. }
  389. else
  390. {
  391. Logger.Send(LogType.Error, "",
  392. string.Format("- {0}.{1} Compile Exception:\n{2}", script.Section, script.ScriptType.ToString(), doc.Result));
  393. }
  394. }
  395. Logger.Send(LogType.Information, "", "Loading Script Cache Complete");
  396. }
  397. //private static Type[] entities = null;
  398. //private static void SetEntityTypes(Type[] types)
  399. //{
  400. // foreach (Type type in types)
  401. // {
  402. // if (!type.IsSubclassOf(typeof(Entity)))
  403. // throw new Exception(String.Format("{0} is not a valid entity", type.Name));
  404. // }
  405. // entities = types;
  406. //}
  407. private static Type[] stores = { };
  408. private static void SetStoreTypes(Type[] types)
  409. {
  410. types = types.Where(
  411. myType => myType.IsClass
  412. && !myType.IsAbstract
  413. && !myType.IsGenericType).ToArray();
  414. foreach (var type in types)
  415. if (!type.GetInterfaces().Contains(typeof(IStore)))
  416. throw new Exception(string.Format("{0} is not a valid store", type.Name));
  417. stores = types;
  418. }
  419. private static Type[] ConsolidatedObjectModel()
  420. {
  421. // Add the core types from InABox.Core
  422. var types = new List<Type>();
  423. //var coreTypes = CoreUtils.TypeList(
  424. // new Assembly[] { typeof(Entity).Assembly },
  425. // myType =>
  426. // myType.IsClass
  427. // && !myType.IsAbstract
  428. // && !myType.IsGenericType
  429. // && myType.IsSubclassOf(typeof(Entity))
  430. // && myType.GetInterfaces().Contains(typeof(IRemotable))
  431. //);
  432. //types.AddRange(coreTypes);
  433. // Now add the end-user object model
  434. types.AddRange(Entities.Where(x =>
  435. x.GetTypeInfo().IsClass
  436. && !x.GetTypeInfo().IsGenericType
  437. && x.GetTypeInfo().IsSubclassOf(typeof(Entity))
  438. ));
  439. return types.ToArray();
  440. }
  441. private enum SchemaStatus
  442. {
  443. New,
  444. Changed,
  445. Validated
  446. }
  447. private static Dictionary<string, Type> GetSchema()
  448. {
  449. var model = new Dictionary<string, Type>();
  450. var objectmodel = ConsolidatedObjectModel();
  451. foreach (var type in objectmodel)
  452. {
  453. Dictionary<string, Type> thismodel = CoreUtils.PropertyList(type, x => true, true);
  454. foreach (var key in thismodel.Keys)
  455. model[type.Name + "." + key] = thismodel[key];
  456. }
  457. return model;
  458. //return Serialization.Serialize(model, Formatting.Indented);
  459. }
  460. private static SchemaStatus ValidateSchema()
  461. {
  462. var db_schema = Provider.GetSchema();
  463. if (db_schema.Count() == 0)
  464. return SchemaStatus.New;
  465. var mdl_json = Serialization.Serialize(GetSchema());
  466. var db_json = Serialization.Serialize(db_schema);
  467. return mdl_json.Equals(db_json) ? SchemaStatus.Validated : SchemaStatus.Changed;
  468. }
  469. private static void SaveSchema()
  470. {
  471. Provider.SaveSchema(GetSchema());
  472. }
  473. #endregion
  474. }
  475. }