-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathServer.js
342 lines (330 loc) · 9.61 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
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { CONTENT_TYPE } from "https://js.sabae.cc/CONTENT_TYPE.js";
import { UUID } from "https://js.sabae.cc/UUID.js";
import { getExtension } from "https://js.sabae.cc/getExtension.js";
import { parseURL } from "https://js.sabae.cc/parseURL.js";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { DateTime } from "https://js.sabae.cc/DateTime.js";
const getFileNameFromDate = () => {
const d = new Date();
const fix0 = (n) => n < 10 ? "0" + n : n.toString();
const ymd = d.getFullYear() + fix0(d.getMonth() + 1) + fix0(d.getDate());
return ymd + "/" + UUID.generate();
};
const DENO_BUF_SIZE = 32 * 1024;
const readFilePartial = async (fn, offset, len) => {
const f = await Deno.open(fn);
//console.log(fn, offset, len);
await Deno.seek(f.rid, offset, Deno.SeekMode.Start);
const buf = new Uint8Array(len);
const rbuf = new Uint8Array(DENO_BUF_SIZE);
let off = 0;
for (;;) {
const rlen = await Deno.read(f.rid, rbuf);
for (let i = 0; i < rlen; i++) {
buf[off + i] = rbuf[i];
}
//console.log(off, rlen);
off += rlen;
len -= rlen;
if (len == 0) {
break;
}
}
await Deno.close(f.rid);
return buf;
};
const RANGE_LEN = 1024 * 1024 * 10;
const readFileRange = async (fn, range) => {
let gzip = true;
let data = null;
let range0 = 0;
let range1 = RANGE_LEN - 1;
if (range) {
range0 = parseInt(range[0]);
if (range[1] != "") {
range1 = parseInt(range[1]);
} else {
range1 += range0;
}
}
let flen = 0;
try {
/* // unsupported gzip & range request
//data = Deno.readFileSync(fn + ".gz");
flen = (await Deno.stat(fn + ".gz")).size;
if (range1 >= flen) {
range1 = flen - 1;
}
data = await readFilePartial(fn + ".gz", range0, range1 - range0 + 1);
*/
flen = (await Deno.stat(fn + ".gz")).size;
if (flen < RANGE_LEN) {
data = await Deno.readFile(fn + ".gz");
return [data, data.length, gzip];
}
} catch (e) {
}
gzip = false;
flen = (await Deno.stat(fn)).size;
if (range1 >= flen) {
range1 = flen - 1;
}
data = await readFilePartial(fn, range0, range1 - range0 + 1);
return [data, flen, gzip];
};
let logpath = null;
{
logpath = Deno.env.get("SERVER_LOG_PATH");
if (logpath && !logpath.endsWith("/")) {
logpath += "/";
}
}
class Server {
constructor(port) {
this.start(port);
}
async handleApi(req) {
//const url = req.url;
const path = req.path;
if (req.method === "OPTIONS") {
const res = "ok";
return new Response(JSON.stringify(res), {
status: 200,
headers: new Headers({
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Accept",
// "Access-Control-Allow-Methods": "PUT, DELETE, PATCH",
})
});
}
try {
const json = await (async () => {
if (req.method === "POST") {
return await req.json();
} else if (req.method == "DELETE") {
return null; // no requets
} else if (req.method === "GET") {
const n = req.url.indexOf("?");
const sjson = decodeURIComponent(req.url.substring(n + 1));
try {
return JSON.parse(sjson);
} catch (e) {
return sjson;
}
}
return null;
})();
//console.log("[req api]", json);
const res = await this.api(path, json, req.remoteAddr, req);
if (res instanceof Response) {
return res;
}
//console.log("[res api]", res);
return new Response(JSON.stringify(res), {
status: 200,
headers: new Headers({
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Accept", // must
//"Access-Control-Allow-Methods": "PUT, DELETE, PATCH",
})
});
} catch (e) {
this.err(e);
}
return null;
};
async handleData(req) {
//const url = req.url;
const path = req.path;
try {
if (req.method === "POST") {
const ext = getExtension(path, ".jpg");
const bin = new Uint8Array(await req.arrayBuffer());
//console.log("[req data]", bin.length);
const fn = getFileNameFromDate();
const name = fn + ext;
try {
Deno.mkdirSync("data");
} catch (e) {
}
try {
const dir = name.substring(0, name.lastIndexOf("/"));
Deno.mkdirSync("data/" + dir);
} catch (e) {
}
Deno.writeFileSync("data/" + name, bin);
const res = { name };
//console.log("[data res]", res);
return new Response(JSON.stringify(res), {
status: 200,
headers: new Headers({
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type, Accept", // must
//"Access-Control-Allow-Methods": "PUT, DELETE, PATCH",
})
});
} else if (req.method === "GET" || req.method === "HEAD") {
const fn = path;
if (fn.indexOf("..") >= 0) {
throw new Error("illegal filename");
}
const n = fn.lastIndexOf(".");
const ext = n < 0 ? "html" : fn.substring(n + 1);
const data = Deno.readFileSync("." + fn);
const ctype = CONTENT_TYPE[ext] || "text/plain";
return new Response(req.method === "HEAD" ? null : data, {
status: 200,
headers: new Headers({
"Content-Type": ctype,
"Access-Control-Allow-Origin": "*",
"Content-Length": data.length,
}),
});
}
} catch (e) {
//console.log("err", e.stack);
}
}
async handleWeb(req) {
//const url = req.url;
const path = req.path;
try {
//console.log(path, req.headers);
const getRange = (req) => {
const range = req.headers.get("Range");
if (!range || !range.startsWith("bytes=")) {
return null;
}
const res = range.substring(6).split("-");
if (res.length === 0) {
return null;
}
return res;
};
let range = getRange(req);
const calcPath = (path) => {
if (path === "/" || path.indexOf("..") >= 0) {
return "/index.html";
}
if (path.endsWith("/")) {
return path + "index.html";
}
return path;
};
const fn = calcPath(path);
const n = fn.lastIndexOf(".");
const ext = n < 0 ? "html" : fn.substring(n + 1);
const [data, totallen, gzip] = await readFileRange("static" + fn, range);
if (!range) {
if (data.length != totallen) {
range = [0, data.length - 1];
}
} else if (range[1] == "") {
range[1] = parseInt(range[0]) + data.length - 1;
}
const ctype = CONTENT_TYPE[ext] || "text/plain";
const headers = {
"Content-Type": ctype,
"Accept-Ranges": "bytes",
"Content-Length": data.length,
};
if (gzip) {
headers["Content-Encoding"] = "gzip";
}
if (totallen == data.length) {
range = null;
}
if (range) {
headers["Content-Range"] = "bytes " + range[0] + "-" + range[1] +
"/" + totallen;
}
return new Response(data, {
status: range ? 206 : 200,
headers: new Headers(headers),
});
} catch (e) {
if (path !== "/favicon.ico") {
//console.log("err", path, e.stack);
}
}
}
async start(port) {
console.log(`http://localhost:${port}/`);
const hostname = "[::]"; // for IPv6
const addr = hostname + ":" + port;
serve(async (req, conn) => {
const remoteAddr = conn.remoteAddr.hostname;
//console.log("remoteAddr", remoteAddr);
try {
const url = req.url;
const purl = parseURL(url);
if (purl) {
req.path = purl.path;
req.query = purl.query;
req.host = purl.host;
req.port = purl.port;
req.remoteAddr = remoteAddr;
const path = req.path;
await this.log(req);
if (path.startsWith("/api/")) {
const resd = await this.handleApi(req);
if (resd) {
return resd;
}
} else if (path.startsWith("/data/")) {
const resd = await this.handleData(req);
if (resd) {
return resd;
}
}
const resd = await this.handleWeb(req);
if (resd) {
return resd;
}
}
return await this.handleNotFound(req);
} catch (e) {
this.err(e);
}
}, { addr });
}
// log
async log(req) { //
/*
req.path = purl.path;
req.query = purl.query;
req.host = purl.host;
req.port = purl.port;
req.remoteAddr = remoteAddr;
*/
if (logpath) {
const dt = new DateTime();
const fn = logpath + dt.day.toStringYMD() + ".log";
const s = dt.toString() + "\t" + req.path + "\t" + req.remoteAddr + "\n";
await Deno.writeTextFile(fn, s, { append: true });
}
}
// err
err(e) {
console.log("err", e.stack);
}
// not found
async handleNotFound(req) { // to override
const err = new TextEncoder().encode("not found");
return new Response(err);
}
// Web API
async api(path, req, remoteAddr) { // to override
return req;
}
}
export { Server };
/*
if (Deno. run script name? .endsWith("/Server.js")) {
const port = parseInt(Deno.args[0]);
new Server(port);
}
*/