DatabaseEngine.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. DbFactory.EmailAddress = imap.EmailAddress;
  148. break;
  149. case ServerEmailExchangeProperties exchange:
  150. DbFactory.Mailer = new ExchangeMailer
  151. {
  152. MailboxHost = exchange.Host,
  153. MailboxDomain = exchange.Domain,
  154. MailboxUserName = exchange.UserName,
  155. MailboxPassword = exchange.Password,
  156. MailboxPort = exchange.Port
  157. };
  158. DbFactory.EmailAddress = exchange.EmailAddress;
  159. break;
  160. }
  161. }
  162. }
  163. #region Run/Stop Functionality
  164. public override void Run()
  165. {
  166. Logger.Send(LogType.Information, "", "Starting..");
  167. if (string.IsNullOrEmpty(Properties.FileName))
  168. throw new Exception("Error: Filename not Specified\n");
  169. Logger.Send(LogType.Information, "", "Registering Classes: " + Properties.FileName);
  170. StoreUtils.RegisterClasses();
  171. CoreUtils.RegisterClasses();
  172. ComalUtils.RegisterClasses();
  173. PRSSharedUtils.RegisterClasses();
  174. ReportUtils.RegisterClasses();
  175. ConfigurationUtils.RegisterClasses();
  176. DatabaseUpdateScripts.RegisterScripts();
  177. Logger.Send(LogType.Information, "", "Starting Database: " + Properties.FileName);
  178. DbFactory.Stores = CoreUtils.TypeList(
  179. AppDomain.CurrentDomain.GetAssemblies(),
  180. myType =>
  181. myType is { IsClass: true, IsAbstract: false, IsGenericType: false }
  182. && myType.GetInterfaces().Contains(typeof(IStore))
  183. ).ToArray();
  184. DbFactory.DefaultStore = typeof(BaseStore<>);
  185. DbFactory.ProviderFactory = new SQLiteProviderFactory(Properties.FileName);
  186. DbFactory.ColorScheme = Properties.ColorScheme;
  187. DbFactory.Logo = Properties.Logo;
  188. // See notes on Request.DatabaseInfo Class
  189. // Once RPC listeners are stable, this should be removed.
  190. DbFactory.RestPort = Properties.Port;
  191. DbFactory.RPCPort = Properties.RPCPort;
  192. DbFactory.Start();
  193. UserStore.PasswordExpirationTime = TimeSpan.FromDays(Properties.PasswordExpiryTime);
  194. RestService.CheckPasswordExpiration = Properties.PasswordExpiryTime > 0;
  195. if (DbFactory.IsReadOnly)
  196. {
  197. Logger.Send(LogType.Error,"","Unable to create ADMIN user at this time.");
  198. }
  199. else
  200. {
  201. var users = DbFactory.NewProvider(Logger.Main).Load<User>();
  202. if (!users.Any())
  203. {
  204. var user = new User { UserID = "ADMIN", Password = "admin" };
  205. DbFactory.NewProvider(Logger.Main).Save(user);
  206. var employee = DbFactory.NewProvider(Logger.Main).Load(new Filter<Employee>(x => x.Code).IsEqualTo("ADMIN"))
  207. .FirstOrDefault()
  208. ?? new Employee { Code = "ADMIN", Name = "Administrator Account" };
  209. employee.UserLink.ID = user.ID;
  210. DbFactory.NewProvider(Logger.Main).Save(employee);
  211. }
  212. }
  213. StoreUtils.GoogleAPIKey = Properties.GoogleAPIKey;
  214. PurchaseOrder.PONumberPrefix = Properties.PurchaseOrderPrefix;
  215. Job.JobNumberPrefix = Properties.JobPrefix;
  216. ConfigureSmsProviders();
  217. CredentialsCache.SetCacheFile(Path.Combine(AppDataFolder, "session_cache.json"));
  218. CredentialsCache.LoadSessionCache();
  219. CredentialsCache.SetSessionExpiryTime(TimeSpan.FromMinutes(Properties.SessionExpiryTime));
  220. Start();
  221. }
  222. private void Start()
  223. {
  224. var certificate = LoadCertificate(CertificateFileName());
  225. if (certificate != null)
  226. {
  227. // Once every day, check certificate expiry
  228. if (_certificateRefreshTimer == null)
  229. {
  230. _certificateRefreshTimer = new Timer(1000 * 60 * 60 * 24);
  231. _certificateRefreshTimer.Elapsed += CertificateTimer_Elapsed;
  232. _certificateRefreshTimer.AutoReset = true;
  233. }
  234. _certificateRefreshTimer.Start();
  235. }
  236. // Older Style Rest-Listener
  237. if (Properties.Port != 0)
  238. {
  239. RestListener.Init((ushort)Properties.Port, certificate);
  240. RestListener.Start();
  241. Logger.Send(LogType.Information, "", $"- Rest Listener Started: Port={Properties.Port}");
  242. }
  243. // New Style Socket Listener
  244. if (Properties.RPCPort != 0)
  245. {
  246. var sockettransport = new RpcServerSocketTransport(Properties.RPCPort); //, certificate);
  247. _socketserver = new RpcServer<RpcServerSocketTransport>(sockettransport);
  248. _socketserver.OnLog += (type, userid, message, parameters) => Logger.Send(type, userid, $"[S] {message}", parameters);
  249. _socketserver.Start();
  250. PushManager.AddPusher(sockettransport);
  251. Logger.Send(LogType.Information, "", $"- RPC Listener Started: Port={Properties.RPCPort}");
  252. }
  253. // Older-Style Pipe (IPC Server)
  254. _ipcServer = new IPCServer(_ipcPipeName);
  255. _ipcServer.Start();
  256. Logger.Send(LogType.Information, "", $"- IPC Pipe Listener started: Name=[{_ipcPipeName}]");
  257. // New Style Pipe (RPC) Listener
  258. var pipetransport = new RpcServerPipeTransport(_rpcPipeName);
  259. PushManager.AddPusher(pipetransport);
  260. _pipeserver = new RpcServer<RpcServerPipeTransport>(pipetransport);
  261. _pipeserver.OnLog += (type, userid, message, parameters) => Logger.Send(type, userid, $"[P] {message}", parameters);
  262. _pipeserver.Start();
  263. Logger.Send(LogType.Information, "", $"- RPC Pipe Listener started: Name=[{_rpcPipeName}]");
  264. PushManager.AddPollHandler(PollNotifications);
  265. Logger.Send(LogType.Information, "", $"- Push Notifications Configured");
  266. if(_scheduleTimer is null)
  267. {
  268. _scheduleTimer = new Timer(TimeSpan.FromMinutes(1));
  269. _scheduleTimer.Elapsed += _scheduleTimer_Elapsed;
  270. _scheduleTimer.AutoReset = true;
  271. }
  272. _scheduleTimer.Start();
  273. Logger.Send(LogType.Information, "", "Schedule timer started");
  274. }
  275. private void _scheduleTimer_Elapsed(object? sender, ElapsedEventArgs e)
  276. {
  277. EventUtils.CheckScheduledEvents();
  278. }
  279. public override void Stop()
  280. {
  281. Logger.Send(LogType.Information, "", "Stopping..");
  282. _socketserver?.Stop();
  283. _socketserver = null;
  284. _pipeserver?.Stop();
  285. _pipeserver = null;
  286. _scheduleTimer?.Stop();
  287. _scheduleTimer = null;
  288. _ipcServer?.Dispose();
  289. RestListener.Stop();
  290. CredentialsCache.SaveSessionCache();
  291. _certificateRefreshTimer?.Stop();
  292. _certificateRefreshTimer = null;
  293. _certificateHaltTimer?.Stop();
  294. _certificateHaltTimer = null;
  295. }
  296. #endregion
  297. #region Certificate Management
  298. private string CertificateFileName() => Properties.CertificateFile.NotWhiteSpaceOr(CertificateEngine.CertificateFile);
  299. private void SendCertificateExpiryNotification(DateTime expiry)
  300. {
  301. var message = expiry.Date == DateTime.Now.Date
  302. ? $"HTTPS Certificate for Database Engine will expire today at {expiry.TimeOfDay:hh\\:mm}"
  303. : $"HTTPS Certificate for Database Engine will expire in {(expiry - DateTime.Now).Days} at {expiry:dd/MM/yyyy hh:mm}";
  304. Logger.Send(LogType.Information, "DATABASE", message);
  305. if (!string.IsNullOrWhiteSpace(Properties.CertificateExpirationSubscriber))
  306. {
  307. var employee = DbFactory.NewProvider(Logger.Main).Query(
  308. new Filter<Employee>(x => x.UserLink.UserID).IsEqualTo(Properties.CertificateExpirationSubscriber),
  309. Columns.None<Employee>().Add(x => x.ID, x => x.UserLink.ID, x => x.UserLink.UserID)).Rows.FirstOrDefault()?.ToObject<Employee>();
  310. if (employee != null)
  311. {
  312. var notification = new Notification();
  313. notification.Employee.ID = employee.ID;
  314. notification.Title = "HTTPS Certificate expires soon";
  315. notification.Description = message;
  316. DbFactory.FindStore<Notification>(employee.UserLink.ID, employee.UserLink.UserID, Platform.DatabaseEngine, "", Logger.New())
  317. .Save(notification, "");
  318. }
  319. else
  320. {
  321. Logger.Send(LogType.Information, "DATABASE", $"Certificate expiration subscriber {Properties.CertificateExpirationSubscriber} employee doesn't exist");
  322. }
  323. }
  324. }
  325. private void CertificateTimer_Elapsed(object? sender, ElapsedEventArgs e)
  326. {
  327. if (RestListener.Certificate != null)
  328. {
  329. X509Certificate2? cert = null;
  330. if (File.Exists(CertificateFileName()))
  331. {
  332. cert = new X509Certificate2(CertificateFileName());
  333. }
  334. if (cert != null && cert.NotAfter > RestListener.Certificate.NotAfter && cert.NotAfter > DateTime.Now)
  335. {
  336. Logger.Send(LogType.Information, "DATABASE", "HTTPS Certificate with greater expiry date found; restarting HTTPS listener...");
  337. Stop();
  338. Start();
  339. }
  340. var expiry = RestListener.Certificate.NotAfter;
  341. var untilExpiry = expiry - DateTime.Now;
  342. if (untilExpiry.TotalDays <= 7)
  343. {
  344. SendCertificateExpiryNotification(expiry);
  345. if (untilExpiry.TotalDays <= 1)
  346. {
  347. _certificateRefreshTimer?.Stop();
  348. _certificateHaltTimer = new Timer(untilExpiry.TotalMilliseconds);
  349. _certificateHaltTimer.Elapsed += HTTPS_Halt_Elapsed;
  350. _certificateHaltTimer.AutoReset = false;
  351. _certificateHaltTimer.Start();
  352. }
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// Restarts listener in HTTP mode
  358. /// </summary>
  359. /// <param name="sender"></param>
  360. /// <param name="e"></param>
  361. private void HTTPS_Halt_Elapsed(object? sender, ElapsedEventArgs e)
  362. {
  363. _certificateHaltTimer?.Dispose();
  364. _certificateHaltTimer = null;
  365. Logger.Send(LogType.Information, "", "Expiry of certificate reached; restarting HTTPS listener...");
  366. Stop();
  367. Start();
  368. }
  369. #endregion
  370. #region Desktop Installer Files
  371. private static bool CheckNewer(string filename)
  372. {
  373. var source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update", filename);
  374. var target = Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update", filename);
  375. if (!File.Exists(target)) return true;
  376. if (!File.Exists(source)) return false;
  377. return File.GetLastWriteTimeUtc(source) > File.GetLastWriteTimeUtc(target);
  378. }
  379. private static void CopyFile(string filename)
  380. {
  381. var source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "update", filename);
  382. var targetdir = Path.Combine(CoreUtils.GetCommonAppData("PRSServer"), "update");
  383. if (!Directory.Exists(targetdir))
  384. Directory.CreateDirectory(targetdir);
  385. var target = Path.Combine(targetdir, filename);
  386. File.Copy(source, target, true);
  387. }
  388. public static void MoveUpdateFiles()
  389. {
  390. try
  391. {
  392. if (CheckNewer("version.txt") || CheckNewer("Release Notes.txt") || CheckNewer("PRSDesktopSetup.exe"))
  393. {
  394. CopyFile("version.txt");
  395. CopyFile("Release Notes.txt");
  396. CopyFile("PRSDesktopSetup.exe");
  397. }
  398. }
  399. catch (Exception e)
  400. {
  401. Logger.Send(LogType.Error, "", $"Could not copy desktop update files: {e.Message}");
  402. }
  403. }
  404. #endregion
  405. }