index.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { Guid, Server } from 'org.crazydoctor.expressts';
  2. import * as path from 'path';
  3. import os from 'os';
  4. import fs from 'fs';
  5. import { Sources } from './sources/Sources';
  6. import SHA256 from './util/SHA256';
  7. import CronSourcesUpdateTask from './util/CronSourcesUpdateTask';
  8. import { CommentsManager } from './comments/CommentsManager';
  9. import { WebSocket as WS } from 'ws';
  10. import WebSocketHandler from './websocket/WebSocket';
  11. class ServerApp {
  12. public static SourcesUpdating = false;
  13. public static Server: Server | null = null;
  14. public static WebSocketUrl: string = '/ws';
  15. public static getWebSocketConnections(): Set<WS> | null {
  16. return ServerApp.Server?.getWsConnections(ServerApp.WebSocketUrl) || null;
  17. }
  18. public static async notifySocket(ws: WS, message: string): Promise<void> {
  19. return new Promise((resolve, reject) => {
  20. if(ws.readyState !== WS.OPEN)
  21. reject();
  22. ws.send(message, (err) => {
  23. if(err)
  24. return reject();
  25. return resolve();
  26. });
  27. });
  28. }
  29. public static async notifyAllSockets(message: string): Promise<void[]> {
  30. const promises: Promise<void>[] = [];
  31. ServerApp.getWebSocketConnections()?.forEach((connection) => {
  32. promises.push(ServerApp.notifySocket(connection, message));
  33. });
  34. return Promise.all(promises);
  35. }
  36. public static start(): void {
  37. const Config = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'config.json'), { encoding: 'utf-8' }).toString());
  38. const ServerConfig = Config.server;
  39. const SourcesConfig = Config.sources;
  40. CommentsManager.init(path.resolve(`${os.homedir()}/${SourcesConfig.assetsDir}/comments`), ServerConfig.commentsRepoUrl);
  41. new Server({
  42. port: 3000,
  43. routesPath: path.resolve(__dirname, './routes'),
  44. middlewaresPath: path.resolve(__dirname, './middlewares'),
  45. viewsPath: path.resolve(__dirname, './views'),
  46. viewEngine: 'pug',
  47. wsHandlers: {[ServerApp.WebSocketUrl]: new WebSocketHandler()},
  48. options: {
  49. static: path.resolve(__dirname, './static'),
  50. sessionSecret: Guid.new(),
  51. adminPassword: SHA256.hash(ServerConfig.adminPassword)
  52. }
  53. }).init().then((server) => {
  54. server.start(() => {
  55. ServerApp.SourcesUpdating = true;
  56. Sources.get(() => {
  57. ServerApp.SourcesUpdating = false;
  58. CronSourcesUpdateTask.start();
  59. });
  60. });
  61. ServerApp.Server = server;
  62. });
  63. }
  64. }
  65. ServerApp.start();
  66. export default ServerApp;