123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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';
- import DBEvents from './db/DBEvents';
- class ServerApp {
- public static SourcesUpdating = false;
- public static Server: Server | null = null;
- public static WebSocketUrl: string = '/ws';
- public static GitHost: string = '';
- 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;
- const assetsDir = path.resolve(`${os.homedir()}/${SourcesConfig.assetsDir}`);
- if(!fs.existsSync(assetsDir))
- fs.mkdirSync(assetsDir);
- ServerApp.GitHost = ServerConfig.gitHost;
- CommentsManager.init(path.resolve(`${assetsDir}/comments`), ServerConfig.commentsRepoUrl);
- DBEvents.init(path.resolve(`${assetsDir}/events.db`));
- new Server({
- port: 9080,
- 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),
- sessionMaxAge: 21600000
- }
- }).init().then((server) => {
- server.start(() => {
- ServerApp.SourcesUpdating = true;
- Sources.get(() => {
- ServerApp.SourcesUpdating = false;
- CronSourcesUpdateTask.start();
- });
- });
- ServerApp.Server = server;
- });
- }
- }
- ServerApp.start();
- export default ServerApp;
|