NextAITeam commited on
Commit
3ca805b
·
verified ·
1 Parent(s): 2692d56

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +80 -110
server.js CHANGED
@@ -7,101 +7,54 @@ const PORT = 7860;
7
  const CACHE_TTL = 3600;
8
  const cache = new Map();
9
 
10
- // ===== لیست User-Agentها برای چرخش =====
11
- const USER_AGENTS = [
12
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
13
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
14
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
15
- "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
 
 
16
  ];
17
 
18
- // ===== جستجو در Bing با اسکرپینگ =====
19
- async function searchBing(query) {
20
- const userAgent = USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];
21
- const url = `https://www.bing.com/search?q=${encodeURIComponent(query)}&count=20&form=QBLH&sp=-1&pq=${encodeURIComponent(query)}&sc=0-0&qs=n&sk=&cvid=1234567890`;
22
-
23
- try {
24
- const response = await fetch(url, {
25
- headers: {
26
- 'User-Agent': userAgent,
27
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
28
- 'Accept-Language': 'en-US,en;q=0.9',
29
- 'Accept-Encoding': 'gzip, deflate, br',
30
- 'Connection': 'keep-alive',
31
- 'Upgrade-Insecure-Requests': '1'
32
- }
33
- });
34
-
35
- if (!response.ok) {
36
- console.log(`⚠️ Bing returned ${response.status}`);
37
- return [];
38
- }
39
-
40
- const html = await response.text();
41
 
42
- // بررسی مسدود شدن
43
- if (html.includes('detected unusual traffic') || html.includes('captcha') || html.includes('sorry')) {
44
- console.log(`⚠️ Bing blocked the request for "${query}"`);
45
- return [];
46
- }
 
47
 
48
- // استخراج نتایج با رجکس
49
- const results = [];
50
- // الگوی اصلی نتایج Bing
51
- const regex = /<li class="b_algo"[^>]*>.*?<h2><a href="([^"]+)"[^>]*>(.*?)<\/a><\/h2>.*?<p>(.*?)<\/p>/gs;
52
- let match;
53
- let count = 0;
54
- while ((match = regex.exec(html)) !== null && count < 15) {
55
- const url = match[1];
56
- let title = match[2].replace(/<[^>]+>/g, '').trim();
57
- let snippet = match[3].replace(/<[^>]+>/g, '').trim();
58
-
59
- // حذف موارد تکراری و نامعتبر
60
- if (title && url && !url.includes('bing.com') && !url.includes('microsoft.com')) {
61
- // اگر title طولانی‌تر از حد بود، کوتاه کن
62
- if (title.length > 200) title = title.slice(0, 200) + '...';
63
- if (snippet.length > 300) snippet = snippet.slice(0, 300) + '...';
64
-
65
- results.push({
66
- title: title,
67
- url: url,
68
- snippet: snippet || 'No description available',
69
- site: new URL(url).hostname.replace('www.', '')
70
- });
71
- count++;
72
  }
73
- }
74
 
75
- // اگر با رجکس اصلی نتیجه‌ای پیدا نشد، از روش جایگزین استفاده کن
76
- if (results.length === 0) {
77
- // روش دوم: جستجوی لینک‌های داخل div#b_results
78
- const altRegex = /<div id="b_results">.*?<a href="([^"]+)"[^>]*>.*?<h2>(.*?)<\/h2>.*?<p>(.*?)<\/p>/gs;
79
- while ((match = altRegex.exec(html)) !== null && count < 15) {
80
- const url = match[1];
81
- const title = match[2].replace(/<[^>]+>/g, '').trim();
82
- const snippet = match[3].replace(/<[^>]+>/g, '').trim();
83
- if (title && url && !url.includes('bing.com') && !url.includes('microsoft.com')) {
84
- results.push({
85
- title: title,
86
- url: url,
87
- snippet: snippet || 'No description available',
88
- site: new URL(url).hostname.replace('www.', '')
89
- });
90
- count++;
91
- }
92
  }
 
 
