manaf1234 commited on
Commit
5b9cea1
·
verified ·
1 Parent(s): 5e1c2ba

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +169 -0
server.js ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const express = require('express');
2
+ const { chromium } = require('playwright');
3
+ const cheerio = require('cheerio');
4
+ const cors = require('cors');
5
+
6
+ const app = express();
7
+ app.use(cors());
8
+ app.use(express.json());
9
+
10
+ const requestQueue = [];
11
+ let isProcessing = false;
12
+ let browserInstance = null; // Globally cached single browser instance
13
+
14
+ // Initialize the master browser process on boot
15
+ async function initBrowser() {
16
+ try {
17
+ console.log("[System Init]: Launching master Chromium process...");
18
+ browserInstance = await chromium.launch({
19
+ headless: true,
20
+ args: [
21
+ '--no-sandbox',
22
+ '--disable-setuid-sandbox',
23
+ '--disable-dev-shm-usage', // Vital for low memory containers
24
+ '--disable-accelerated-2d-canvas',
25
+ '--disable-gpu'
26
+ ]
27
+ });
28
+ console.log("[System Init]: Headless Chromium ready to snatch.");
29
+ } catch (err) {
30
+ console.error("[System Init Error]: Failed launching master browser:", err.message);
31
+ }
32
+ }
33
+
34
+ // Queue Processing Loop
35
+ async function processQueue() {
36
+ if (isProcessing || requestQueue.length === 0) return;
37
+
38
+ isProcessing = true;
39
+ const currentTask = requestQueue.shift();
40
+
41
+ // Ensure browser didn't crash or close unexpectedly under heavy workloads
42
+ if (!browserInstance) {
43
+ await initBrowser();
44
+ }
45
+
46
+ let context = null;
47
+ let page = null;
48
+
49
+ try {
50
+ const { targetUrl, requestedAssets, res } = currentTask;
51
+ console.log(`\n[Snatch Worker]: Processing -> ${targetUrl}`);
52
+
53
+ // Create an isolated, completely fresh browser context (simulates a new device context)
54
+ context = await browserInstance.newContext({
55
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
56
+ viewport: { width: 1280, height: 800 },
57
+ deviceScaleFactor: 1,
58
+ bypassCSP: true // Bypass Content Security Policy to pull stylesheets freely
59
+ });
60
+
61
+ page = await context.newPage();
62
+
63
+ // Navigate to the page and wait until network connections completely settle down
64
+ await page.goto(targetUrl, {
65
+ timeout: 25000,
66
+ waitUntil: 'networkidle' // Crucial: Waits for all dynamic React/JS loads to finish
67
+ });
68
+
69
+ // Pull the fully compiled, javascript-rendered DOM tree structure string
70
+ const renderedHtml = await page.content();
71
+ const $ = cheerio.load(renderedHtml);
72
+
73
+ let extractedCss = "";
74
+ let extractedJs = "";
75
+
76
+ // 1. Asset Extractor: CSS Elements
77
+ if (requestedAssets.includes('css')) {
78
+ $('style').each((_, el) => {
79
+ extractedCss += `/* --- Inline Style --- */\n${$(el).text()}\n\n`;
80
+ });
81
+ $('link[rel="stylesheet"]').each((_, el) => {
82
+ const href = $(el).attr('href');
83
+ if (href) {
84
+ const absUrl = href.startsWith('http') ? href : new URL(href, targetUrl).href;
85
+ extractedCss += `/* External Reference: ${absUrl} */\n`;
86
+ }
87
+ });
88
+ }
89
+
90
+ // 2. Asset Extractor: JS Elements
91
+ if (requestedAssets.includes('js')) {
92
+ $('script').each((_, el) => {
93
+ const text = $(el).text();
94
+ const src = $(el).attr('src');
95
+ if (text.trim()) {
96
+ extractedJs += `// --- Inline Script ---\n${text.trim()}\n\n`;
97
+ } else if (src) {
98
+ const absUrl = src.startsWith('http') ? src : new URL(src, targetUrl).href;
99
+ extractedJs += `// External Reference: ${absUrl}\n`;
100
+ }
101
+ });
102
+ }
103
+
104
+ // 3. Asset Extractor: Clean, isolated HTML document frame body
105
+ let cleanHtml = "";
106
+ if (requestedAssets.includes('html')) {
107
+ $('script, style, link[rel="stylesheet"]').remove();
108
+ cleanHtml = $('body').html() || $.html();
109
+ }
110
+
111
+ // Send payload back cleanly
112
+ res.json({
113
+ html: requestedAssets.includes('html') ? cleanHtml.trim() : null,
114
+ css: requestedAssets.includes('css') ? extractedCss.trim() : null,
115
+ js: requestedAssets.includes('js') ? extractedJs.trim() : null
116
+ });
117
+
118
+ console.log(`[Snatch Worker]: Successfully sent assets back to frontend client.`);
119
+
120
+ } catch (error) {
121
+ console.error(`[Snatch Worker Error]: Execution hit a wall:`, error.message);
122
+ currentTask.res.status(500).json({ error: "Playwright Snatcher failed execution task: " + error.message });
123
+ } finally {
124
+ // Clean up individual tabs to completely prevent memory leaks
125
+ if (page) await page.close().catch(() => {});
126
+ if (context) await context.close().catch(() => {});
127
+
128
+ isProcessing = false;
129
+ // Moderate pacing backoff time window delay
130
+ setTimeout(processQueue, 150);
131
+ }
132
+ }
133
+
134
+ // Operational Status Route Mapping
135
+ app.get('/', (req, res) => {
136
+ res.json({
137
+ engine: "CodeSnatch Ultimate Playwright Cluster",
138
+ status: "operational",
139
+ browserProcessAlive: !!browserInstance,
140
+ backlogLength: requestQueue.length
141
+ });
142
+ });
143
+
144
+ // Primary Scrape Ingestion Route
145
+ app.get('/scrape', (req, res) => {
146
+ const targetUrl = req.query.url;
147
+ const requestedAssets = req.query.assets ? req.query.assets.split(',') : ['html', 'css', 'js'];
148
+
149
+ if (!targetUrl) {
150
+ return res.status(400).json({ error: "Missing required query parameter 'url'." });
151
+ }
152
+
153
+ requestQueue.push({ targetUrl, requestedAssets, res });
154
+ console.log(`[Traffic]: Enqueued new web page target. Backlog count: ${requestQueue.length}`);
155
+
156
+ processQueue();
157
+ });
158
+
159
+ // Standard system shutdown handling to cleanly close Chromium process
160
+ process.on('SIGTERM', async () => {
161
+ if (browserInstance) await browserInstance.close();
162
+ process.exit(0);
163
+ });
164
+
165
+ const PORT = process.env.PORT || 7860;
166
+ app.listen(PORT, async () => {
167
+ console.log(`=== Ultimate CodeSnatch Backend Listening on Port: ${PORT} ===`);
168
+ await initBrowser(); // Instantly spin up browser engine instance when web server activates
169
+ });