-
Notifications
You must be signed in to change notification settings - Fork 6
/
requestHandler.js
38 lines (32 loc) · 1.13 KB
/
requestHandler.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
const send = require('send');
const path = require('path');
const logger = require('./logger');
module.exports = (config, hlsSessions) => (req, res) => {
const { cors, mediaPath } = config;
const { url, method } = req;
Object.keys(cors).forEach(corsOption => {
res.setHeader(corsOption, cors[corsOption]);
});
if (method === 'GET') {
const filePath = path.resolve(mediaPath + url);
if (filePath.endsWith('.m3u8') || filePath.endsWith('.ts')) {
send(req, filePath)
.on('error', (err) => logger.error('Error serving ' + filePath, err))
.pipe(res);
const sessionID = url.split('/')[1];
const hlsSession = hlsSessions.get(sessionID);
const requestIp = (typeof req.headers['x-forwarded-for'] === 'string' && req.headers['x-forwarded-for'].split(',').shift()) ||
req.connection?.remoteAddress ||
req.socket?.remoteAddress ||
req.connection?.socket?.remoteAddress;
hlsSession.addViewer(requestIp);
hlsSession.updateLastRequestAt();
} else {
res.statusCode = 400;
res.end();
}
} else {
res.statusCode = 400;
res.end();
}
};