NextAITeam commited on
Commit
5258f8b
·
verified ·
1 Parent(s): 181a65d

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +62 -189
server.js CHANGED
@@ -1,17 +1,10 @@
1
  import express from "express";
2
  import { chromium } from "playwright";
3
- import StealthPlugin from "puppeteer-extra-plugin-stealth";
4
- import { addExtra } from "playwright-extra";
5
-
6
- // ===== استفاده از Playwright با Stealth =====
7
- const playwright = addExtra(chromium);
8
- const stealth = StealthPlugin();
9
- playwright.use(stealth);
10
 
11
  const app = express();
12
  const PORT = 7860;
13
 
14
- // ===== لیست User-Agentهای واقعی =====
15
  const USER_AGENTS = [
16
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
17
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
@@ -19,9 +12,9 @@ const USER_AGENTS = [
19
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
20
  ];
21
 
22
- // ===== تنظیمات پیشرفته براوزر =====
23
  const LAUNCH_OPTIONS = {
24
- headless: "new",
25
  args: [
26
  "--no-sandbox",
27
  "--disable-blink-features=AutomationControlled",
@@ -60,20 +53,12 @@ const LAUNCH_OPTIONS = {
60
  ]
61
  };
62
 
63
- // ===== تابع کمکی برای استخراج نتایج =====
64
- async function extractGoogleResults(page) {
65
- // منتظر بارگذاری نتایج با سلکتورهای مختلف
66
- const resultSelectors = [
67
- 'div.g',
68
- 'div.yuRUbf',
69
- 'div[data-sokoban-container]',
70
- 'div.rc',
71
- 'div.tF2Cxc',
72
- '#search div.g'
73
- ];
74
-
75
  let found = false;
76
- for (const selector of resultSelectors) {
77
  try {
78
  await page.waitForSelector(selector, { timeout: 5000 });
79
  found = true;
@@ -82,74 +67,31 @@ async function extractGoogleResults(page) {
82
  }
83
 
84
  if (!found) {
85
- await page.waitForTimeout(2000);
86
- // بررسی کنید که آیا گوگل مسدود کرده است
87
- const bodyText = await page.textContent('body');
88
- if (bodyText && (bodyText.includes('detected unusual traffic') || bodyText.includes('captcha'))) {
89
  return { blocked: true, results: [] };
90
  }
 
91
  }
92
 
93
- // استخراج نتایج با چندین روش
94
  const results = await page.evaluate(() => {
95
  const items = [];
96
- const seenUrls = new Set();
97
-
98
- // روش‌های مختلف برای پیدا کردن نتایج
99
- const extractionMethods = [
100
- // روش ۱: لینک‌های داخل div.g با h3
101
- () => {
102
- const links = document.querySelectorAll('div.g a[href^="http"]');
103
- for (const a of links) {
104
- const h3 = a.querySelector('h3');
105
- if (h3) {
106
- const title = h3.innerText.trim();
107
- const url = a.href;
108
- if (title && url && !seenUrls.has(url) && !url.includes('google.com/')) {
109
- seenUrls.add(url);
110
- items.push({ title, url });
111
- }
112
- }
113
- }
114
- },
115
- // روش ۲: yuRUbf
116
- () => {
117
- const links = document.querySelectorAll('div.yuRUbf a[href^="http"]');
118
- for (const a of links) {
119
- const h3 = a.querySelector('h3');
120
- if (h3) {
121
- const title = h3.innerText.trim();
122
- const url = a.href;
123
- if (title && url && !seenUrls.has(url) && !url.includes('google.com/')) {
124
- seenUrls.add(url);
125
- items.push({ title, url });
126
- }
127
- }
128
- }
129
- },
130
- // روش ۳: div#search
131
- () => {
132
- const searchDiv = document.querySelector('div#search');
133
- if (searchDiv) {
134
- const links = searchDiv.querySelectorAll('a[href^="http"]');
135
- for (const a of links) {
136
- const title = a.innerText.trim() || a.querySelector('h3')?.innerText?.trim() || '';
137
- const url = a.href;
138
- if (title && title.length > 3 && url && !seenUrls.has(url) && !url.includes('google.com/')) {
139
- seenUrls.add(url);
140
- items.push({ title, url });
141
- }
142
- }
143
- }
144
- }
145
- ];
146
-
147
- for (const method of extractionMethods) {
148
- method();
149
  if (items.length >= 10) break;
150
  }
151
-
152
- return items.slice(0, 10);
153
  });
154
 
155
  return { blocked: false, results };
@@ -166,91 +108,55 @@ app.get("/search", async (req, res) => {
166
 
167
  let browser = null;
168
  try {
169
- // انتخاب تصادفی User-Agent
170
  const userAgent = USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
171
 
172
- // ===== راه‌اندازی براوزر =====
173
- browser = await playwright.launch(LAUNCH_OPTIONS);
174
  const context = await browser.newContext({
175
  userAgent: userAgent,
176
  viewport: { width: 1366, height: 768 },
177
  locale: "en-US",
178
- timezoneId: "America/New_York",
179
- permissions: ["geolocation"],
180
- geolocation: { latitude: 40.7128, longitude: -74.0060 },
181
- deviceScaleFactor: 1,
182
- hasTouch: false,
183
- isMobile: false,
184
- extraHTTPHeaders: {
185
- 'Accept-Language': 'en-US,en;q=0.9',
186
- 'Accept-Encoding': 'gzip, deflate, br',
187
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
188
- 'Connection': 'keep-alive',
189
- 'Upgrade-Insecure-Requests': '1'
190
- }
191
  });
192
 
193
  const page = await context.newPage();
194
 
195
- // ===== مرحله ۱: رد کردن کوکی‌ها =====
196
- await page.goto("https://www.google.com/", {
197
- waitUntil: "domcontentloaded",
198
- timeout: 15000
199
- });
200
-
201
- // تلاش برای رد کردن کوکی‌ها
202
  try {
203
- const acceptBtn = await page.$('button:has-text("Accept all"), button:has-text("I agree"), button:has-text("Accept"), button[aria-label="Accept all"]');
204
- if (acceptBtn) {
205
- await acceptBtn.click();
206
  await page.waitForTimeout(1000);
207
  }
208
  } catch (e) {}
209
 
210
- // ===== مرحله ۲: شبیه‌سازی حرکت انسان =====
211
  await page.waitForTimeout(500 + Math.random() * 1000);
212
- await page.mouse.move(
213
- 100 + Math.random() * 200,
214
- 100 + Math.random() * 200
215
- );
216
- await page.waitForTimeout(200 + Math.random() * 500);
217
 
218
- // ===== مرحله ۳: انجام جستجو =====
219
  await page.goto(
220
- `https://www.google.com/search?q=${encodeURIComponent(query)}&hl=en&num=20`,
221
- {
222
- waitUntil: "networkidle",
223
- timeout: 35000
224
- }
225
  );
226
 
227
- // ===== مرحله ۴: شبیه‌سازی اسکرول =====
228
- await page.evaluate(() => {
229
- window.scrollTo(0, document.body.scrollHeight * 0.3);
230
- });
231
  await page.waitForTimeout(300 + Math.random() * 500);
232
- await page.evaluate(() => {
233
- window.scrollTo(0, document.body.scrollHeight * 0.6);
234
- });
235
- await page.waitForTimeout(200 + Math.random() * 400);
236
-
237
- // ===== مرحل�� ۵: بررسی مسدود شدن =====
238
- const pageTitle = await page.title();
239
- const pageContent = await page.content();
240
-
241
- if (pageContent.includes('detected unusual traffic') ||
242
- pageContent.includes('captcha') ||
243
- pageTitle.toLowerCase().includes('sorry') ||
244
- pageTitle.toLowerCase().includes('unusual')) {
245
-
246
- console.log(`⚠️ Google blocked the request for "${query}"`);
247
 
248
- // ===== Fallback به DuckDuckGo =====
 
 
 
 
249
  try {
250
- const ddgResponse = await fetch(
251
  `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`
252
  );
253
- const ddgData = await ddgResponse.json();
254
  const ddgResults = (ddgData.RelatedTopics || [])
255
  .filter(t => t.FirstURL && t.Text)
256
  .slice(0, 10)
@@ -260,42 +166,28 @@ app.get("/search", async (req, res) => {
260
  snippet: t.Text,
261
  site: new URL(t.FirstURL).hostname.replace("www.", "")
262
  }));
263
-
264
  if (ddgResults.length > 0) {
265
  await browser.close();
266
- return res.json({
267
- query,
268
- count: ddgResults.length,
269
- results: ddgResults,
270
- source: "duckduckgo_fallback"
271
- });
272
  }
273
- } catch (ddgError) {}
274
-
275
  await browser.close();
276
- return res.json({
277
- query,
278
- count: 0,
279
- results: [],
280
- source: "google",
281
- blocked: true,
282
- message: "Google blocked this request. Please try again later."
283
- });
284
  }
285
 
286
- // ===== مرحله ۶: استخراج نتایج =====
287
- const { results } = await extractGoogleResults(page);
288
  console.log(`✅ Found ${results.length} results for "${query}"`);
289
 
290
  await browser.close();
291
 
292
- // ===== اگر نتیجه‌ای نبود، از DuckDuckGo استفاده کن =====
293
  if (results.length === 0) {
294
  try {
295
- const ddgResponse = await fetch(
296
  `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`
297
  );
298
- const ddgData = await ddgResponse.json();
299
  const ddgResults = (ddgData.RelatedTopics || [])
300
  .filter(t => t.FirstURL && t.Text)
301
  .slice(0, 10)
@@ -305,48 +197,29 @@ app.get("/search", async (req, res) => {
305
  snippet: t.Text,
306
  site: new URL(t.FirstURL).hostname.replace("www.", "")
307
  }));
308
-
309
  if (ddgResults.length > 0) {
310
- return res.json({
311
- query,
312
- count: ddgResults.length,
313
- results: ddgResults,
314
- source: "duckduckgo"
315
- });
316
  }
317
- } catch (ddgError) {}
318
  }
319
 
320
- res.json({
321
- query,
322
- count: results.length,
323
- results: results,
324
- source: "google"
325
- });
326
 
327
  } catch (error) {
328
  console.error(`❌ Error:`, error.message);
329
  if (browser) await browser.close().catch(() => {});
330
- res.status(500).json({
331
- error: error.message,
332
- query,
333
- count: 0,
334
- results: []
335
- });
336
  }
337
  });
338
 
339
- // ===== مسیر اصلی =====
340
  app.get("/", (req, res) => {
341
  res.json({
342
  status: "running",
343
  usage: "/search?q=YOUR_QUERY",
344
- note: "Google Search with Playwright + Stealth + Fallback to DuckDuckGo"
345
  });
346
  });
347
 
348
- // ===== راه‌اندازی سرور =====
349
  app.listen(PORT, "0.0.0.0", () => {
350
  console.log(`🚀 Server running on port ${PORT}`);
351
- console.log(`📍 Test: http://localhost:${PORT}/search?q=python`);
352
  });
 
1
  import express from "express";
2
  import { chromium } from "playwright";
 
 
 
 
 
 
 
3
 
4
  const app = express();
5
  const PORT = 7860;
6
 
7
+ // ===== لیست User-Agentهای واقعی برای چرخش =====
8
  const USER_AGENTS = [
9
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
10
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
 
12
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
13
  ];
14
 
15
+ // ===== تنظیمات براوزر (سازگار با همه نسخه‌ها) =====
16
  const LAUNCH_OPTIONS = {
17
+ headless: true, // به جای "new"
18
  args: [
19
  "--no-sandbox",
20
  "--disable-blink-features=AutomationControlled",
 
53
  ]
54
  };
55
 
56
+ // ===== استخراج نتایج با سلکتورهای مقاوم =====
57
+ async function extractResults(page) {
58
+ // منتظر بارگذاری نتایج
59
+ const selectors = ['div.g', 'div.yuRUbf', 'div[data-sokoban-container]', 'div.rc', '#search div.g'];
 
 
 
 
 
 
 
 
60
  let found = false;
61
+ for (const selector of selectors) {
62
  try {
63
  await page.waitForSelector(selector, { timeout: 5000 });
64
  found = true;
 
67
  }
68
 
69
  if (!found) {
70
+ // اگر نتیجه‌ای نیامد، بررسی کن که گوگل مسدود نکرده باشد
71
+ const body = await page.textContent('body');
72
+ if (body && (body.includes('detected unusual traffic') || body.includes('captcha'))) {
 
73
  return { blocked: true, results: [] };
74
  }
75
+ await page.waitForTimeout(2000);
76
  }
77
 
78
+ // استخراج نتایج
79
  const results = await page.evaluate(() => {
80
  const items = [];
81
+ const seen = new Set();
82
+ const links = document.querySelectorAll('div.g a[href^="http"], div.yuRUbf a[href^="http"], #search a[href^="http"]');
83
+ for (const a of links) {
84
+ const h3 = a.querySelector('h3');
85
+ if (!h3) continue;
86
+ const title = h3.innerText.trim();
87
+ const url = a.href;
88
+ if (!title || !url || seen.has(url)) continue;
89
+ if (url.includes('google.com/') && !url.includes('/search?')) continue;
90
+ seen.add(url);
91
+ items.push({ title, url });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  if (items.length >= 10) break;
93
  }
94
+ return items;
 
95
  });
96
 
97
  return { blocked: false, results };
 
108
 
109
  let browser = null;
110
  try {
 
111
  const userAgent = USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
112
 
113
+ browser = await chromium.launch(LAUNCH_OPTIONS);
 
114
  const context = await browser.newContext({
115
  userAgent: userAgent,
116
  viewport: { width: 1366, height: 768 },
117
  locale: "en-US",
118
+ timezoneId: "America/New_York"
 
 
 
 
 
 
 
 
 
 
 
 
119
  });
120
 
121
  const page = await context.newPage();
122
 
123
+ // رفتن به صفحه اصلی و رد کردن کوکی
124
+ await page.goto("https://www.google.com/", { waitUntil: "domcontentloaded", timeout: 15000 });
 
 
 
 
 
125
  try {
126
+ const accept = await page.$('button:has-text("Accept all"), button:has-text("I agree")');
127
+ if (accept) {
128
+ await accept.click();
129
  await page.waitForTimeout(1000);
130
  }
131
  } catch (e) {}
132
 
133
+ // شبیه‌سازی حرکت انسانی
134
  await page.waitForTimeout(500 + Math.random() * 1000);
135
+ await page.mouse.move(200 + Math.random() * 300, 200 + Math.random() * 300);
136
+ await page.waitForTimeout(300 + Math.random() * 500);
 
 
 
137
 
138
+ // جستجو
139
  await page.goto(
140
+ `https://www.google.com/search?q=${encodeURIComponent(query)}&hl=en`,
141
+ { waitUntil: "networkidle", timeout: 30000 }
 
 
 
142
  );
143
 
144
+ // شبیه‌سازی اسکرول
145
+ await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight * 0.3));
146
+ await page.waitForTimeout(300 + Math.random() * 500);
147
+ await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight * 0.6));
148
  await page.waitForTimeout(300 + Math.random() * 500);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ // بررسی مسدود شدن
151
+ const content = await page.content();
152
+ if (content.includes('detected unusual traffic') || content.includes('captcha')) {
153
+ console.log(`⚠️ Google blocked request for "${query}"`);
154
+ // Fallback به DuckDuckGo
155
  try {
156
+ const ddg = await fetch(
157
  `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`
158
  );
159
+ const ddgData = await ddg.json();
160
  const ddgResults = (ddgData.RelatedTopics || [])
161
  .filter(t => t.FirstURL && t.Text)
162
  .slice(0, 10)
 
166
  snippet: t.Text,
167
  site: new URL(t.FirstURL).hostname.replace("www.", "")
168
  }));
 
169
  if (ddgResults.length > 0) {
170
  await browser.close();
171
+ return res.json({ query, count: ddgResults.length, results: ddgResults, source: "duckduckgo_fallback" });
 
 
 
 
 
172
  }
173
+ } catch (e) {}
 
