-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathnode_http_server.js
More file actions
227 lines (193 loc) · 7.29 KB
/
node_http_server.js
File metadata and controls
227 lines (193 loc) · 7.29 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
const Fs = require('fs');
const path = require('path');
const Http = require('http');
const Https = require('https');
const WebSocket = require('ws');
const Express = require('express');
const bodyParser = require('body-parser');
const basicAuth = require('basic-auth-connect');
const CryptoJS = require("crypto-js");
const NodeFlvSession = require('./node_flv_session');
const HTTP_PORT = 80;
const HTTPS_PORT = 443;
const HTTP_MEDIAROOT = './media';
const Logger = require('./node_core_logger');
const context = require('./node_core_ctx');
const ip = require("ip");
const streamsRoute = require('./api/routes/streams');
const serverRoute = require('./api/routes/server');
const relayRoute = require('./api/routes/relay');
class NodeHttpServer {
constructor(config) {
this.port = config.http.port || HTTP_PORT;
this.mediaroot = config.http.mediaroot || HTTP_MEDIAROOT;
this.config = config;
if(!this.config.cdn_url){
this.config.cdn_url = "";
}
if(!this.config.rtmp_url){
this.config.rtmp_url = "rtmp://"+ip.address();
}
let app = Express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.all('*.ts', (req, res, next) => {
res.header("Access-Control-Allow-Origin", this.config.http.allow_origin);
res.header("Access-Control-Allow-Headers", "Content-Length,Authorization,Accept,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range");
res.header("Access-Control-Allow-Methods", "GET,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
res.header("Cache-Control", "public,max-age=5m,s-maxage=5m");
req.method === "OPTIONS" ? res.sendStatus(200) : next();
});
app.get('*.m3u8', (req, res, next) => {
res.header("Access-Control-Allow-Origin", this.config.http.allow_origin);
res.header("Access-Control-Allow-Headers", "Content-Length,Authorization,Accept,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range");
res.header("Access-Control-Allow-Methods", "GET,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
res.header("Cache-Control", "public,max-age=5s,s-maxage=5s");
req.method === "OPTIONS" ? res.sendStatus(200) : next();
});
app.get('*.flv', (req, res, next) => {
req.nmsConnectionType = 'http';
this.onConnect(req, res);
});
let adminEntry = path.join(__dirname + '/public/admin/index.html');
if (Fs.existsSync(adminEntry)) {
app.get('/admin/*', (req, res) => {
res.sendFile(adminEntry);
});
}
app.get('/', (req, res) => {
res.header("Cache-Control", "no-store, max-age=0");
var name = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < 8; i++ ) {
name += characters.charAt(Math.floor(Math.random() * charactersLength));
}
var md5 = CryptoJS.SHA256(this.config.passphrase+"/live/"+name).toString();
var key = name+"?pwd="+md5.substring(0,6);
res.render(
"views/index.html",
{
name:name,
key:key,
rtmp_url:this.config.rtmp_url,
cdn_url:this.config.cdn_url
}
);
});
app.get('/v/:id', (req, res) => {
res.render(
"views/channel.html",
{
name: req.params.id,
cdn_url: this.config.cdn_url
}
);
});
if (this.config.http.api !== false) {
if (this.config.auth && this.config.auth.api) {
app.use(['/api/*', '/admin/*'], basicAuth(this.config.auth.api_user, this.config.auth.api_pass));
}
app.use('/api/streams', streamsRoute(context));
app.use('/api/server', serverRoute(context));
app.use('/api/relay', relayRoute(context));
}
app.use(Express.static(path.join(__dirname + '/public')));
app.use(Express.static(this.mediaroot));
if (config.http.webroot) {
app.use(Express.static(config.http.webroot));
}
this.httpServer = Http.createServer(app);
/**
* ~ openssl genrsa -out privatekey.pem 1024
* ~ openssl req -new -key privatekey.pem -out certrequest.csr
* ~ openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
*/
if (this.config.https) {
let options = {
key: Fs.readFileSync(this.config.https.key),
cert: Fs.readFileSync(this.config.https.cert)
};
this.sport = config.https.port ? config.https.port : HTTPS_PORT;
this.httpsServer = Https.createServer(options, app);
}
}
run() {
this.httpServer.listen(this.port, () => {
Logger.log(`Media Server - Http Server started on port: ${this.port}`);
});
this.httpServer.on('error', (e) => {
Logger.error(`Media Server - Http Server ${e}`);
});
this.httpServer.on('close', () => {
Logger.log('Media Server - Http Server Close.');
});
this.wsServer = new WebSocket.Server({ server: this.httpServer });
this.wsServer.on('connection', (ws, req) => {
req.nmsConnectionType = 'ws';
this.onConnect(req, ws);
});
this.wsServer.on('listening', () => {
Logger.log(`Media Server - WebSocket Server started on port: ${this.port}`);
});
this.wsServer.on('error', (e) => {
Logger.error(`Media Server - WebSocket Server ${e}`);
});
if (this.httpsServer) {
this.httpsServer.listen(this.sport, () => {
Logger.log(`Media Server - Https Server started on port: ${this.sport}`);
});
this.httpsServer.on('error', (e) => {
Logger.error(`Media Server - Https Server ${e}`);
});
this.httpsServer.on('close', () => {
Logger.log('Media Server - Https Server Close.');
});
this.wssServer = new WebSocket.Server({ server: this.httpsServer });
this.wssServer.on('connection', (ws, req) => {
req.nmsConnectionType = 'ws';
this.onConnect(req, ws);
});
this.wssServer.on('listening', () => {
Logger.log(`Media Server - WebSocketSecure Server started on port: ${this.sport}`);
});
this.wssServer.on('error', (e) => {
Logger.error(`Media Server - WebSocketSecure Server ${e}`);
});
}
context.nodeEvent.on('postPlay', (id, args) => {
context.stat.accepted++;
});
context.nodeEvent.on('postPublish', (id, args) => {
context.stat.accepted++;
});
context.nodeEvent.on('doneConnect', (id, args) => {
let session = context.sessions.get(id);
let socket = session instanceof NodeFlvSession ? session.req.socket : session.socket;
context.stat.inbytes += socket.bytesRead;
context.stat.outbytes += socket.bytesWritten;
});
}
stop() {
this.httpServer.close();
if (this.httpsServer) {
this.httpsServer.close();
}
context.sessions.forEach((session, id) => {
if (session instanceof NodeFlvSession) {
session.req.destroy();
context.sessions.delete(id);
}
});
}
onConnect(req, res) {
let session = new NodeFlvSession(this.config, req, res);
session.run();
}
}
module.exports = NodeHttpServer;