-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.ts
204 lines (175 loc) 路 4.5 KB
/
index.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
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
import {IncomingMessage, Server, ServerResponse, createServer} from 'http';
import {config, setConfig} from '../config';
import {createReadStream, readdir} from 'fs';
import {
getAllBrands,
getAllModels,
getAllSeries,
storeList,
updateStores
} from '../store/model';
import {isAbsolute, join, normalize, relative} from 'path';
import {logger} from '../logger';
const approot = join(__dirname, '../../');
const webroot = join(approot, './web');
const contentTypeMap: Record<string, string> = {
css: 'text/css',
htm: 'text/html',
html: 'text/html',
jpeg: 'image/jpeg',
jpg: 'image/jpeg',
js: 'application/javascript',
json: 'application/json',
png: 'image/png',
txt: 'text/plain'
};
function sendFile(
response: ServerResponse,
path: string,
relativeTo: string = webroot
) {
path = normalize(`./${path}`);
const fsPath = join(relativeTo, path);
const relPath = relative(relativeTo, fsPath);
if (!relPath || relPath.startsWith('..') || isAbsolute(relPath)) {
sendError(response, 'Bad request', 400);
return;
}
try {
const stream = createReadStream(fsPath);
let responseDead = false;
stream.on('error', (err) => {
responseDead = true;
logger.error(`Error in WebUI stream ${err.message}`);
sendError(response, 'Not found', 404);
});
const pathSplit = path.split('.');
const ext = pathSplit[pathSplit.length - 1].toLowerCase();
if (responseDead) {
return;
}
response.setHeader(
'Content-Type',
contentTypeMap[ext] ?? contentTypeMap.txt
);
stream.on('end', () => response.end());
stream.pipe(response);
} catch (error: unknown) {
logger.error(`Error in WebUI ${(error as Error).message}`);
sendError(response, 'Internal server error');
}
}
function sendError(response: ServerResponse, data: string, statusCode = 500) {
response.statusCode = statusCode;
response.setHeader('Content-Type', contentTypeMap.txt);
response.write(data);
response.end();
}
function sendJSON(response: ServerResponse, data: any) {
response.setHeader('Content-Type', contentTypeMap.json);
response.write(JSON.stringify(data));
response.end();
}
function sendConfig(response: ServerResponse) {
sendJSON(response, config);
}
function handleAPI(
request: IncomingMessage,
response: ServerResponse,
urlComponents: string[]
) {
if (urlComponents.length < 2) {
sendError(response, 'No API route specified', 400);
return;
}
switch (urlComponents[1]) {
case 'config':
if (request.method === 'PUT') {
const data: string[] = [];
request.on('data', (chunk) => {
data.push(chunk);
});
request.on('end', () => {
// We ignore errors, client just sent wrong data...
try {
setConfig(JSON.parse(data.join('')));
updateStores();
} catch {}
sendConfig(response);
});
return;
}
sendConfig(response);
return;
case 'stores':
sendJSON(response, Array.from(storeList.keys()));
return;
case 'brands':
sendJSON(response, getAllBrands());
return;
case 'series':
sendJSON(response, getAllSeries());
return;
case 'models':
sendJSON(response, getAllModels());
return;
case 'screenshots':
if (urlComponents.length >= 3) {
const timeStamp = urlComponents[2];
if (/\D/.test(timeStamp)) {
sendError(response, 'Invalid screenshot timestamp', 400);
return;
}
sendFile(response, `../success-${timeStamp}.png`);
return;
}
readdir(approot, (error, files) => {
if (error) {
sendError(response, error.message);
return;
}
const result = [];
for (const file of files) {
const match = /^success-(\d+)\.png$/.exec(file);
if (!match) {
continue;
}
result.push(match[1]);
}
sendJSON(response, result);
});
return;
default:
sendError(response, 'No API route found for path', 400);
}
}
function requestListener(request: IncomingMessage, response: ServerResponse) {
const url = request.url!;
const urlComponents = url.slice(1).split('/'); // Remove the leading /
switch (urlComponents[0]) {
case 'api':
handleAPI(request, response, urlComponents);
break;
default:
sendFile(response, url === '/' ? '/index.html' : url);
break;
}
}
let server: Server | undefined;
export async function startAPIServer() {
await stopAPIServer();
if (process.env.WEB_PORT) {
server = createServer(requestListener);
server.listen(Number(process.env.WEB_PORT));
}
}
export async function stopAPIServer() {
return new Promise((resolve) => {
if (server) {
server.close(resolve);
server = undefined;
return;
}
resolve(null);
});
}