174
  await browser.close();
175
+ return res.json({ query, count: 0, results: [], source: "google", blocked: true });
 
 
 
 
 
 
 
176
  }
177
 
178
+ // استخراج نتایج
179
+ const { results } = await extractResults(page);
180
  console.log(`✅ Found ${results.length} results for "${query}"`);
181
 
182
  await browser.close();
183
 
184
+ // اگر نتیجه‌ای نبود، DuckDuckGo
185
  if (results.length === 0) {
186
  try {
187
+ const ddg = await fetch(
188
  `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`
189
  );
190
+ const ddgData = await ddg.json();
191
  const ddgResults = (ddgData.RelatedTopics || [])
192
  .filter(t => t.FirstURL && t.Text)
193
  .slice(0, 10)
 
197
  snippet: t.Text,
198
  site: new URL(t.FirstURL).hostname.replace("www.", "")
199
  }));
 
200
  if (ddgResults.length > 0) {
201
+ return res.json({ query, count: ddgResults.length, results: ddgResults, source: "duckduckgo" });
 
 
 
 
 
202
  }
203
+ } catch (e) {}
204
  }
205
 
206
+ res.json({ query, count: results.length, results, source: "google" });
 
 
 
 
 
207
 
208
  } catch (error) {
209
  console.error(`❌ Error:`, error.message);
210
  if (browser) await browser.close().catch(() => {});
211
+ res.status(500).json({ error: error.message, query, count: 0, results: [] });
 
 
 
 
 
212
  }
213
  });
214
 
 
215
  app.get("/", (req, res) => {
216
  res.json({
217
  status: "running",
218
  usage: "/search?q=YOUR_QUERY",
219
+ note: "Google Search with Playwright + Fallback to DuckDuckGo"
220
  });
221
  });
222
 
 
223
  app.listen(PORT, "0.0.0.0", () => {
224
  console.log(`🚀 Server running on port ${PORT}`);
 
225
  });