This repository has been archived by the owner on Aug 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.ts
96 lines (81 loc) · 2.47 KB
/
server.ts
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
import * as assert from "assert";
import * as _ from "lodash";
import * as path from "path";
import * as Hapi from "hapi";
const Inert = require("inert");
const ffmpeg = require("fluent-ffmpeg");
import * as request from "request";
const server = new Hapi.Server({
connections: {
routes: {
files: {
relativeTo: path.join(__dirname, 'build')
}
}
}
});
server.connection({ host: process.env.HOST || "0.0.0.0", port: process.env.PORT || 3001 });
server.register(Inert, () => {});
server.route({
method: 'GET',
path: '/transcode',
handler: async function (req, reply) {
const _reply = _.once(reply);
try {
const url:string = req.query["url"];
const output_format = req.query["output_format"];
const container_format = output_format;
const codecs = {
mp3: "libmp3lame",
ogg: "vorbis",
wav: "pcm_s16le"
};
const mime_types = {
mp3: "audio/mpeg",
ogg: "audio/vorbis",
wav: "audio/wav"
}
assert(url);
assert(output_format);
assert(
codecs[output_format] !== undefined,
`Invalid output format: ${output_format}`
);
console.log(url);
console.log(output_format, codecs[output_format]);
const stream = await request(url);
const out = ffmpeg(stream).
on("stderr", console.error).
on("error", console.error).
on("error", err => _reply(err.message).code(500)).
audioCodec(codecs[output_format]).
format(container_format).
stream();
_reply(out).type(mime_types[output_format]);
} catch(ex) {
console.error(ex);
// TODO: Correctly report 404 etc.
_reply(ex.message).code(500);
console.log("Errored out");
}
}
});
// Static files (WebPack / SPA)
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: '.',
redirectToSlash: true,
index: true
}
}
});
export function serve() {
server.initialize().
then(() => server.start()).
then(() => console.log('Server running at:', server.info.uri)).
catch(err => { console.error(err); throw err; });
}
serve()