-
Notifications
You must be signed in to change notification settings - Fork 0
/
chillerbot-api-srv.js
167 lines (143 loc) · 4.99 KB
/
chillerbot-api-srv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const express = require('express')
const app = express()
const cron = require('node-cron')
const dotenv = require('dotenv')
dotenv.config()
const { insertPlaytime, getPlaytime } = require('./src/database')
const logger = require('./src/logger')
const port = 9812
// Add headers
// https://stackoverflow.com/a/18311469
app.use(function (req, res, next) {
// TODO: make this more dynamic and decide on a front end port (9090 for now)
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9090')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
// Set to true if you need the website to include cookies in the requests sent
// res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next()
})
app.use(
express.urlencoded({
extended: true
})
)
app.set('view engine', 'ejs')
const onlineClients = {}
cron.schedule('* * * * *', () => {
logger.log('cron', `check online players ${Object.keys(onlineClients).length}`)
for (const clientId in onlineClients) {
const client = onlineClients[clientId]
logger.log('cron', `id=${clientId} username=${client.username} lastSeen=${client.lastSeen}`)
const seenSecsAgo = (new Date() - client.lastSeen) / 1000
if (seenSecsAgo > 60 * 3) {
const playtime = Math.round((new Date() - client.firstSeen) / 1000 / 60)
logger.log('cron', `username='${client.username}' left the game (playtime=${playtime})`)
if (playtime > 0) {
insertPlaytime(clientId, client.username, client.ip, playtime)
}
delete onlineClients[clientId]
}
}
})
const saveCurrentPlaytimes = () => {
for (const clientId in onlineClients) {
const client = onlineClients[clientId]
const seenSecsAgo = (new Date() - client.lastSeen) / 1000
if (seenSecsAgo > 60 * 3) {
const playtime = Math.round((new Date() - client.firstSeen) / 1000 / 60)
logger.log('cron', `saving username='${client.username}' (playtime=${playtime})`)
if (playtime > 0) {
insertPlaytime(clientId, client.username, client.ip, playtime)
}
onlineClients[clientId].firstSeen = new Date()
}
}
}
cron.schedule('0 * * * *', () => {
// do hourly saves in case the server restarts or crashes
saveCurrentPlaytimes()
})
const getIpAddr = (req) => {
const forwarded = req.headers['x-forwarded-for']
if (typeof forwarded === 'object') {
return forwarded.pop()
} else if (typeof forwarded === 'string') {
return forwarded.split(',').pop()
}
return req.socket.remoteAddress
}
app.get('/', (req, res) => {
const reqAddr = getIpAddr(req)
logger.log('server', `GET / ${reqAddr}`)
res.end('OK')
})
app.use(express.json())
app.set('trust proxy', true)
app.post('/', (req, res) => {
// const reqHost = `${req.protocol}://${req.header('Host')}`
const reqAddr = getIpAddr(req)
// const isOwnAddr = reqAddr === process.env.IP_ADDR
// if (reqHost !== process.env.CAPTCHA_BACKEND && !isOwnAddr) {
// logger.log('captcha', `blocked post from invalid host='${reqHost}' addr='${reqAddr}' expected='${process.env.CAPTCHA_BACKEND}'`)
// res.end('ERROR')
// return
// }
// const score = req.body.score
// if (score === 1) {
// // do not save robot scores to save memory
// captchaData[req.body.token] = score
// logger.log('captcha', `result=hooman ip=${req.ip}`)
// } else {
// logger.log('captcha', `result=robot ip=${req.ip}`)
// }
logger.log('server', `POST / ${reqAddr}`)
res.end('OK')
})
app.get('/api/v1/beat/:id/:client/:name', (req, res) => {
const clientId = decodeURIComponent(req.params.id)
const name = decodeURIComponent(req.params.name)
const client = decodeURIComponent(req.params.client)
const reqAddr = getIpAddr(req)
logger.log('server', `GET /api/v1/beat/${clientId}/${client}/${name} ${reqAddr}`)
if (!onlineClients[clientId]) {
logger.log('server', `username='${name}' joined the game (client=${client})`)
onlineClients[clientId] = {
username: name,
lastSeen: new Date(),
firstSeen: new Date(),
ip: reqAddr,
client: client
}
} else {
onlineClients[clientId].username = name
onlineClients[clientId].lastSeen = new Date()
}
res.end(JSON.stringify(
getPlaytime(clientId) || 0
))
})
app.get('/api/v1/users', (req, res) => {
res.end(JSON.stringify(
Object.keys(onlineClients).map(id => onlineClients[id].username)
))
})
app.get('/api/v1/playtime/:id', (req, res) => {
const clientId = decodeURIComponent(req.params.id)
res.end(JSON.stringify(
getPlaytime(clientId)
))
})
app.use(express.static('static'))
process.on("SIGINT", () => {
console.log('[*] Got shutdown. Saving current playtimes ...')
saveCurrentPlaytimes()
process.exit()
})
app.listen(port, () => {
logger.log('server', `App running on http://localhost:${port}.`)
})