-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
95 lines (84 loc) · 2.39 KB
/
server.js
File metadata and controls
95 lines (84 loc) · 2.39 KB
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
const fastify = require('fastify')({
logger: true
})
const crypto = require('node:crypto')
const fs = require('node:fs')
const path = require('node:path')
const qrcode = require('qrcode')
const replaceStream = require('replacestream')
const listenConfig = require('./listen_config.js')
fastify.register(require('@fastify/formbody'))
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public')
})
/* trivial mapping to A-Z0-5 */
const prefix_codes = new Uint8Array(8)
crypto.getRandomValues(prefix_codes)
const prefix = String.fromCharCode(... prefix_codes.map(n => { n >>= 3; return n + (n < 26 ? 97 : 22) }))
/* global! */
fastify.decorate('shouldExit', false)
function sendAndMaybeExit (path) {
return async (req, res) => {
await res.sendFile(path);
if (req.server.shouldExit) {
req.server.close(() => process.exit(1))
}
}
}
function sendAndShouldExit (path) {
return async (req, res) => {
await res.sendFile(path);
req.server.shouldExit = true;
}
}
fastify.get(`/${prefix}/`, async (req, res) => {
const stream = fs.createReadStream(
path.join(__dirname, 'public', 'text-drop.html'),
'utf8'
).pipe(replaceStream('%prefix%', prefix))
res.header('Content-Type', 'text/html')
await res.send(stream)
})
fastify.get(`/style.css`, sendAndMaybeExit('text-drop-style.css'))
fastify.get(`/${prefix}/succeeded`, sendAndShouldExit('text-drop-succeeded.html'))
fastify.get(`/${prefix}/failed`, sendAndShouldExit('text-drop-failed.html'))
fastify.route({
method: 'POST',
path: `/${prefix}/text-drop-process`,
handler: async (req, res) => {
const drop_path = path.join(__dirname, 'drops', `${new Date() .toISOString()}.txt`)
try {
fs.writeFileSync(drop_path, req.body.dropped_text);
} catch (err) {
fastify.log.error(`Could not write to ${drop_path}`)
await res.redirect(503, `/${prefix}/failed`);
}
await res.redirect(`/${prefix}/succeeded`);
}
})
fastify.listen({
host: listenConfig.host || '0.0.0.0',
port: listenConfig.port || 0,
bodyLimit: 200000,
listenTextResolver: address => {
return `Listening at ${address}/${prefix}/`
}
}, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
qrcode.toFile(
path.join(__dirname, 'private', 'qr_url.png'),
`${address}/${prefix}/`,
function (err) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
else {
fastify.log.info('qr code written to disk')
}
}
)
})