-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
252 lines (206 loc) · 6.04 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
const puppeteer = require('puppeteer-extra')
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
const flags = [
`--disable-accelerated-2d-canvas`,
`--no-first-run`,
`--disable-setuid-sandbox`,
`--no-zygote`,
`--disable-gpu`,
`--start-maximized`,
`--disable-notifications`,
`--disable-translate`,
`--ignore-certificate-errors`,
`--disable-popup-blocking`,
`--no-sandbox`,
`--disable-dev-shm-usage`,
`--blink-settings=imagesEnabled=false`,
`--disable-blink-features=AutomationControlled`,
`--disable-gl-drawing-for-tests`,
'--disable-background-timer-throttling',
'--disable-backgrounding-occluded-windows',
'--disable-breakpad',
'--disable-component-extensions-with-background-pages',
'--disable-extensions',
'--disable-features=TranslateUI',
'--disable-sync',
'--metrics-recording-only',
'--mute-audio',
'--safebrowsing-disable-auto-update',
]
const defaultCacheDuration = {
document: 0,
script: 600,
stylesheet: 600
};
const maxTimeout = 10;
const cache = {};
let result = {}
let options = {}
let page = null
let api_key = null
async function parseTranscript(page) {
await page.waitForSelector('#segments-container');
return page.evaluate(() => {
return Array.from(document.querySelectorAll('#segments-container yt-formatted-string')).map(element => element.textContent?.trim());
});
}
function blockedResource(resourceURL, type) {
const blockedDomains = [
'www.google-analytics.com',
'connect.facebook.net',
'googlevideo.com',
'googleads.g.doubleclick.net',
'www.googletagmanager.com',
'www.googletagservices.com',
'fonts.googleapis.com',
'fonts.gstatic.com',
'adservice.google.co'
]
const blockedTypes = [
'media',
'font',
'image'
]
let resourceUrlObject = ''
try {
resourceUrlObject = new URL(resourceURL)
} catch {
return true
}
const resourceHostName = resourceUrlObject.hostname
if (resourceURL.match(/\.(woff2|woff|mp3|mp4|jpg|png|gif|avi|flv|mov|wmv|svg)$/i)) {
return true
}
if(blockedTypes.includes(type)) {
return true
}
let isBlocked = false;
for (const blockedDomain of blockedDomains) {
if (resourceHostName.includes(blockedDomain)) {
isBlocked = true;
break;
}
}
if (isBlocked) {
return true
}
return false
}
exports.run = async(req, res) => {
options = req.body
api_key = options.api_key
result = {
bytes: 0,
error: null,
transcript: null
}
if (api_key == process.env.API_KEY) {
puppeteer.use(StealthPlugin())
if(options.proxy) {
flags.push(`--proxy-server=${options.proxy.server}`)
}
const browser = await puppeteer.launch({
headless: "new",
ignoreDefaultArgs: ["--enable-automation"],
args: flags
});
page = await browser.newPage();
if(options.proxy) {
await page.authenticate({
username: options.proxy.username,
password: options.proxy.password,
})
}
if (options.user_agent) {
await page.setUserAgent(options.user_agent.trim())
}
await page.setRequestInterception(true)
page.on('request', async (interceptedRequest) => {
let type = interceptedRequest.resourceType()
let url = interceptedRequest.url()
if (blockedResource(url, type)) {
interceptedRequest.abort()
}
else {
if (cache[url] && cache[url].expires > Date.now() && !url.includes('www.elon.se')) {
try {
await interceptedRequest.respond(cache[url]);
return;
} catch {}
}
interceptedRequest.continue()
}
})
page.on('response', async (response) => {
const url = response.url();
const resourceType = response.request().resourceType();
const headers = response.headers();
// Use Cache-Control max-age if available
const cacheControl = headers['cache-control'] || '';
const maxAgeMatch = cacheControl.match(/max-age=(\d+)/);
let maxAge = maxAgeMatch && maxAgeMatch.length > 1 ? parseInt(maxAgeMatch[1], 10) : 0;
// If max-age is not available, use a default cache duration
if (!maxAge) {
maxAge = defaultCacheDuration[resourceType] || 60;
}
// Check cache for existing entry
if (cache[url] && cache[url].expires > Date.now()) {
// Revalidate with ETag or Last-Modified if present
const etag = headers['etag'];
const lastModified = headers['last-modified'];
if ((etag && cache[url].etag === etag) || (lastModified && cache[url].lastModified === lastModified)) {
return; // Cached data is still valid
}
}
let buffer;
try {
buffer = await response.buffer();
} catch {
// Response does not have a buffer
return;
}
// Cache the response
cache[url] = {
status: response.status(),
headers: headers,
body: buffer,
expires: Date.now() + (maxAge * 1000),
etag: headers['etag'], // Store ETag
lastModified: headers['last-modified'] // Store Last-Modified
};
try {
let length = response.headers()['content-length']
if (length) {
result.bytes += Number(length)
}
} catch {}
})
try {
await page.goto(options.url, { waitUntil: 'domcontentloaded' });
await page.evaluate(() => {
document.querySelector('button[aria-label*=cookies]')?.click()
});
await page.waitForSelector("ytd-video-description-transcript-section-renderer button", {
timeout: maxTimeout * 1000
})
await page.evaluate(() => {
document.querySelector('ytd-video-description-transcript-section-renderer button').click()
})
result.transcript = await parseTranscript(page);
await page.close()
await browser.close()
res.status(200).json(
result
);
} catch(error) {
result.error = error
console.log(error)
await page.close()
await browser.close()
}
} else {
res.status(401).json(
{ error: "Unauthorized" }
)
}
}