This repository has been archived by the owner on May 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcardserver.js
executable file
·85 lines (66 loc) · 2.32 KB
/
cardserver.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
#!/usr/bin/env node
const express = require('express')
const puppeteer = require('puppeteer')
const fs = require('fs')
const path = require('path')
const port = process.env.PORT || 9100
const width = 1200
const height = 630
const maxage = 60 * 60 * 24 * 7
;(async () => {
const app = express()
const browser = await puppeteer.launch({
args: [
'--disable-accelerated-2d-canvas',
'--disable-dev-shm-usage',
'--disable-gpu',
'--disable-setuid-sandbox',
'--no-first-run',
'--no-sandbox',
'--no-zygote',
'--single-process',
],
headless: true,
})
app.enable('trust proxy')
app.get(/^\/(.*)\.png$/, async (req, res) => {
const host = req.hostname.replace('cards.', '')
const url = `${req.protocol}://${host}/${req.params[0]}`
const imagePath = `/tmp/cards/${host}/${req.params[0].replace('cards/', '')}.png`
const imageExpired = !fs.existsSync(imagePath) || Date.parse(fs.statSync(imagePath).mtime) < new Date - maxage * 1000
console.log(url + '.png')
let image
if (imageExpired) {
const page = await browser.newPage()
await page.setViewport({ width, height })
try {
const result = await page.goto(url)
await page.evaluateHandle('document.fonts.ready')
if (result.ok()) {
fs.mkdirSync(path.dirname(imagePath), { recursive: true })
image = await page.screenshot({ path: imagePath })
}
res.status(result.status())
} catch (err) {
res.status(502)
}
page.close()
} else {
image = fs.readFileSync(imagePath)
}
if (image) {
res.header('Cache-Control', 'public, max-age=' + maxage)
res.header('Content-Type', 'image/png')
res.header('Expires', new Date(Date.now() + maxage * 1000).toUTCString())
}
return res.send(image)
})
if (app.listen(port)) {
console.log('Card server started on port ' + port)
} else {
console.log('Error starting card server on port ' + port)
}
process.on('exit', async () => {
await browser.close()
})
})()