mikmc5 commited on
Commit
ff45571
·
verified ·
1 Parent(s): ccbfc9d

Update bt4g.js

Browse files
Files changed (1) hide show
  1. bt4g.js +105 -106
bt4g.js CHANGED
@@ -1,8 +1,5 @@
1
  import { XMLParser } from 'fast-xml-parser';
2
 
3
- // Timeout helper function
4
- const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
-
6
  // Create a new instance of the XML parser
7
  const parser = new XMLParser({
8
  ignoreAttributes: true,
@@ -10,118 +7,120 @@ const parser = new XMLParser({
10
  trimValues: true,
11
  });
12
 
13
- async function fetchRSSFeeds(searchQuery) {
14
- const page1Url = `https://stremio-rev-proxy.h-y.workers.dev/https://bt4gprx.com/search?q=${encodeURIComponent(searchQuery)}&page=1&orderby=size&page=rss`;
15
- const page2Url = `https://bt4gprx.com/search?q=${encodeURIComponent(searchQuery)}&page=2&orderby=size&page=rss`; // Direct URL for page 2
16
-
17
- console.log('\n🔄 Fetching RSS feed for:', searchQuery);
18
 
19
  try {
20
- // Fetch page 1 with proxy
21
- const page1Response = await fetch(page1Url, {
22
- headers: {
23
- 'accept': '*/*',
24
- 'accept-language': 'en-US,en;q=0.9',
25
- },
26
- method: 'GET',
27
- });
28
- if (!page1Response.ok) {
29
- throw new Error(`Failed to fetch page 1: ${page1Response.status}`);
 
 
 
30
  }
31
 
32
- const page1RssData = await page1Response.text();
33
- console.log('Page 1 RSS data:', page1RssData); // Log the RSS data to see if it’s empty or malformed
34
- const parsedPage1Data = parser.parse(page1RssData); // Use the `parse` method here
35
- const page1Items = parsedPage1Data?.rss?.channel?.item || [];
36
-
37
- console.log(`Found ${page1Items.length} items on page 1`);
38
-
39
- // Fetch page 2 without proxy
40
- const page2Response = await fetch(page2Url, {
41
- headers: {
42
- 'accept': '*/*',
43
- 'accept-language': 'en-US,en;q=0.9',
44
- },
45
- method: 'GET',
46
- });
47
- if (!page2Response.ok) {
48
- throw new Error(`Failed to fetch page 2: ${page2Response.status}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  }
50
 
51
- const page2RssData = await page2Response.text();
52
- console.log('Page 2 RSS data:', page2RssData); // Log the RSS data to check for issues
53
- const parsedPage2Data = parser.parse(page2RssData); // Use the `parse` method here
54
- const page2Items = parsedPage2Data?.rss?.channel?.item || [];
55
-
56
- console.log(`Found ${page2Items.length} items on page 2`);
57
-
58
- // Combine items from both pages
59
- const allItems = [...page1Items, ...page2Items];
60
-
61
- // Map each item to the desired structure
62
- const torrentResults = await Promise.all(
63
- allItems.map(async (item) => {
64
- if (!item.title || !item.description) return null;
65
-
66
- const magnetLink = item.link; // Use the "link" as Magnet URI
67
- if (!magnetLink) return null;
68
-
69
- const sizeMatch = item.description.match(/Size:\s*([\d.]+)\s*(MB|GB|TB)/i);
70
- const size = sizeMatch ? `${sizeMatch[1]} ${sizeMatch[2]}` : 'Unknown';
71
-
72
- let sizeInBytes = 0;
73
- if (sizeMatch) {
74
- const [, value, unit] = sizeMatch;
75
- const multiplier =
76
- unit.toUpperCase() === 'TB'
77
- ? 1024 * 1024 * 1024 * 1024
78
- : unit.toUpperCase() === 'GB'
79
- ? 1024 * 1024 * 1024
80
- : 1024 * 1024;
81
- sizeInBytes = parseFloat(value) * multiplier;
82
- }
83
-
84
- const infoHashMatch = magnetLink.match(/urn:btih:([A-Za-z0-9]+)/i);
85
- const infoHash = infoHashMatch ? infoHashMatch[1] : null;
86
-
87
- let websiteTitle = item.title;
88
- if (websiteTitle.includes(' - ')) {
89
- websiteTitle = websiteTitle.split(' - ')[0];
90
- }
91
-
92
- return {
93
- magnetLink,
94
- websiteTitle,
95
- quality: extractQuality(item.title),
96
- size,
97
- source: 'BT4G',
98
- infoHash,
99
- mainFileSize: sizeInBytes,
100
- pubDate: item.pubDate,
101
- categories: Array.isArray(item.category) ? item.category : [item.category],
102
- };
103
- })
104
- );
105
-
106
- const validStreams = torrentResults.filter(Boolean);
107
-
108
- // Sort streams by quality and size (with higher quality and larger size first)
109
- validStreams.sort((a, b) => {
110
- const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
111
- const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
112
- if (qualityDiff === 0) {
113
- return b.mainFileSize - a.mainFileSize;
114
- }
115
- return qualityDiff;
116
- });
117
-
118
- console.log(`✅ Processed ${validStreams.length} valid streams`);
119
-
120
- return validStreams;
121
  } catch (error) {
122
- console.error('❌ Error fetching from BT4G:', error);
123
  return [];
124
  }
125
  }
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  export { fetchRSSFeeds };
 
1
  import { XMLParser } from 'fast-xml-parser';
2
 
 
 
 
3
  // Create a new instance of the XML parser
4
  const parser = new XMLParser({
5
  ignoreAttributes: true,
 
7
  trimValues: true,
8
  });
9
 
10
+ // Function to fetch and parse the RSS feed for a given page
11
+ async function fetchPageResults(searchQuery, page) {
12
+ const url = `https://bt4gprx.com/search?q=${encodeURIComponent(searchQuery)}&page=${page}&rss`;
13
+ console.log(`🔄 Fetching RSS feed for: ${searchQuery} (Page: ${page})`);
 
14
 
15
  try {
16
+ const response = await Promise.race([
17
+ fetch(url, {
18
+ headers: {
19
+ 'accept': '*/*',
20
+ 'accept-language': 'en-US,en;q=0.9',
21
+ },
22
+ method: 'GET',
23
+ }),
24
+ timeout(5000), // Timeout after 5 seconds
25
+ ]);
26
+
27
+ if (!response || !response.ok) {
28
+ throw new Error(`Failed to fetch from BT4G: ${response?.status || 'timeout'}`);
29
  }
30
 
31
+ const rssData = await response.text();
32
+
33
+ // Log the raw RSS data for debugging purposes
34
+ console.log("Raw RSS data from BT4G:", rssData);
35
+
36
+ // Parsing the RSS XML response
37
+ try {
38
+ const parsedData = parser.parse(rssData);
39
+ const items = parsedData?.rss?.channel?.item || [];
40
+
41
+ console.log(`Found ${items.length} items on page ${page}`);
42
+
43
+ const torrentResults = await Promise.all(
44
+ items.map(async (item) => {
45
+ if (!item.title || !item.description) return null;
46
+
47
+ const magnetLink = item.link;
48
+ if (!magnetLink) return null;
49
+
50
+ const sizeMatch = item.description.match(/Size:\s*([\d.]+)\s*(MB|GB|TB)/i);
51
+ const size = sizeMatch ? `${sizeMatch[1]} ${sizeMatch[2]}` : 'Unknown';
52
+
53
+ let sizeInBytes = 0;
54
+ if (sizeMatch) {
55
+ const [, value, unit] = sizeMatch;
56
+ const multiplier =
57
+ unit.toUpperCase() === 'TB'
58
+ ? 1024 * 1024 * 1024 * 1024
59
+ : unit.toUpperCase() === 'GB'
60
+ ? 1024 * 1024 * 1024
61
+ : 1024 * 1024;
62
+ sizeInBytes = parseFloat(value) * multiplier;
63
+ }
64
+
65
+ const infoHashMatch = magnetLink.match(/urn:btih:([A-Za-z0-9]+)/i);
66
+ const infoHash = infoHashMatch ? infoHashMatch[1] : null;
67
+
68
+ let websiteTitle = item.title;
69
+ if (websiteTitle.includes(' - ')) {
70
+ websiteTitle = websiteTitle.split(' - ')[0];
71
+ }
72
+
73
+ return {
74
+ magnetLink,
75
+ websiteTitle,
76
+ quality: extractQuality(item.title),
77
+ size,
78
+ source: 'BT4G',
79
+ infoHash,
80
+ mainFileSize: sizeInBytes,
81
+ pubDate: item.pubDate,
82
+ categories: Array.isArray(item.category) ? item.category : [item.category],
83
+ };
84
+ })
85
+ );
86
+
87
+ return torrentResults.filter(Boolean); // Filter out null values
88
+ } catch (err) {
89
+ console.error('❌ Error parsing RSS data:', err);
90
+ return [];
91
  }
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  } catch (error) {
94
+ console.error(`❌ Error fetching from BT4G (Page ${page}):`, error);
95
  return [];
96
  }
97
  }
98
 
99
+ // Function to fetch RSS feeds for both pages (1 and 2)
100
+ async function fetchRSSFeeds(searchQuery) {
101
+ const allResults = [];
102
+
103
+ // Fetch results for page 1
104
+ const page1Results = await fetchPageResults(searchQuery, 1);
105
+ allResults.push(...page1Results);
106
+
107
+ // Fetch results for page 2
108
+ const page2Results = await fetchPageResults(searchQuery, 2);
109
+ allResults.push(...page2Results);
110
+
111
+ console.log(`✅ Processed ${allResults.length} valid streams from pages 1 and 2`);
112
+
113
+ // Sort by quality and size
114
+ allResults.sort((a, b) => {
115
+ const qualityOrder = { '2160p': 4, '4k': 4, 'uhd': 4, '1080p': 3, '720p': 2 };
116
+ const qualityDiff = (qualityOrder[b.quality] || 0) - (qualityOrder[a.quality] || 0);
117
+ if (qualityDiff === 0) {
118
+ return b.mainFileSize - a.mainFileSize;
119
+ }
120
+ return qualityDiff;
121
+ });
122
+
123
+ return allResults;
124
+ }
125
+
126
  export { fetchRSSFeeds };