Spaces:
Runtime error
Runtime error
File size: 17,803 Bytes
fb38ec5 | 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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | import { FastifyReply } from "fastify";
import { BrowserContext, Page, HTTPResponse } from "puppeteer-core";
import { CDPService } from "../../services/cdp/cdp.service.js";
import { SessionService } from "../../services/session.service.js";
import { ScrapeFormat } from "../../types/index.js";
import { getErrors } from "../../utils/errors.js";
import { updateLog } from "../../utils/logging.js";
import { IProxyServer } from "../../utils/proxy.js";
import {
cleanHtml,
getDefuddleContent,
htmlToMarkdown,
transformHtml,
} from "../../utils/scrape/index.js";
import { normalizeUrl } from "../../utils/url.js";
import { PDFRequest, ScrapeRequest, ScreenshotRequest, SearchRequest } from "./actions.schema.js";
import { DefuddleResponse } from "defuddle";
import pdf2html from "pdf2html";
import {
buildHtmlLikeMetadataFromPdf,
extractLinksFromConvertedHtml,
} from "../../utils/scrape/pdfToHtml.js";
import { safeGoto } from "../../utils/scrape/safeGoTo.js";
export const handleScrape = async (
sessionService: SessionService,
browserService: CDPService,
request: ScrapeRequest,
reply: FastifyReply,
) => {
const startTime = Date.now();
let times: Record<string, number> = {};
const { url, format, screenshot, pdf, proxyUrl, logUrl, delay } = request.body;
let proxy: IProxyServer | null = null;
let context: BrowserContext | null = null;
try {
if (proxyUrl) {
proxy = await sessionService.proxyFactory(proxyUrl);
await proxy.listen();
}
times.proxyTime = Date.now() - startTime;
let page: Page;
let response: HTTPResponse | null = null;
let pdfResponse: HTTPResponse | null = null;
let isPdfNavigation = false;
if (!browserService.isRunning()) {
await browserService.launch();
}
if (proxy) {
// If a proxy is used, we proceed with browser navigation; implementing proxy-aware Node fetch
// would require an HTTP agent and is outside current scope.
context = await browserService.createBrowserContext(proxy.url);
page = await context.newPage();
times.proxyPageTime = Date.now() - startTime - times.proxyTime;
} else {
page = await browserService.getPrimaryPage();
times.pageTime = Date.now() - startTime - times.proxyTime;
}
// PDF retrieval will use node fetch with session cookies; removed CDP tracking
let normalizedUrl: string | null = null;
if (url) {
normalizedUrl = normalizeUrl(url);
if (!normalizedUrl) {
throw new Error(`Invalid URL: ${url}`);
}
}
const safeResponse = normalizedUrl
? await safeGoto(page, normalizedUrl, {
timeout: 30000,
waitUntil: "domcontentloaded",
})
: { response: null, isPdf: false, pdfResponse: null };
response = safeResponse.response !== null ? safeResponse.response : safeResponse.pdfResponse;
pdfResponse = safeResponse.pdfResponse;
const isPdf = safeResponse.isPdf;
if (delay) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
const contentType = response?.headers()["content-type"]?.toLowerCase() || "";
let scrapeResponse: Record<string, any> = {};
let htmlContent = "";
let cleanedHtml: string;
let readabilityContent: DefuddleResponse;
if (isPdf || contentType.includes("application/pdf")) {
// Node fetch using session cookies (same browser auth state)
const targetUrl = normalizedUrl || url!;
const cookies = await page.cookies(targetUrl);
const cookieHeader = cookies.map((c) => `${c.name}=${c.value}`).join("; ");
const fetchHeaders: Record<string, string> = {};
if (cookieHeader) fetchHeaders["Cookie"] = cookieHeader;
if (!fetchHeaders["Referer"]) {
const u = new URL(targetUrl);
fetchHeaders["Referer"] = u.origin + "/";
}
const nodeRes = await fetch(targetUrl, {
method: "GET",
redirect: "follow",
headers: fetchHeaders,
});
const nodeCT = (nodeRes.headers.get("content-type") || "").toLowerCase();
if (!nodeRes.ok || !nodeCT.includes("application/pdf")) {
throw new Error(`Expected PDF; got status ${nodeRes.status} content-type ${nodeCT}`);
}
const arrBuf = await nodeRes.arrayBuffer();
const pdfBuffer = Buffer.from(arrBuf);
const convertStart = Date.now();
htmlContent = await pdf2html.html(pdfBuffer);
times.pdfHtmlConvertTime = Date.now() - convertStart;
const metaStart = Date.now();
const pdfMeta = await pdf2html.meta(pdfBuffer);
times.pdfMetaTime = Date.now() - metaStart;
const htmlMeta = buildHtmlLikeMetadataFromPdf(pdfMeta, {
urlSource: targetUrl,
statusCode: nodeRes.status,
htmlForFallback: htmlContent,
});
const htmlLinks = extractLinksFromConvertedHtml(htmlContent);
scrapeResponse = {
content: {},
metadata: {
...htmlMeta,
statusCode: nodeRes.status,
headers: Object.fromEntries(nodeRes.headers.entries()),
originalContentType: nodeCT,
pdfAcquisition: "node-fetch-with-cookies",
},
links: htmlLinks,
};
if (pdf) {
scrapeResponse.pdf = pdfBuffer.toString("base64");
}
} else {
// Regular HTML flow
await page.evaluate(() => {
(window as any).__name = (func: Function) => func;
});
const [{ html, metadata, links }, base64Screenshot, pdfBuffer] = await Promise.all([
page.evaluate(() => {
const getMetaContent = (selector: string) => {
const element = document.querySelector(selector);
return element ? element.getAttribute("content") : null;
};
const getMetaByName = (name: string) => getMetaContent(`meta[name="${name}"]`);
const getMetaByProperty = (property: string) =>
getMetaContent(`meta[property="${property}"]`);
const extractJsonLd = () => {
const scripts = document.querySelectorAll('script[type="application/ld+json"]');
const jsonLdData: any[] = [];
scripts.forEach((script) => {
try {
const data = JSON.parse(script.textContent || "");
jsonLdData.push(data);
} catch (e) {
console.error(e);
}
});
return jsonLdData;
};
return {
html: document.documentElement.outerHTML,
links: [...document.links].map((l) => ({
url: l.href,
text: l.textContent?.trim() || "",
})),
metadata: {
title: document.title,
language: document.documentElement.lang,
urlSource: window.location.href,
timestamp: new Date().toISOString(),
description: getMetaByName("description"),
keywords: getMetaByName("keywords"),
author: getMetaByName("author"),
ogTitle: getMetaByProperty("og:title"),
ogDescription: getMetaByProperty("og:description"),
ogImage: getMetaByProperty("og:image"),
ogUrl: getMetaByProperty("og:url"),
ogSiteName: getMetaByProperty("og:site_name"),
articleAuthor: getMetaByProperty("article:author"),
publishedTime: getMetaByProperty("article:published_time"),
modifiedTime: getMetaByProperty("article:modified_time"),
canonical: document.querySelector('link[rel="canonical"]')?.getAttribute("href"),
favicon: document.querySelector('link[rel="icon"]')?.getAttribute("href"),
jsonLd: extractJsonLd(),
statusCode: 200,
},
};
}),
screenshot ? page.screenshot({ encoding: "base64", type: "jpeg", quality: 100 }) : null,
pdf ? page.pdf() : null,
]);
htmlContent = html;
times.extractionTime = Date.now() - startTime - (times.pageLoadTime || 0);
scrapeResponse = { content: {}, metadata, links };
if (base64Screenshot) {
scrapeResponse.screenshot = base64Screenshot;
}
if (pdfBuffer) {
scrapeResponse.pdf = Buffer.from(pdfBuffer).toString("base64");
}
}
// Format handling (works for both PDF converted HTML and normal HTML)
if (format && format.length > 0) {
if (format.includes(ScrapeFormat.HTML)) {
scrapeResponse.content.html = htmlContent;
}
const needsCleanedHtml = format.includes(ScrapeFormat.CLEANED_HTML);
const needsReadability =
format.includes(ScrapeFormat.READABILITY) || format.includes(ScrapeFormat.MARKDOWN);
if (needsCleanedHtml) {
const cleanHtmlStart = Date.now();
cleanedHtml = cleanHtml(htmlContent);
times.cleanedHtmlTime = Date.now() - cleanHtmlStart;
if (format.includes(ScrapeFormat.CLEANED_HTML)) {
scrapeResponse.content.cleaned_html = cleanedHtml;
}
}
if (needsReadability) {
const readabilityStart = Date.now();
readabilityContent = await getDefuddleContent(
transformHtml(htmlContent, normalizedUrl || url),
);
times.readabilityTime = Date.now() - readabilityStart;
if (format.includes(ScrapeFormat.READABILITY)) {
scrapeResponse.content.readability = readabilityContent.content;
}
}
if (format.includes(ScrapeFormat.MARKDOWN)) {
const markdownStart = Date.now();
scrapeResponse.content.markdown = await htmlToMarkdown(readabilityContent!.content);
times.markdownTime = Date.now() - markdownStart;
}
} else {
scrapeResponse.content.html = htmlContent;
}
times.totalInstanceTime = Date.now() - startTime;
if (logUrl) {
await updateLog(logUrl, { times });
}
return reply.send(scrapeResponse);
} catch (e: unknown) {
const error = getErrors(e);
if (logUrl) {
await updateLog(logUrl, { times, response: { browserError: error } });
}
if (url) {
await browserService.refreshPrimaryPage();
}
return reply.code(500).send({ message: error });
} finally {
if (context) {
await context.close().catch(() => {});
}
if (proxy) {
await proxy.close(true).catch(() => {});
}
}
};
export const handleSearch = async (
sessionService: SessionService,
browserService: CDPService,
request: SearchRequest,
reply: FastifyReply,
) => {
const startTime = Date.now();
let times: Record<string, number> = {};
const { query, proxyUrl, logUrl } = request.body;
let proxy: IProxyServer | null = null;
let context: BrowserContext | null = null;
try {
if (proxyUrl) {
proxy = await sessionService.proxyFactory(proxyUrl);
await proxy.listen();
}
times.proxyTime = Date.now() - startTime;
let page: Page;
if (!browserService.isRunning()) {
await browserService.launch();
}
if (proxy) {
// If a proxy is used, we proceed with browser navigation; implementing proxy-aware Node fetch
// would require an HTTP agent and is outside current scope.
context = await browserService.createBrowserContext(proxy.url);
page = await context.newPage();
times.proxyPageTime = Date.now() - startTime - times.proxyTime;
} else {
page = await browserService.getPrimaryPage();
times.pageTime = Date.now() - startTime - times.proxyTime;
}
await page.evaluate(() => {
(window as any).__name = (func: Function) => func;
});
// Go to Brave
await page.goto(`https://search.brave.com/search?q=${encodeURIComponent(query)}`, {
waitUntil: "networkidle2",
});
// Wait for results to load
await page.waitForSelector("#results");
// Scrape results
const results = await page.evaluate(() => {
const items = document.querySelectorAll("div.snippet");
return Array.from(items)
.map((item) => {
if (
[
"llm-snippet",
"faq",
"pagination-snippet",
"search-elsewhere",
"infoblox-snippet",
"discussions",
].includes(item.id)
) {
return;
}
const urlEl = item.querySelector("div.result-content a");
const descEl = item.querySelector("div.generic-snippet");
const titleEl = item.querySelector("div.result-content a div.title");
return {
title: titleEl?.textContent?.trim() || null,
url: urlEl?.getAttribute("href") || null,
description: descEl?.textContent?.split("-")[1]?.trim() || null,
};
})
.filter(
(item) =>
item &&
typeof item === "object" &&
"title" in item &&
"url" in item &&
"description" in item &&
item.title !== null &&
item.url !== null,
);
});
times.totalInstanceTime = Date.now() - startTime;
if (logUrl) {
await updateLog(logUrl, { times });
}
return reply.send({ results });
} catch (e: unknown) {
const error = getErrors(e);
if (logUrl) {
await updateLog(logUrl, { times, response: { browserError: error } });
}
return reply.code(500).send({ message: error });
} finally {
if (context) {
await context.close().catch(() => {});
}
if (proxy) {
await proxy.close(true).catch(() => {});
}
}
};
export const handleScreenshot = async (
sessionService: SessionService,
browserService: CDPService,
request: ScreenshotRequest,
reply: FastifyReply,
) => {
const startTime = Date.now();
let times: Record<string, number> = {};
const { url, logUrl, proxyUrl, delay, fullPage } = request.body;
let proxy: IProxyServer | null = null;
let context: BrowserContext | null = null;
if (!browserService.isRunning()) {
await browserService.launch();
}
try {
if (proxyUrl) {
proxy = await sessionService.proxyFactory(proxyUrl);
await proxy.listen();
}
times.proxyTime = Date.now() - startTime;
let page: Page;
if (proxy) {
context = await browserService.createBrowserContext(proxy.url);
page = await context.newPage();
times.proxyPageTime = Date.now() - startTime - times.proxyTime;
} else {
page = await browserService.getPrimaryPage();
times.pageTime = Date.now() - startTime;
}
if (url) {
const normalizedUrl = normalizeUrl(url);
if (!normalizedUrl) {
throw new Error(`Invalid URL: ${url}`);
}
await page.goto(normalizedUrl, { timeout: 30000, waitUntil: "domcontentloaded" });
times.pageLoadTime = Date.now() - times.pageTime - times.proxyTime - startTime;
}
if (delay) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
const screenshot = await page.screenshot({ fullPage, type: "jpeg", quality: 100 });
times.screenshotTime =
Date.now() - times.pageLoadTime - times.pageTime - times.proxyTime - startTime;
if (logUrl) {
await updateLog(logUrl, { times });
}
return reply.send(screenshot);
} catch (e: unknown) {
const error = getErrors(e);
if (logUrl) {
await updateLog(logUrl, { times, response: { browserError: error } });
}
if (url) {
await browserService.refreshPrimaryPage();
}
return reply.code(500).send({ message: error });
} finally {
if (context) {
await context.close().catch(() => {});
}
if (proxy) {
await proxy.close(true).catch(() => {});
}
}
};
export const handlePDF = async (
sessionService: SessionService,
browserService: CDPService,
request: PDFRequest,
reply: FastifyReply,
) => {
const startTime = Date.now();
let times: Record<string, number> = {};
const { url, logUrl, proxyUrl, delay } = request.body;
let proxy: IProxyServer | null = null;
let context: BrowserContext | null = null;
if (!browserService.isRunning()) {
await browserService.launch();
}
try {
if (proxyUrl) {
proxy = await sessionService.proxyFactory(proxyUrl);
await proxy.listen();
}
times.proxyTime = Date.now() - startTime;
let page: Page;
if (proxy) {
context = await browserService.createBrowserContext(proxy.url);
page = await context.newPage();
times.proxyPageTime = Date.now() - startTime - times.proxyTime;
} else {
page = await browserService.getPrimaryPage();
times.pageTime = Date.now() - startTime;
}
if (url) {
const normalizedUrl = normalizeUrl(url);
if (!normalizedUrl) {
throw new Error(`Invalid URL: ${url}`);
}
await page.goto(normalizedUrl, { timeout: 30000, waitUntil: "domcontentloaded" });
times.pageLoadTime = Date.now() - times.pageTime - times.proxyTime - startTime;
}
if (delay) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
const pdf = await page.pdf();
times.pdfTime = Date.now() - times.pageLoadTime - times.pageTime - times.proxyTime - startTime;
if (logUrl) {
await updateLog(logUrl, { times });
}
return reply.send(pdf);
} catch (e: unknown) {
const error = getErrors(e);
if (logUrl) {
await updateLog(logUrl, { times, response: { browserError: error } });
}
if (url) {
await browserService.refreshPrimaryPage();
}
return reply.code(500).send({ message: error });
} finally {
if (context) {
await context.close().catch(() => {});
}
if (proxy) {
await proxy.close(true).catch(() => {});
}
}
};
|