-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
377 lines (310 loc) · 11.6 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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
let express = require('express');
let cors = require('cors');
let multer = require('multer');
let fs = require("fs");
let url = require("url");
const puppeteerExtra = require('puppeteer-extra');
const Stealth = require('puppeteer-extra-plugin-stealth');
let pages = {}
puppeteerExtra.use(Stealth());
let upload = multer({dest: "uploads/"});
let type = upload.any('file');
let app = express();
let {default: puppeteer,executablePath} = require('puppeteer');
let browser
(async _ => {
browser = await puppeteer.launch({
headless: 'new',
timeout: 0,
executablePath: executablePath(),
})
})()
async function wait({selector,func,timeout = 0} = {}) {
timeout = timeout > 0 ? timeout : 0
let result
let selected
let functionObject = {
func: null,
delay: 100
}
async function waitForSelector(selector) {
if(typeof selector != "string") return
return new Promise((resolve,reject) => {
let timeoutCallBack
if(timeout) timeoutCallBack = setTimeout(_ => {
reject(`timeout (${timeout}ms)`)
},timeout)
let result
let check = _ => {
result = document.querySelectorAll(selector)
if(result && result.length > 0) return true
}
if (check()) {
clearTimeout(timeoutCallBack)
resolve(result)
}
const observer = new MutationObserver(mutations => {
if (check()) {
observer.disconnect();
clearTimeout(timeoutCallBack)
resolve(result);
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
async function waitForCondition() {
let {func,delay} = functionObject
return new Promise((res,reject) => {
let timeoutCallBack
let interval = setInterval(_ => {
let testResult = func({
selected
})
if(testResult) {
clearInterval(interval)
clearTimeout(timeoutCallBack)
res(testResult)
}
},delay)
if(timeout) timeoutCallBack = setTimeout(_ => {
clearInterval(interval)
reject(`timeout (${timeout}ms)`)
},timeout)
})
}
function runFunc() {
if(typeof func == "function") functionObject.func = func
else functionObject = {...functionObject,...func}
return waitForCondition()
}
let type = typeof arguments[0]
if(type != "object") {
if(type == "string") return waitForSelector(arguments[0])
if(type == "function") {
functionObject.func = arguments[0]
return waitForCondition()
}
}
if(selector != null) {
selected = await waitForSelector(selector)
result = selected
}
if(func != null) result = {
functionResult: await runFunc(),
selected
}
return result
}
function sleep(ms) {
return new Promise((resolve, rejectect) => {
setTimeout(_ => resolve("sleeped for " + ms),ms)
})
}
function getFile({fileName,mime,convert}) {
let results = []
files.forEach(file => {
let {originalname,mimetype} = file.fileInfo
let [nature,format] = mimetype.split('/')
if(
fileName == originalname ||
mime && (mime == mimetype || mime.split('/').some(x => x == nature || x == format)) ||
fileName == undefined && mime == undefined
) {
results.push(file)
}
})
if(typeof convert == "string" || Array.isArray(convert)) {
if(typeof convert == "string") convert = [convert]
results = results.map(file => {
let {buffer,base64} = file
let {originalname,mimetype} = file.fileInfo
buffer = new Uint8Array(buffer.data).buffer;
if(convert.some(type => type.toLowerCase() == "dataurl")) file.dataURL = `data:${mimetype};base64,${base64}`
if(convert.some(type => type.toLowerCase() == "file")) file.File = new File([buffer],originalname,{type: mimetype})
if(convert.some(type => type.toLowerCase() == "blob")) file.Blob = new Blob([buffer],{type: mimetype})
return file
})
}
return results
}
async function read(file,type) {
let reader = new FileReader
let readHash = {
"buffer": "readAsArrayBuffer",
"binary": "readAsBinaryString",
"dataurl": "readAsDataURL",
"text": "readAsText"
}
let readType = readHash[type.toLowerCase()]
if(!readType) return Error(`${type} isn't an available type`)
reader[readType](file)
return new Promise((res) => {
reader.addEventListener("load",_ => {
res(reader.result)
})
})
}
async function evaluateScripts(url,id,scripts,files) {
if(browser == undefined) return {}
async function getPage() {
if(id && pages[id]) return pages[id]
if(url == 'undefind' || url == '') return
let page = await browser.newPage()
return {page,id: crypto.randomUUID(),expireTime: 0}
}
let pageObject = await getPage()
try {
await Promise.race([
pageObject.page.goto(url, {timeout: 0}),
pageObject.page.waitForSelector("html")
])
} catch(err) {}
let lastResult
if(scripts) {
try {
let scriptResult
for(let [index,script] of scripts.entries()) {
let evalScript = `_ => {
return new Promise(async res => {
try {
let script = eval(${script});
let wait = eval(${wait.toString()});
let sleep = eval(${sleep.toString()});
let getFile = eval(${getFile.toString()});
let readFile = eval(${read.toString()});
let lastResult = ${lastResult != undefined ? `JSON.parse(${lastResult})` : `undefined`}
let pageId = '${pageObject.id}'
let gotoUrl = url => {
res({
type: "goto",
url
})
};
let changeExpireTime = (time = 1000 * 60) => {
if(typeof time != 'number') return
res({
type: "changeExpireTime",
time
})
}
let puppeteerClick = (x,y) => res({type: "click",x,y})
let puppeteerInputFile = (file,input) => {
let filePath = file.fileInfo.path
input.dataset.file = filePath.replace(/uploads\\\\/,'')
res({type: "inputFile",file})
}
let files = (${JSON.stringify(files)})
let scriptResult = await script({gotoUrl,wait,sleep,getFile,readFile,puppeteerClick,puppeteerInputFile,changeExpireTime})
res(scriptResult)
} catch(_e) {
console.error(_e)
res({
type:"error",
message:_e.toString()
})
}
})
}`
let func = eval(evalScript)
scriptResult = await pageObject.page.evaluate(func)
if(scriptResult?.type == "goto" && scriptResult.url) {
let gotoPromise = pageObject.page.goto(scriptResult.url, {timeout: 0})
await Promise.race([
gotoPromise,
pageObject.page.waitForSelector("html")
])
return
}
if(scriptResult?.type == "click") {
let {x,y} = scriptResult
await pageObject.page.mouse.click(x || 0,y || 0)
}
if(scriptResult?.type == "changeExpireTime") {
let {time} = scriptResult
if(typeof time != 'number') return
pageObject.expireTime = time
}
if(scriptResult?.type == "inputFile") {
let {file} = scriptResult
let filePath = file.fileInfo.path
let input = await pageObject.page.$(`input[type=file][data-file="${filePath.replace(/uploads\\/,'')}"]`);
let inputingPromise = input.uploadFile(filePath)
await Promise.race([
inputingPromise,
pageObject.page.waitForSelector("html")
])
await sleep(1000)
}
if(scriptResult?.type == "error") {
lastResult = JSON.stringify({
generalType: "error",
type: "borwser error",
message: scriptResult?.message ?? "unknown error"
})
break
}
}
if(scriptResult != undefined) lastResult = JSON.stringify(scriptResult);
else lastResult = scriptResult
} catch(_e) {
lastResult = JSON.stringify({
generalType: "error",
type: "server error",
message: _e
})
}
}
if(pageObject.expireTime == 0) await pageObject.page.close()
else {
timeoutCall = setTimeout(_ => pageObject.page.close(),pageObject.expireTime)
pages[pageObject.id] = pageObject
}
return lastResult
};
app.use(cors())
app.use(express.json({type: ["text/plain","application/json"]}))
app.use(express.urlencoded({ extended: true }));
app.use(type);
app.use(express.static('public'));
app.all("*",ServerFunction)
app.listen(2400)
async function ServerFunction(req,res) {
if(browser == undefined) res.end("failed to get the content")
let urlParem = new URL(req.url,req.headers.origin).pathname.slice(1)
let id = req.query.id
if(urlParem == undefined) return res.end("url not found")
let {scripts,script} = req.body
let scriptsArray = []
let files = req.files?.map(file => {
let {path} = file
let buffer = fs.readFileSync(path)
let base64 = buffer.toString("base64")
return {
fileInfo:file,
buffer,
base64
}
})
if(scripts) {
scriptsArray.push(...eval(`[${scripts}]`))
}
if(script) {
if(typeof script == "string") scriptsArray.push(script)
else scriptsArray.push(...script)
}
if(Array.isArray(req.body)) {
scriptsArray.push(...req.body)
}
scriptsArray = scriptsArray.map(script => eval(script))
let scriptResult = await evaluateScripts(urlParem,id,scriptsArray,files);
req?.files?.forEach(file => {
let {path} = file
fs.rmSync(path)
})
if(scriptResult != undefined) res.end(scriptResult)
else res.end(JSON.stringify({}))
}