-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathindex.js
233 lines (226 loc) · 8.07 KB
/
index.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
const swaggerUi = require('swagger-ui-express')
let swaggerOnly = process.argv.includes('--swagger-only')
let puppeteer
try {
puppeteer = swaggerOnly ? {
launch: (...args) => {
log('[PuPsIm]', ...args)
return {
newPage: (...args) => {
log('[PuPsIm]', ...args)
return {
goto: (...args) => log('[PuPsIm]', ...args),
screenshot: (...args) => log('[PuPsIm]', ...args),
evaluate: (...args) => log('[PuPsIm]', ...args),
on: (...args) => log('[PuPsIm]', ...args)
}
},
close: () => {}
}
}
} : require('puppeteer')
} catch (e) {
console.log("\033[31mTry adding '--swagger-only' option for testing or 'npm install puppeteer' instead\033[0m", e)
}
const fetch = require('node-fetch')
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
const CONSTANT = {
mimetype: {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
webp: 'image/webp',
'image/png': 'image/png',
'image/jpg': 'image/jpeg',
'image/jpeg': 'image/jpeg',
'image/webp': 'image/webl'
}
}
const app = express()
.use(express.static(path.join(__dirname, 'public')))
.use((req, res, next) => {
if (req.url === '/swagger.json') res.sendFile(path.join(__dirname, 'swagger.json'))
else next()
})
.use(express.text())
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('index'))
.get('/api/ssweb', async (req, res) => {
try {
let {
url,
full,
delay,
type
} = {
url: '',
full: false,
delay: 0,
type: 'png',
...req.query
}
type = type.toLowerCase()
if (!type in CONSTANT.mimetype) type = 'png'
if (url) {
const browser = await getBrowser()
const page = await browser.newPage()
await page.goto(url, {
waitUntil: 'load',
timeout: 300000
})
if (delay > 0) await sleep(delay)
const screenshot = swaggerOnly ? Buffer.from(type) : await page.screenshot({
type,
fullPage: full ? full != 'false' : false
})
await browser.close()
res.writeHead(200, {
'Content-Type': CONSTANT.mimetype[type],
'Content-Length': screenshot.length
})
res.end(screenshot)
} else {
res.status(400).json({
error: 'parameter \'url\' not provided',
hint: '/api/ssweb?url=http://example.com',
status: 400
})
}
} catch (e) {
res.status(501).json({
error: e.toString(),
status: 501
})
}
})
.post('/api/canvas', async (req, res) => {
let timeout
try {
let {
apikey,
type,
quality
} = {
type: 'png',
quality: 0.92,
...req.query
}
let code = req.body
if (process.env.API_KEY && process.env.API_KEY != apikey) return res.json({
result: 'apikey invalid'
})
type = type.toLowerCase()
quality = Math.max(0, Math.min(quality, 1))
const mimetype = CONSTANT.mimetype[type] || CONSTANT.mimetype.png
log(type, quality, mimetype, req.query)
const browser = await getBrowser()
const page = await browser.newPage()
page.on('console', l => log('[CHROME]', l._type, l._text))
code = `try{\n${code}\n} catch (e) {\n console.error(e.toString())\n}`
log(code)
timeout = setTimeout(() => {
log('timed out')
browser.close()
res.status(201).json({
error: 'Timeout limit exceeded',
status: 201
})
}, 24000)
await page.exposeFunction('nodeFetch', fetch)
await page.exposeFunction('loadToDataURI', async function(url) {
let res = await fetch(url)
let buf = await res.buffer()
return buf.toString('base64')
})
const base64 = await page.evaluate(async function(code, mimetype, quality) {
try {
let c = document.createElement('canvas')
let ctx = c.getContext('2d')
function loadImg(url) {
return new Promise(resolve => {
let img = new Image()
img.crossOrigin = "Anonymous"
img.src = url
img.onload = () => resolve(img)
})
}
await (new(async () => {}).constructor('c', 'ctx', 'Image', 'loadImg', code))(c, ctx, Image, loadImg)
return (/png/.test(mimetype) ? c.toDataURL(mimetype) : c.toDataURL(mimetype, quality)).split `,` [1]
} catch (e) {
return e.toString()
}
}, code, mimetype, quality)
if (/error\:/i.test(base64)) throw base64
clearTimeout(timeout)
await browser.close()
const image = swaggerOnly ? Buffer.from(type) : Buffer.from(base64, 'base64')
log(image)
if (res.headersSent) return
res.writeHead(200, {
'Content-Type': mimetype,
'Content-Length': image.length
})
res.end(image)
} catch (e) {
clearTimeout(timeout)
res.status(501).json({
error: e.toString(),
status: 501
})
}
})
.use('/api', swaggerUi.serve)
.get('/api', swaggerUi.setup(null, false, options = {
validatorUrl: null,
docExpansion: 'full',
operationsSorter: function(a, b) {
var score = {
'/api/ssweb': 1,
'/api/canvas': 2,
}
// console.log('a', a.get("path"), b.get("path"))
return score[a.get("path")] < score[b.get("path")]
}
}, '.swagger-ui .topbar { background-color: #0099FF }', null, '/swagger.json'))
.get('*', function(req, res) {
res.status(404).json({
error: 'Page you are looking for is not found',
hint: '/',
status: 404
})
})
.listen(PORT, () => console.log(`Listening on ${ PORT }`))
const io = require('socket.io')(app)
//listen on every connection
io.on('connection', socket => {
socket.on('memoryUsage', () => socket.emit('memoryUsage', process.memoryUsage()))
})
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function getBrowser(opts = {}) {
const chromeOptions = {
headless: true,
defaultViewport: {
width: 1920,
height: 1080
},
timeout: 120000,
args: [
"--incognito",
"--no-sandbox",
"--single-process",
"--no-zygote",
"--no-cache"
],
...opts
}
log('Launching Browser')
return await puppeteer.launch(chromeOptions)
}
function log(...args) {
console.log('\033[42mLOG\033[49m \033[33m%s\033[39m\n', new Date(), ...args)
}