index.ts 2.4 KB

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