-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
75 lines (67 loc) · 2.59 KB
/
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
73
74
75
import proxyRequest from "./backend/api/proxyRequest.js";
import streamSentences from "./backend/api/streamSentences.js";
import addGarejeyKeyframe from "./backend/api/addGarejeyKeyframe.js";
import * as url from 'url';
import * as fsSync from 'fs';
import * as path from 'path';
import * as http from 'http';
import {getMimeByExt} from 'klesun-node-tools/src/Utils/HttpUtil.js';
import {dirname} from "path";
import {fileURLToPath} from "url";
const fs = fsSync.promises;
const __dirname = dirname(fileURLToPath(import.meta.url));
const PUBLIC_PATH = path.resolve(__dirname, './public');
class HttpError extends Error {
constructor(statusCode, message) {
super(message);
this.statusCode = statusCode;
}
}
const serveStaticFile = async (rq, rs) => {
const parsedUrl = url.parse(rq.url);
const pathname = decodeURIComponent(parsedUrl.pathname);
const normalizedPathname = pathname.endsWith('/')
? pathname + 'index.html'
: pathname;
const absPath = path.resolve(PUBLIC_PATH + '/' + normalizedPathname);
if (!absPath.startsWith(PUBLIC_PATH + '/') && absPath !== PUBLIC_PATH) {
throw new HttpError(400, 'Invalid path requested: ' + pathname);
}
if (!fsSync.existsSync(absPath)) {
throw new HttpError(404, 'File ' + pathname + ' does not exist');
}
const ext = absPath.replace(/^.*\./, '');
const mime = getMimeByExt(ext);
if (mime) {
rs.setHeader('Content-Type', mime);
}
fsSync.createReadStream(absPath).pipe(rs);
};
const handleHttpRequest = async (req, res) => {
if (req.url === '/api/proxyRequest') {
await proxyRequest(req, res);
} else if (req.url === '/api/streamSentences') {
await streamSentences(req, res);
} else if (req.url === '/api/addGarejeyKeyframe') {
await addGarejeyKeyframe(req, res);
} else {
await serveStaticFile(req, res);
}
};
/**
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
const handleHttpRequestSafe = (req, res) => {
handleHttpRequest(req, res).catch(exc => {
res.statusCode = exc?.statusCode || 500;
res.statusMessage = ((exc || {}).message || exc + '' || '(empty error)')
// sanitize, as statusMessage seems to not allow special characters
.slice(0, 300).replace(/[^ -~]/g, '?');
res.end(JSON.stringify({error: exc + '', stack: exc.stack}));
});
};
// const PORT = 80;
const PORT = 19424;
http.createServer(handleHttpRequestSafe)
.listen(PORT, () => console.log('Now you can open http://localhost:' + PORT + '/views/untranslate.html in your browser ;)'));