93
  }
94
-
95
- console.log(`✅ Bing found ${results.length} results for "${query}"`);
96
- return results;
97
-
98
- } catch (error) {
99
- console.log(`❌ Bing error:`, error.message);
100
- return [];
101
  }
 
102
  }
103
 
104
- // ===== جستجوی اصلی با Fallback =====
105
  async function search(query) {
106
  // ۱. کش
107
  const cached = cache.get(query);
@@ -114,42 +67,59 @@ async function search(query) {
114
 
115
  let results = [];
116
 
117
- // ۲. Bing
118
- results = await searchBing(query);
 
 
 
 
119
 
120
- // ۳. اگر Bing نتیجه‌ای نداشت، DuckDuckGo (فقط برای کوئری‌های عمومی)
121
  if (results.length === 0) {
122
- console.log(`🔄 Bing no results, trying DuckDuckGo...`);
123
  try {
124
- const ddg = await fetch(
125
- `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`
126
- );
127
- const data = await ddg.json();
128
- const ddgResults = (data.RelatedTopics || [])
129
- .filter(t => t.FirstURL && t.Text)
130
- .slice(0, 10)
131
- .map(t => ({
132
- title: t.Text.split("-")[0]?.trim() || t.Text,
133
- url: t.FirstURL,
134
- snippet: t.Text,
135
- site: new URL(t.FirstURL).hostname.replace("www.", "")
136
- }));
137
-
138
- if (ddgResults.length > 0) {
139
- results = ddgResults;
140
- console.log(`🦆 DuckDuckGo found ${results.length} results`);
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  }
142
  } catch (e) {
143
- console.log(`❌ DuckDuckGo fallback failed:`, e.message);
144
  }
145
  }
146
 
147
- // ۴. اگر هیچ نتیجه‌ای نبود
148
  if (results.length === 0) {
149
  results = [{
150
  title: "No results found",
151
  url: "#",
152
- snippet: `No results found for "${query}". You can try searching directly on Bing: https://www.bing.com/search?q=${encodeURIComponent(query)}`,
153
  site: "system"
154
  }];
155
  }
@@ -171,7 +141,7 @@ app.get("/search", async (req, res) => {
171
  query,
172
  count: results.length,
173
  results,
174
- source: results[0]?.site === "system" ? "none" : "bing"
175
  });
176
  } catch (error) {
177
  console.error(`❌ Error:`, error.message);
@@ -189,7 +159,7 @@ app.get("/", (req, res) => {
189
  res.json({
190
  status: "running",
191
  usage: "/search?q=YOUR_QUERY",
192
- note: "Search powered by Bing (scraping) + DuckDuckGo fallback"
193
  });
194
  });
195
 
 
7
  const CACHE_TTL = 3600;
8
  const cache = new Map();
9
 
10
+ // ===== لیست نمونه‌های عمومی Whoogle =====
11
+ const WHOOGLE_INSTANCES = [
12
+ "https://whoogle.uesugi.eu",
13
+ "https://whoogle.pussthecat.org",
14
+ "https://whoogle.foss.wtf",
15
+ "https://search.ngn.tf",
16
+ "https://whoogle.priv.pw",
17
+ "https://whoogle.suds.one"
18
  ];
19
 
20
+ // ===== جستجو با Whoogle =====
21
+ async function searchWhoogle(query) {
22
+ for (const instance of WHOOGLE_INSTANCES) {
23
+ try {
24
+ const url = `${instance}/search?q=${encodeURIComponent(query)}&format=json`;
25
+ console.log(`🔍 Trying Whoogle: ${instance}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ const response = await fetch(url, {
28
+ signal: AbortSignal.timeout(10000),
29
+ headers: {
30
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
31
+ }
32
+ });
33
 
34
+ if (!response.ok) {
35
+ console.log(`⚠️ ${instance} returned ${response.status}`);
36
+ continue;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  }
 
38
 
39
+ const data = await response.json();
40
+
41
+ if (data.results && data.results.length > 0) {
42
+ console.log(`✅ Whoogle (${instance}) found ${data.results.length} results`);
43
+ return data.results.slice(0, 15).map(item => ({
44
+ title: item.title || "No title",
45
+ url: item.url || "#",
46
+ snippet: item.description || item.snippet || "",
47
+ site: new URL(item.url || "#").hostname.replace("www.", "") || "unknown"
48
+ }));
 
 
 
 
 
 
 
49
  }
50
+ } catch (e) {
51
+ console.log(`❌ Whoogle ${instance} failed:`, e.message);
52
  }
 
 
 
 
 
 
 
53
  }
54
+ return [];
55
  }
56
 
57
+ // ===== جستجوی اصلی =====
58
  async function search(query) {
59
  // ۱. کش
60
  const cached = cache.get(query);
 
67
 
68
  let results = [];
69
 
70
+ // ۲. Whoogle (منبع اصلی)
71
+ try {
72
+ results = await searchWhoogle(query);
73
+ } catch (e) {
74
+ console.log(`❌ Whoogle error:`, e.message);
75
+ }
76
 
77
+ // ۳. اگر Whoogle نتیجه‌ای نداشت، Bing Scraping (پشتیبان)
78
  if (results.length === 0) {
79
+ console.log(`🔄 Whoogle no results, trying Bing...`);
80
  try {
81
+ // کد Bing Scraping (همان قبلی)
82
+ const bingUrl = `https://www.bing.com/search?q=${encodeURIComponent(query)}&count=10`;
83
+ const bingResponse = await fetch(bingUrl, {
84
+ headers: {
85
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
86
+ 'Accept': 'text/html'
87
+ }
88
+ });
89
+ if (bingResponse.ok) {
90
+ const html = await bingResponse.text();
91
+ const regex = /<li class="b_algo"[^>]*>.*?<h2><a href="([^"]+)"[^>]*>(.*?)<\/a><\/h2>.*?<p>(.*?)<\/p>/gs;
92
+ let match;
93
+ const bingResults = [];
94
+ while ((match = regex.exec(html)) !== null && bingResults.length < 10) {
95
+ const url = match[1];
96
+ const title = match[2].replace(/<[^>]+>/g, '').trim();
97
+ const snippet = match[3].replace(/<[^>]+>/g, '').trim();
98
+ if (title && url && !url.includes('bing.com') && !url.includes('microsoft.com')) {
99
+ bingResults.push({
100
+ title: title,
101
+ url: url,
102
+ snippet: snippet || 'No description available',
103
+ site: new URL(url).hostname.replace('www.', '')
104
+ });
105
+ }
106
+ }
107
+ if (bingResults.length > 0) {
108
+ results = bingResults;
109
+ console.log(`✅ Bing found ${results.length} results`);
110
+ }
111
  }
112
  } catch (e) {
113
+ console.log(`❌ Bing fallback failed:`, e.message);
114
  }
115
  }
116
 
117
+ // ۴. اگر هیچ نتیجه‌ای نبود، یک پیام مفید برگردان
118
  if (results.length === 0) {
119
  results = [{
120
  title: "No results found",
121
  url: "#",
122
+ snippet: `No results found for "${query}". Try searching on Whoogle: https://whoogle.uesugi.eu/search?q=${encodeURIComponent(query)}`,
123
  site: "system"
124
  }];
125
  }
 
141
  query,
142
  count: results.length,
143
  results,
144
+ source: results[0]?.site === "system" ? "none" : "whoogle"
145
  });
146
  } catch (error) {
147
  console.error(`❌ Error:`, error.message);
 
159
  res.json({
160
  status: "running",
161
  usage: "/search?q=YOUR_QUERY",
162
+ note: "Search powered by Whoogle (Google results) + Bing fallback"
163
  });
164
  });
165