-
Notifications
You must be signed in to change notification settings - Fork 0
/
dca-server.js
72 lines (56 loc) · 2.33 KB
/
dca-server.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
#!/usr/bin/env node
const DEBUG = process.env.DEBUG;
const port = process.env.DCA_SERVER_PORT || 0xDCA /* 3530 */;
const host = process.env.DCA_SERVER_HOST || "127.0.0.1";
const dca = require("./dca");
const spawn = require('child_process').spawn;
const http = require('http');
const server = http.createServer(onRequest);
server.listen(port, host);
console.log(`Running at ${host}:${port}`);
function error(res, code, message) {
res.writeHead(code, {"Content-Type": "application/json"});
res.end(JSON.stringify({message}));
}
function onRequest(req, res){
if (req.method !== "POST") {
return error(res, 400, "Not a POST request");
}
var query = "";
req.on("data", data => query += data);
req.on("end", () => {
try {
query = query.length > 0 ? JSON.parse(query) : null;
} catch(e) {
return error(res, 400, "Unable to parse request: invalid JSON");
}
handleRequest(req, res, query)
});
}
function handleRequest(req, res, query) {
if (DEBUG) console.log("query", query);
if (query == null) return error(res, 400, "Empty query");
if (!query.input) return error(res, 400, "Undefined 'input' parameter");
if (query.args && typeof query.args.map !== "function")
return error(res, 400, "Parameter 'args' must be an array");
query.frame_duration = query.frame_duration || 20;
if (typeof query.frame_duration !== "number")
return error(res, 400, "Parameter 'frame_duration' must be a number");
query.compression_level = query.compression_level || 10;
if (typeof query.frame_duration !== "number")
return error(res, 400, "Parameter 'compression_level' must be a number");
query.b = query.bitrate || null;
query.ac = query.channels || null;
query.vol = query.volume || null;
var applications = ["voip", "audio", "lowdelay"];
query.application = query.application || "audio";
if (typeof query.application !== "string")
return error(res, 400, "Parameter 'application' must be a string");
if (applications.indexOf(query.application) < 0)
return error(res, 400, "Parameter 'application' must be one of the following: " + applications.join(", "));
var streamInfo = dca.createStream(query);
res.writeHead(200, {"Content-Type": "audio/discord-dca-raw"});
streamInfo.stream.pipe(res);
res.on("error", () => streamInfo.process.kill());
res.on("close", () => streamInfo.process.kill());
}