DatabaseEngine.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography.X509Certificates;
  6. using System.Timers;
  7. using Comal.Classes;
  8. using Comal.Stores;
  9. using InABox.API;
  10. using InABox.Configuration;
  11. using InABox.Core;
  12. using InABox.Database;
  13. using InABox.Database.SQLite;
  14. using InABox.IPC;
  15. using InABox.Mail;
  16. using InABox.Rpc;
  17. using InABox.Server;
  18. using InABox.Wpf.Reports;
  19. using PRS.Shared;
  20. using PRS.Shared.Events;
  21. using PRSServices;
  22. using Timer = System.Timers.Timer;
  23. namespace PRSServer;
  24. public class DatabaseEngine : Engine<DatabaseServerProperties>
  25. {
  26. private Timer? _certificateRefreshTimer;
  27. private Timer? _certificateHaltTimer;
  28. private Timer? _scheduleTimer;
  29. private string _ipcPipeName = "";
  30. private IPCServer? _ipcServer;
  31. private string _rpcPipeName = "";
  32. private IRpcServer? _pipeserver;
  33. private IRpcServer? _socketserver;
  34. public override void Configure(Server server)
  35. {
  36. base.Configure(server);
  37. Logger.Send(LogType.Information, "", "Configuring...");
  38. _ipcPipeName = DatabaseServerProperties.GetPipeName(server.Key, false);
  39. _rpcPipeName = DatabaseServerProperties.GetPipeName(server.Key, true);
  40. MoveUpdateFiles();
  41. }
  42. public override PortStatus[] PortStatusList()
  43. {
  44. var result = new List<PortStatus>();
  45. if (Properties.Port != 0)
  46. {
  47. result.Add(RestListener.Certificate != null
  48. ? new PortStatus(Properties.Port, PortType.Database, PortState.Secure)
  49. : new PortStatus(Properties.Port, PortType.Database, PortState.Available));
  50. }
  51. if (Properties.RPCPort != 0)
  52. result.Add(new PortStatus(Properties.RPCPort, PortType.Session, PortState.Available));
  53. return result.ToArray();
  54. }
  55. private void ConfigureSmsProviders()
  56. {
  57. if (Properties.SMSProviderProperties == null) return;
  58. if (Properties.SMSProviderProperties.Count == 0)
  59. {
  60. Logger.Send(LogType.Information, "", "No SMS Providers to initialise");
  61. }
  62. foreach (var (type, properties) in Properties.SMSProviderProperties)
  63. {
  64. var provider = SMSProviderProperties.ToProperties(type, properties);
  65. switch (provider)
  66. {
  67. case ExchangeProviderProperties exchange:
  68. Logger.Send(LogType.Information, "", "Initializing Exchange Mailer");
  69. CredentialsCache.AddSMSProvider(new ExchangeProvider(
  70. exchange.Host,
  71. exchange.Port,
  72. exchange.EmailAddress,
  73. exchange.Password
  74. ));
  75. break;
  76. case IMAPProviderProperties imap:
  77. Logger.Send(LogType.Information, "", "Initializing IMAP Mailer");
  78. CredentialsCache.AddSMSProvider(new IMAPProvider(
  79. imap.Host,
  80. imap.Port,
  81. imap.EmailAddress,
  82. imap.Password
  83. ));
  84. break;
  85. case ASPSMSProviderProperties asp:
  86. Logger.Send(LogType.Information, "", "Initializing ASPSMS");
  87. CredentialsCache.AddSMSProvider(new ASPSMSProvider(
  88. asp.Userkey,
  89. asp.APIPassword
  90. ));
  91. break;
  92. case TwilioProviderProperties tw:
  93. Logger.Send(LogType.Information, "", "Initializing Twilio");
  94. CredentialsCache.AddSMSProvider(new TwilioSMSProvider(
  95. tw.AccountSID,
  96. tw.AuthToken,
  97. tw.Number
  98. ));
  99. break;
  100. }
  101. }
  102. }
  103. private IEnumerable<Notification> PollNotifications(Guid session)
  104. {
  105. var user = CredentialsCache.Validate(session);
  106. if (user == null)
  107. return Array.Empty<Notification>();
  108. var store = DbFactory.FindStore<Notification>(user.ID, user.UserID, Platform.DatabaseEngine, "", Logger.New());
  109. return store.Query(
  110. new Filter<Notification>(x => x.Employee.UserLink.ID).IsEqualTo(user.ID)
  111. .And(x => x.Closed).IsEqualTo(DateTime.MinValue),
  112. Columns.None<Notification>().Add(
  113. x => x.ID,
  114. x => x.Title,
  115. //x => x.Description,
  116. x => x.Created,
  117. x => x.Sender.ID,
  118. x => x.Sender.Name,
  119. x => x.Job.ID,
  120. x => x.Job.Deleted,
  121. x => x.Job.JobNumber,
  122. //x => x.Kanban.ID,
  123. //x => x.Setout.ID,
  124. //x => x.Requisition.ID,
  125. //x => x.Delivery.ID,
  126. x => x.Employee.ID,
  127. x => x.EntityType,
  128. x => x.EntityID,
  129. x => x.Closed
  130. )).Rows.Select(x => x.ToObject<Notification>());
  131. }
  132. private void ConfigureMailer()
  133. {
  134. if (!Properties.EmailProperties.IsNullOrWhiteSpace())
  135. {
  136. switch (Properties.GetEmailProperties())
  137. {
  138. case ServerEmailIMAPProperties imap:
  139. DbFactory.Mailer = new IMAPMailer
  140. {
  141. SMTPHost = imap.Host,
  142. SMTPDomain = imap.Domain,
  143. SMTPUserName = imap.UserName,
  144. SMTPPassword = imap.Password,
  145. SMTPPort = imap.Port
  146. };
  147. break;
  148. case ServerEmailExchangeProperties exchange:
  149. DbFactory.Mailer = new ExchangeMailer
  150. {
  151. MailboxHost = exchange.Host,
  152. MailboxDomain = exchange.Domain,
  153. MailboxUserName = exchange.UserName,
  154. MailboxPassword = exchange.Password,
  155. MailboxPort = exchange.Port
  156. };
  157. break;
  158. }
  159. }
  160. }
  161. #region Run/Stop Functionality
  162. public override void Run()
  163. {
  164. Logger.Send(LogType.Information, "", "Starting..");
  165. if (string.IsNullOrEmpty(Properties.FileName))
  166. throw new Exception("Error: Filename not Specified\n");
  167. Logger.Send(LogType.Information, "", "Registering Classes: " + Properties.FileName);
  168. StoreUtils.RegisterClasses();
  169. CoreUtils.RegisterClasses();
  170. ComalUtils.RegisterClasses();
  171. PRSSharedUtils.RegisterClasses();
  172. ReportUtils.RegisterClasses();
  173. ConfigurationUtils.RegisterClasses();
  174. DatabaseUpdateScripts.RegisterScripts();
  175. Logger.Send(LogType.Information, "", "Starting Database: " + Properties.FileName);
  176. DbFactory.Stores = CoreUtils.TypeList(
  177. AppDomain.CurrentDomain.GetAssemblies(),
  178. myType =>
  179. myType is { IsClass: true, IsAbstract: false, IsGenericType: false }
  180. && myType.GetInterfaces().Contains(typeof(IStore))
  181. ).ToArray();
  182. DbFactory.DefaultStore = typeof(BaseStore<>);
  183. DbFactory.ProviderFactory = new SQLiteProviderFactory(Properties.FileName);
  184. DbFactory.ColorScheme = Properties.ColorScheme;
  185. DbFactory.Logo = Properties.Logo;
  186. // See notes on Request.DatabaseInfo Class
  187. // Once RPC listeners are stable, this should be removed.
  188. DbFactory.RestPort = Properties.Port;
  189. DbFactory.RPCPort = Properties.RPCPort;
  190. DbFactory.Start();
  191. UserStore.PasswordExpirationTime = TimeSpan.FromDays(Properties.PasswordExpiryTime);
  192. RestService.CheckPasswordExpiration = Properties.PasswordExpiryTime > 0;
  193. if (DbFactory.IsReadOnly)
  194. {
  195. Logger.Send(LogType.Error,"","Unable to create ADMIN user at this time.");
  196. }
  197. else
  198. {
  199. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  200. if (!users.Any())
  201. {
  202. var user = new User { UserID = "ADMIN", Password = "admin" };
  203. DbFactory.NewProvider(Logger.Main).Save(user);
  204. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN"))
  205. .FirstOrDefault()
  206. ?? new Employee { Code = "ADMIN", Name = "Administrator Account" };
  207. employee.UserLink.ID = user.ID;
  208. DbFactory.NewProvider(Logger.Main).Save(employee);
  209. }
  210. }
  211. CoreUtils.GoogleAPIKey = Properties.GoogleAPIKey;
  212. PurchaseOrder.PONumberPrefix = Properties.PurchaseOrderPrefix;
  213. Job.JobNumberPrefix = Properties.JobPrefix;
  214. ConfigureMailer();
  215. ConfigureSmsProviders();
  216. CredentialsCache.SetCacheFile(Path.Combine(AppDataFolder, "session_cache.json"));
  217. CredentialsCache.LoadSessionCache();
  218. CredentialsCache.SetSessionExpiryTime(TimeSpan.FromMinutes(Properties.SessionExpiryTime));
  219. Start();
  220. }
  221. private void Start()
  222. {
  223. var certificate = LoadCertificate(CertificateFileName());
  224. if (certificate != null)
  225. {
  226. // Once every day, check certificate expiry
  227. if (_certificateRefreshTimer == null)
  228. {
  229. _certificateRefreshTimer = new Timer(1000 * 60 * 60 * 24);
  230. _certificateRefreshTimer.Elapsed += CertificateTimer_Elapsed;
  231. _certificateRefreshTimer.AutoReset = true;
  232. }
  233. _certificateRefreshTimer.Start();
  234. }
  235. // Older Style Rest-Listener
  236. if (Properties.Port != 0)
  237. {
  238. RestListener.Init((ushort)Properties.Port, certificate);
  239. RestListener.Start();
  240. Logger.Send(LogType.Information, "", $"- Rest Listener Started: Port={Properties.Port}");
  241. }
  242. // New Style Socket Listener
  243. if (Properties.RPCPort != 0)
  244. {
  245. var sockettransport = new RpcServerSocketTransport(Properties.RPCPort); //, certificate);
  246. _socketserver = new RpcServer<RpcServerSocketTransport>(sockettransport);
  247. _socketserver.OnLog += (type, userid, message, parameters) => Logger.Send(type, userid, $"[S] {message}", parameters);
  248. _socketserver.Start();
  249. PushManager.AddPusher(sockettransport);
  250. Logger.Send(LogType.Information, "", $"- RPC Listener Started: Port={Properties.RPCPort}");
  251. }
  252. // Older-Style Pipe (IPC Server)
  253. _ipcServer = new IPCServer(_ipcPipeName);
  254. _ipcServer.Start();
  255. Logger.Send(LogType.Information, "", $"- IPC Pipe Listener started: Name=[{_ipcPipeName}]");
  256. // New Style Pipe (RPC) Listener
  257. var pipetransport = new RpcServerPipeTransport(_rpcPipeName);
  258. PushManager.AddPusher(pipetransport);
  259. _pipeserver = new RpcServer<RpcServerPipeTransport>(pipetransport);
  260. _pipeserver.OnLog += (type, userid, message, parameters) => Logger.Send(type, userid, $"[P] {message}", parameters);
  261. _pipeserver.Start();
  262. Logger.Send(LogType.Information, "", $"- RPC Pipe Listener started: Name=[{_rpcPipeName}]");
  263. PushManager.AddPollHandler(PollNotifications);
  264. Logger.Send(LogType.Information, "", $"- Push Notifications Configured");
  265. if(_scheduleTimer is null)
  266. {
  267. _scheduleTimer = new Timer(TimeSpan.FromMinutes(1));
  268. _scheduleTimer.Elapsed += _scheduleTimer_Elapsed;
  269. _scheduleTimer.AutoReset = true;
  270. }
  271. _scheduleTimer.Start();
  272. Logger.Send(LogType.Information, "", "Schedule timer started");
  273. }
  274. private void _scheduleTimer_Elapsed(object? sender, ElapsedEventArgs e)
  275. {
  276. EventUtils.CheckScheduledEvents();
  277. }
  278. public override void Stop()
  279. {
  280. Logger.Send(LogType.Information, "", "Stopping..");
  281. _socketserver?.Stop();
  282. _socketserver = null;
  283. _pipeserver?.Stop();
  284. _pipeserver = null;
  285. _scheduleTimer?.Stop();
  286. _scheduleTimer = null;
  287. _ipcServer?.Dispose();
  288. RestListener.Stop();
  289. CredentialsCache.SaveSessionCache();
  290. _certificateRefreshTimer?.Stop();
  291. _certificateRefreshTimer = null;
  292. _certificateHaltTimer?.Stop();
  293. _certificateHaltTimer = null;
  294. }
  295. #endregion
  296. #region Certificate Management
  297. private string CertificateFileName() => Properties.CertificateFile.NotWhiteSpaceOr(CertificateEngine.CertificateFile);
  298. private void SendCertificateExpiryNotification(DateTime expiry)
  299. {
  300. var message = expiry.Date == DateTime.Now.Date
  301. ? $"HTTPS Certificate for Database Engine will expire today at {expiry.TimeOfDay:hh\\:mm}"
  302. : $"HTTPS Certificate for Database Engine will expire in {(expiry - DateTime.Now).Days} at {expiry:dd/MM/yyyy hh:mm}";
  303. Logger.Send(LogType.Information, "DATABASE", message);
  304. if (!string.IsNullOrWhiteSpace(Properties.CertificateExpirationSubscriber))
  305. {
  306. var employee = DbFactory.NewProvider(Logger.Main).Query(
  307. new Filter<Employee>(x => x.UserLink.UserID).IsEqualTo(Properties.CertificateExpirationSubscriber),
  308. Columns.None<Employee>().Add(x => x.ID, x => x.UserLink.ID, x => x.UserLink.UserID)).Rows.FirstOrDefault()?.ToObject<Employee>();
  309. if (employee != null)
  310. {
  311. var notification = new Notification();
  312. notification.Employee.ID = employee.ID;
  313. notification.Title = "HTTPS Certificate expires soon";
  314. notification.Description = message;
  315. DbFactory.FindStore<Notification>(employee.UserLink.ID, employee.UserLink.UserID, Platform.DatabaseEngine, "", Logger.New())
  316. .Save(notification, "");
  317. }
  318. else
  319. {
  320. Logger.Send(LogType.Information, "DATABASE", $"Certificate expiration subscriber {Properties.CertificateExpirationSubscriber} employee doesn't exist");
  321. }
  322. }
  323. }
  324. private void CertificateTimer_Elapsed(object? sender, ElapsedEventArgs e)
  325. {
  326. if (RestListener.Certificate != null)
  327. {
  328. X509Certificate2? cert = null;
  329. if (File.Exists(CertificateFileName()))
  330. {
  331. cert = new X509Certificate2(CertificateFileName());
  332. }
  333. if (cert != null && cert.NotAfter > RestListener.Certificate.NotAfter && cert.NotAfter > DateTime.Now)
  334. {
  335. Logger.Send(LogType.Information, "DATABASE", "HTTPS Certificate with greater expiry date found; restarting HTTPS listener...");
  336. Stop();
  337. Start();
  338. }
  339. var expiry = RestListener.Certificate.NotAfter;
  340. var untilExpiry = expiry - DateTime.Now;
  341. if (untilExpiry.TotalDays <= 7)
  342. {
  343. SendCertificateExpiryNotification(expiry);
  344. if (untilExpiry.TotalDays <= 1)
  345. {
  346. _certificateRefreshTimer?.Stop();
  347. _certificateHaltTimer = new Timer(untilExpiry.TotalMilliseconds);
  348. _certificateHaltTimer.Elapsed += HTTPS_Halt_Elapsed;
  349. _certificateHaltTimer.AutoReset = false;
  350. _certificateHaltTimer.Start();
  351. }
  352. }
  353. }
  354. }
  355. /// <summary>
  356. /// Restarts listener in HTTP mode
  357. /// </summary>
  358. /// <param name="sender"></param>
  359. /// <param name="e"></param>
  360. private void HTTPS_Halt_Elapsed(object? sender, ElapsedEventArgs e)
  361. {
  362. _certificateHaltTimer?.Dispose();
  363. _certificateHaltTimer = null;
  364. Logger.Send(LogType.Information, "", "Expiry of certificate reached; restarting HTTPS listener...");
  365. Stop();
  366. Start();
  367. }
  368. #endregion
  369. #region Desktop Installer Files
  370. private static bool CheckNewer(string filename)
  371. {
  372. var source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update", filename);
  373. var target = Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update", filename);
  374. if (!File.Exists(target)) return true;
  375. if (!File.Exists(source)) return false;
  376. return File.GetLastWriteTimeUtc(source) > File.GetLastWriteTimeUtc(target);
  377. }
  378. private static void CopyFile(string filename)
  379. {
  380. var source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update", filename);
  381. var targetdir = Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  382. if (!Directory.Exists(targetdir))
  383. Directory.CreateDirectory(targetdir);
  384. var target = Path.Combine(targetdir, filename);
  385. File.Copy(source, target, true);
  386. }
  387. public static void MoveUpdateFiles()
  388. {
  389. try
  390. {
  391. if (CheckNewer("version.txt") || CheckNewer("Release Notes.txt") || CheckNewer("PRSDesktopSetup.exe"))
  392. {
  393. CopyFile("version.txt");
  394. CopyFile("Release Notes.txt");
  395. CopyFile("PRSDesktopSetup.exe");
  396. }
  397. }
  398. catch (Exception e)
  399. {
  400. Logger.Send(LogType.Error, "", $"Could not copy desktop update files: {e.Message}");
  401. }
  402. }
  403. #endregion
  404. }