1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2024-11-03 21:04:03 +08:00
pigallery2/src/backend/server.ts

164 lines
4.7 KiB
TypeScript
Raw Normal View History

2020-01-29 01:36:52 +08:00
import {Config} from '../common/config/private/Config';
2021-05-16 14:15:42 +08:00
import * as express from 'express';
2020-01-08 05:17:54 +08:00
import {Request} from 'express';
2018-03-31 03:30:30 +08:00
import * as cookieParser from 'cookie-parser';
import * as _http from 'http';
import {Server as HttpServer} from 'http';
2018-11-30 22:36:42 +08:00
// @ts-ignore
2018-03-31 03:30:30 +08:00
import * as locale from 'locale';
import {ObjectManagers} from './model/ObjectManagers';
2018-03-31 03:30:30 +08:00
import {Logger} from './Logger';
import {LoggerRouter} from './routes/LoggerRouter';
import {DiskManager} from './model/DiskManger';
2018-11-19 03:26:29 +08:00
import {ConfigDiagnostics} from './model/diagnostics/ConfigDiagnostics';
2018-03-31 03:30:30 +08:00
import {Localizations} from './model/Localizations';
import {CookieNames} from '../common/CookieNames';
import {Router} from './routes/Router';
import {PhotoProcessing} from './model/fileprocessing/PhotoProcessing';
2020-01-03 05:11:59 +08:00
import * as _csrf from 'csurf';
2020-01-08 05:17:54 +08:00
import * as unless from 'express-unless';
import {Event} from '../common/event/Event';
2020-01-08 05:17:54 +08:00
import {QueryParams} from '../common/QueryParams';
2020-02-08 19:12:20 +08:00
import {ConfigClassBuilder} from 'typeconfig/node';
import {ConfigClassOptions} from 'typeconfig/src/decorators/class/IConfigClass';
import {DatabaseType} from '../common/config/private/PrivateConfig';
2017-07-24 04:37:29 +08:00
const session = require('cookie-session');
2016-03-12 19:53:19 +08:00
2019-12-13 02:11:49 +08:00
declare var process: NodeJS.Process;
2018-03-31 03:30:30 +08:00
const LOG_TAG = '[server]';
2017-07-19 16:21:52 +08:00
2016-03-12 21:57:22 +08:00
export class Server {
2016-03-12 19:53:19 +08:00
public onStarted = new Event<void>();
2021-05-16 14:15:42 +08:00
private app: express.Express;
private server: HttpServer;
constructor() {
if (!(process.env.NODE_ENV === 'production')) {
Logger.info(LOG_TAG, 'Running in DEBUG mode, set env variable NODE_ENV=production to disable ');
}
2019-12-10 17:44:35 +08:00
this.init().catch(console.error);
}
get App(): any {
return this.server;
}
2019-12-10 17:44:35 +08:00
async init(): Promise<void> {
2018-03-31 03:30:30 +08:00
Logger.info(LOG_TAG, 'running diagnostics...');
2017-07-14 05:39:09 +08:00
await ConfigDiagnostics.runDiagnostics();
2020-02-08 19:12:20 +08:00
Logger.verbose(LOG_TAG, 'using config from ' +
(ConfigClassBuilder.attachPrivateInterface(Config).__options as ConfigClassOptions).configPath + ':');
Logger.verbose(LOG_TAG, JSON.stringify(Config, null, '\t'));
2021-05-16 14:15:42 +08:00
this.app = express();
2017-06-21 17:32:56 +08:00
LoggerRouter.route(this.app);
2016-03-12 19:53:19 +08:00
this.app.set('view engine', 'ejs');
2017-06-04 21:25:08 +08:00
2016-03-19 04:36:58 +08:00
/**
* Session above all
*/
this.app.use(session({
name: CookieNames.session,
2020-01-03 05:11:59 +08:00
keys: Config.Server.sessionSecret
}));
2017-06-04 21:25:08 +08:00
2017-10-20 00:08:07 +08:00
/**
* Parse parameters in POST
*/
// for parsing application/json
2021-05-16 14:15:42 +08:00
this.app.use(express.json());
this.app.use(cookieParser());
2020-01-08 05:17:54 +08:00
const csuf: any = _csrf();
csuf.unless = unless;
this.app.use(csuf.unless((req: Request) => {
return Config.Client.authenticationRequired === false ||
['/api/user/login', '/api/user/logout', '/api/share/login'].indexOf(req.originalUrl) !== -1 ||
(Config.Client.Sharing.enabled === true && !!req.query[QueryParams.gallery.sharingKey_query]);
}));
// enable token generation but do not check it
this.app.post(['/api/user/login', '/api/share/login'], _csrf({ignoreMethods: ['POST']}));
this.app.get(['/api/user/me', '/api/share/:' + QueryParams.gallery.sharingKey_params], _csrf({ignoreMethods: ['GET']}));
DiskManager.init();
PhotoProcessing.init();
Localizations.init();
2018-03-31 03:30:30 +08:00
this.app.use(locale(Config.Client.languages, 'en'));
if (Config.Server.Database.type !== DatabaseType.memory) {
await ObjectManagers.InitSQLManagers();
2017-07-14 05:39:09 +08:00
} else {
await ObjectManagers.InitMemoryManagers();
2017-07-14 05:39:09 +08:00
}
Router.route(this.app);
// Get PORT from environment and store in Express.
this.app.set('port', Config.Server.port);
// Create HTTP server.
this.server = _http.createServer(this.app);
// Listen on provided PORT, on all network interfaces.
2018-12-28 05:14:32 +08:00
this.server.listen(Config.Server.port, Config.Server.host);
this.server.on('error', this.onError);
this.server.on('listening', this.onListening);
this.onStarted.trigger();
}
2019-02-15 07:25:55 +08:00
/**
* Event listener for HTTP server "error" event.
*/
private onError = (error: any) => {
if (error.syscall !== 'listen') {
Logger.error(LOG_TAG, 'Server error', error);
throw error;
}
const bind = Config.Server.host + ':' + Config.Server.port;
// handle specific listen error with friendly messages
switch (error.code) {
case 'EACCES':
Logger.error(LOG_TAG, bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
Logger.error(LOG_TAG, bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
};
/**
* Event listener for HTTP server "listening" event.
*/
private onListening = () => {
const addr = this.server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
Logger.info(LOG_TAG, 'Listening on ' + bind);
};
2016-03-12 19:53:19 +08:00
}