<commit_before>#!/usr/bin/env node
'use strict';

process.title = 'pengu';
let _dbUri = process.env.DATABASE_URL;

const { server: WebSocketServer } = require('websocket');
const http = require('http');
const path = require('path');
const express = require('express');
const pg = require('pg');
const poly = require('./poly');
const { Line, Point } = poly;
const pengu = require('./pengu');
const mapUtils = require('./mapUtils');
const { promisify } = require('es6-promisify');
const session = require('express-session');
const { signedCookie } = require('cookie-parser');
const morgan = require('morgan');
const serveStatic = require('serve-static');
const fs = require('fs');

function findById(arr, id) {
	for (let item of arr) {
		if (item.id === id) {
			return item;
		}
	}
	return null;
}

async function runApp() {
	let app = express();

	app.set('port', process.env.PORT ?? 8080);

	let sessionStore = new session.MemoryStore();
	let secret = Math.random().toString();
	app.use(session({store: sessionStore, resave: true, saveUninitialized: true, secret: secret, cookie: { maxAge: 10000 }, key: 'sid'}));

	let env = process.env.NODE_ENV ?? 'development';
	if (env === 'development') {
		app.use(morgan('combined'));
	}

	app.get('/', function(req, res) {
		if (!req.session.user) {
				res.redirect('/authenticate');
		} else {
				res.statusCode = 200;
				res.sendFile(path.join(__dirname, '../client/index.html'));
		}
	});

	app.use('/content', serveStatic(path.join(__dirname, '../content')));
	app.use('/', serveStatic(path.join(__dirname, '../client')));

	if (process.env.OPENID_PROVIDER) {
		require('./auth/openid')(app, process.env.OPENID_VERIFY, process.env.OPENID_REALM, process.env.OPENID_PROVIDER);
	} else {
		require('./auth/simple')(app);
	}

	let server = http.createServer(app).listen(app.get('port'));
	console.log('Started app on port %d', app.get('port'));

	let wsServer = new WebSocketServer({
		httpServer: server,
		port: 1337,
		autoAcceptConnections: false
	});

	function originIsAllowed(origin) {
		return true;
	}

	let clients = [];
	let players = {};
	let rooms = JSON.parse(fs.readFileSync(path.join(__dirname, '../content/world/map.json'), 'utf8'), function (key, value) {
		let type;
		if (value && typeof value === 'object') {
			type = value._class;
			if (typeof type === 'string' && typeof poly[type] === 'function') {
				return new (poly[type])(value);
			}
		}
		return value;
	});
	let items = JSON.parse(fs.readFileSync(path.join(__dirname, '../content/items/items.json'), 'utf8'));

	let dbEnabled = _dbUri !== null;
	let pgpool = new pg.Pool({connectionString: _dbUri});
	let registered = {};
	if (dbEnabled) {
		let result = await pgpool.query('select * from "penguin"');
		for (let row of result.rows) {
			registered[row.name] = row;
		}
	}

	wsServer.on('request', function(request) {
		if (!originIsAllowed(request.origin)) {
			request.reject();
			console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
			return;
		}

		let connection = request.accept(null, request.origin);
		clients.push(connection);
		console.log((new Date()) + ' Connection accepted.');
		connection.on('message', async function(message) {
			if (message.type === 'utf8') {
				try {
					let json = JSON.parse(message.utf8Data);
					console.log(json);
					if (json.type === 'init' && connection.name === undefined) {
						let sid = signedCookie(request.cookies.filter((x) => x.name == 'sid')[0].value, secret);
						try {
							let session = await promisify(sessionStore.get.bind(sessionStore))(sid);
							if (!session) {
								throw 'Missing session.';
							}<commit_msg>server: Only create pg pool if database is enabled<commit_after>#!/usr/bin/env node
'use strict';

process.title = 'pengu';

const { server: WebSocketServer } = require('websocket');
const http = require('http');
const path = require('path');
const express = require('express');
const pg = require('pg');
const poly = require('./poly');
const { Line, Point } = poly;
const pengu = require('./pengu');
const mapUtils = require('./mapUtils');
const { promisify } = require('es6-promisify');
const session = require('express-session');
const { signedCookie } = require('cookie-parser');
const morgan = require('morgan');
const serveStatic = require('serve-static');
const fs = require('fs');

function findById(arr, id) {
	for (let item of arr) {
		if (item.id === id) {
			return item;
		}
	}
	return null;
}

async function runApp() {
	let app = express();

	app.set('port', process.env.PORT ?? 8080);

	let sessionStore = new session.MemoryStore();
	let secret = Math.random().toString();
	app.use(session({store: sessionStore, resave: true, saveUninitialized: true, secret: secret, cookie: { maxAge: 10000 }, key: 'sid'}));

	let env = process.env.NODE_ENV ?? 'development';
	if (env === 'development') {
		app.use(morgan('combined'));
	}

	app.get('/', function(req, res) {
		if (!req.session.user) {
				res.redirect('/authenticate');
		} else {
				res.statusCode = 200;
				res.sendFile(path.join(__dirname, '../client/index.html'));
		}
	});

	app.use('/content', serveStatic(path.join(__dirname, '../content')));
	app.use('/', serveStatic(path.join(__dirname, '../client')));

	if (process.env.OPENID_PROVIDER) {
		require('./auth/openid')(app, process.env.OPENID_VERIFY, process.env.OPENID_REALM, process.env.OPENID_PROVIDER);
	} else {
		require('./auth/simple')(app);
	}

	let server = http.createServer(app).listen(app.get('port'));
	console.log('Started app on port %d', app.get('port'));

	let wsServer = new WebSocketServer({
		httpServer: server,
		port: 1337,
		autoAcceptConnections: false
	});

	function originIsAllowed(origin) {
		return true;
	}

	let clients = [];
	let players = {};
	let rooms = JSON.parse(fs.readFileSync(path.join(__dirname, '../content/world/map.json'), 'utf8'), function (key, value) {
		let type;
		if (value && typeof value === 'object') {
			type = value._class;
			if (typeof type === 'string' && typeof poly[type] === 'function') {
				return new (poly[type])(value);
			}
		}
		return value;
	});
	let items = JSON.parse(fs.readFileSync(path.join(__dirname, '../content/items/items.json'), 'utf8'));

	let _dbUri = process.env.DATABASE_URL;
	let dbEnabled = _dbUri !== null;
	let pgpool = null;
	let registered = {};
	if (dbEnabled) {
		pgpool = new pg.Pool({connectionString: _dbUri});
		let result = await pgpool.query('select * from "penguin"');
		for (let row of result.rows) {
			registered[row.name] = row;
		}
	}

	wsServer.on('request', function(request) {
		if (!originIsAllowed(request.origin)) {
			request.reject();
			console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
			return;
		}

		let connection = request.accept(null, request.origin);
		clients.push(connection);
		console.log((new Date()) + ' Connection accepted.');
		connection.on('message', async function(message) {
			if (message.type === 'utf8') {
				try {
					let json = JSON.parse(message.utf8Data);
					console.log(json);
					if (json.type === 'init' && connection.name === undefined) {
						let sid = signedCookie(request.cookies.filter((x) => x.name == 'sid')[0].value, secret);
						try {
							let session = await promisify(sessionStore.get.bind(sessionStore))(sid);
							if (!session) {
								throw 'Missing session.';
							}
{'fraction_non_alphanumeric': 0.18397827562797012, 'fraction_numerical': 0.005974202308214528, 'mean_word_length': 4.09053213545266, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3771686', 'n_tokens_mistral': 2663, 'n_tokens_neox': 2396, 'n_words': 558}