12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import { Guid, Server } from 'org.crazydoctor.expressts';
- import * as path from 'path';
- import os from 'os';
- import fs from 'fs';
- import { Sources } from './sources/Sources';
- import SHA256 from './util/SHA256';
- import CronSourcesUpdateTask from './util/CronSourcesUpdateTask';
- import { CommentsManager } from './comments/CommentsManager';
- import { WebSocket as WS } from 'ws';
- import WebSocketHandler from './websocket/WebSocket';
- class ServerApp {
- public static SourcesUpdating = false;
- public static Server: Server | null = null;
- public static WebSocketUrl: string = '/ws';
- public static getWebSocketConnections(): Set<WS> | null {
- return ServerApp.Server?.getWsConnections(ServerApp.WebSocketUrl) || null;
- }
- public static async notifySocket(ws: WS, message: string): Promise<void> {
- return new Promise((resolve, reject) => {
- if(ws.readyState !== WS.OPEN)
- reject();
- ws.send(message, (err) => {
- if(err)
- return reject();
- return resolve();
- });
- });
- }
- public static async notifyAllSockets(message: string): Promise<void[]> {
- const promises: Promise<void>[] = [];
- ServerApp.getWebSocketConnections()?.forEach((connection) => {
- promises.push(ServerApp.notifySocket(connection, message));
- });
- return Promise.all(promises);
- }
- public static start(): void {
- const Config = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'config.json'), { encoding: 'utf-8' }).toString());
- const ServerConfig = Config.server;
- const SourcesConfig = Config.sources;
- CommentsManager.init(path.resolve(`${os.homedir()}/${SourcesConfig.assetsDir}/comments`), ServerConfig.commentsRepoUrl);
- new Server({
- port: 3000,
- routesPath: path.resolve(__dirname, './routes'),
- middlewaresPath: path.resolve(__dirname, './middlewares'),
- viewsPath: path.resolve(__dirname, './views'),
- viewEngine: 'pug',
- wsHandlers: {[ServerApp.WebSocketUrl]: new WebSocketHandler()},
- options: {
- static: path.resolve(__dirname, './static'),
- sessionSecret: Guid.new(),
- adminPassword: SHA256.hash(ServerConfig.adminPassword)
- }
- }).init().then((server) => {
- server.start(() => {
- ServerApp.SourcesUpdating = true;
- Sources.get(() => {
- ServerApp.SourcesUpdating = false;
- CronSourcesUpdateTask.start();
- });
- });
- ServerApp.Server = server;
- });
- }
- }
- ServerApp.start();
- export default ServerApp;
|