Draft rematch (not working yet) + fix Crazyhouse getPromotedFen()
[vchess.git] / server / bin / www
1 #!/usr/bin/env node
2
3 /**
4 * Module dependencies.
5 */
6
7 let app = require('../app');
8 const debug = require('debug')('vc:server');
9 const http = require('http');
10
11 /**
12 * Get port from environment and store in Express.
13 */
14
15 const port = normalizePort(process.env.PORT || '3000');
16 app.set('port', port);
17
18 /**
19 * Create HTTP server.
20 */
21
22 let server = http.createServer(app);
23
24 /*
25 * CRON tasks
26 */
27
28 let cron = require('node-cron');
29 const UserModel = require("../models/User");
30 const GameModel = require("../models/Game");
31 cron.schedule('0 0 0 * * *', function() {
32 // Remove unlogged users and unstarted games every 24h
33 UserModel.cleanUsersDb();
34 GameModel.cleanGamesDb();
35 });
36
37 /**
38 * Listen on provided port, on all network interfaces.
39 */
40
41 server.listen(port);
42 server.on('error', onError);
43 server.on('listening', onListening);
44
45 /*
46 * Sockets handling
47 */
48
49 const WebSocket = require('ws');
50 const wss = new WebSocket.Server({ server: server });
51 require('../sockets')(wss);
52
53 /**
54 * Normalize a port into a number, string, or false.
55 */
56
57 function normalizePort(val) {
58 const parsedPort = parseInt(val, 10);
59
60 if (isNaN(parsedPort)) {
61 // named pipe
62 return val;
63 }
64
65 if (parsedPort >= 0) {
66 // port number
67 return parsedPort;
68 }
69
70 return false;
71 }
72
73 /**
74 * Event listener for HTTP server "error" event.
75 */
76
77 function onError(error) {
78 if (error.syscall !== 'listen') {
79 throw error;
80 }
81
82 const bind = typeof port === 'string'
83 ? 'Pipe ' + port
84 : 'Port ' + port;
85
86 // handle specific listen errors with friendly messages
87 switch (error.code) {
88 case 'EACCES':
89 console.error(bind + ' requires elevated privileges');
90 process.exit(1);
91 break;
92 case 'EADDRINUSE':
93 console.error(bind + ' is already in use');
94 process.exit(1);
95 break;
96 default:
97 throw error;
98 }
99 }
100
101 /**
102 * Event listener for HTTP server "listening" event.
103 */
104
105 function onListening() {
106 const addr = server.address();
107 const bind = typeof addr === 'string'
108 ? 'pipe ' + addr
109 : 'port ' + addr.port;
110 debug('Listening on ' + bind);
111 }