Spaces:
Running
Running
Create index.js
Browse files
index.js
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
for (let condition of ['unhandledRejection', 'uncaughtException'])
|
2 |
+
process.on(condition, console.error)
|
3 |
+
|
4 |
+
const morgan = require('morgan')
|
5 |
+
const express = require('express')
|
6 |
+
const puppeteer = require('puppeteer')
|
7 |
+
|
8 |
+
const cache = new Map()
|
9 |
+
|
10 |
+
const app = express()
|
11 |
+
app.set('json spaces', 4)
|
12 |
+
app.use(morgan('dev'))
|
13 |
+
app.use(async (_, __, next) => {
|
14 |
+
for (let [url, data] of cache) {
|
15 |
+
const timeReset = 10 * 60 * 1000 // 10 min
|
16 |
+
if (Date.now() - data.lastFetch > timeReset) {
|
17 |
+
// await data.close()
|
18 |
+
cache.delete(url)
|
19 |
+
}
|
20 |
+
}
|
21 |
+
next()
|
22 |
+
})
|
23 |
+
|
24 |
+
app.all('/', (_, res) => {
|
25 |
+
res.json({
|
26 |
+
creator: '@rippanteq7',
|
27 |
+
message: 'Hello World',
|
28 |
+
uptime: new Date(process.uptime() * 1000).toUTCString().split(' ')[4]
|
29 |
+
})
|
30 |
+
})
|
31 |
+
|
32 |
+
app.get('/api', async (req, res) => {
|
33 |
+
try {
|
34 |
+
const { url } = req.query
|
35 |
+
if (!url) return res.json({ success: false, message: 'Input parameter url' })
|
36 |
+
if (!/https?:\/\//.test(url)) return res.json({ success: false, message: 'Invalid url' })
|
37 |
+
|
38 |
+
const data = cache.has(url) ? cache.get(url) : await ssyoutube(url)
|
39 |
+
|
40 |
+
data.message ?
|
41 |
+
res.json({ success: false, message: data.message, result: data }) :
|
42 |
+
res.json({ success: true, result: data })
|
43 |
+
} catch (e) {
|
44 |
+
console.log(e)
|
45 |
+
e = String(e)
|
46 |
+
res.json({
|
47 |
+
error: true,
|
48 |
+
message: e === '[object Object]' ? 'Internal Server Error' : e
|
49 |
+
})
|
50 |
+
}
|
51 |
+
})
|
52 |
+
|
53 |
+
const PORT = process.env.PORT || 7860
|
54 |
+
app.listen(PORT, () => console.log('App running on port', PORT))
|
55 |
+
|
56 |
+
async function ssyoutube(url) {
|
57 |
+
const browser = await puppeteer.launch({
|
58 |
+
headless: 'new',
|
59 |
+
executablePath: puppeteer.executablePath(),
|
60 |
+
args: ['--no-sandbox']
|
61 |
+
})
|
62 |
+
|
63 |
+
const page = await browser.newPage()
|
64 |
+
|
65 |
+
await page.goto('https://ssyoutube.com/')
|
66 |
+
await page.type('#id_url', url)
|
67 |
+
await page.click('#search')
|
68 |
+
|
69 |
+
const response = await page.waitForResponse(res =>
|
70 |
+
res.url().includes('convert') && res.request().method() === 'POST')
|
71 |
+
|
72 |
+
const json = await response.json()
|
73 |
+
cache.set(url, Object.assign(json, { lastFetch: Date.now() }))
|
74 |
+
await browser.close()
|
75 |
+
|
76 |
+
return json
|
77 |
+
}
|