-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
210 lines (177 loc) · 7.06 KB
/
server.js
File metadata and controls
210 lines (177 loc) · 7.06 KB
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
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// Request tracking
let activeRequests = 0;
let clients = [];
// Middleware
app.use(cors());
app.use(express.json());
// Middleware to track active requests
app.use((req, res, next) => {
if (req.path.startsWith('/api/v1/')) {
activeRequests++;
notifyClients();
// Decrement when the response is finished or closed
res.on('finish', () => {
activeRequests = Math.max(0, activeRequests - 1);
notifyClients();
});
res.on('close', () => {
// Check if it was already decremented via 'finish'
// Express 'finish' usually handles this, but 'close' is a fallback for aborted requests
});
}
next();
});
function notifyClients() {
const data = JSON.stringify({ activeRequests });
clients.forEach(client => client.res.write(`data: ${data}\n\n`));
}
// SSE endpoint for live stats
app.get('/api/live-stats', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
const clientId = Date.now();
const newClient = { id: clientId, res };
clients.push(newClient);
// Send initial count
res.write(`data: ${JSON.stringify({ activeRequests })}\n\n`);
req.on('close', () => {
clients = clients.filter(client => client.id !== clientId);
});
});
// 1. Root endpoint: /
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index', 'index.html'));
});
// // 2. Get all games endpoint (DEPRECATED: now using dynamic scraping)
// app.get('/api/v1/games', (req, res) => {
// res.json({
// message: "This endpoint is deprecated as the API now uses dynamic scraping to support any Steam ID.",
// games: []
// });
// });
// 3. Get popular games from SteamSpy
app.get('/api/v1/popular', async (req, res) => {
try {
const spyResponse = await fetch('https://steamspy.com/api.php?request=top100forever');
if (spyResponse.ok) {
const data = await spyResponse.json();
const steamSpyIds = Object.keys(data);
// Return all top IDs since we can now scrape any game on the fly
res.json({ popular: steamSpyIds });
} else {
res.status(spyResponse.status).json({ error: 'Failed to fetch popular games from SteamSpy API' });
}
} catch (e) {
console.error('Error fetching SteamSpy API for popular games:', e.message);
res.status(500).json({ error: 'Failed to fetch popular games' });
}
});
// 4. Get a specific game by ID endpoint: /id
app.get('/api/v1/:id', async (req, res) => {
const gameId = req.params.id;
// 1. Fetch data from Steam API first to get the title
let steamData = null;
let gameTitle = null;
try {
const steamResponse = await fetch(`https://store.steampowered.com/api/appdetails?appids=${gameId}`);
if (steamResponse.ok) {
const steamJson = await steamResponse.json();
if (steamJson[gameId] && steamJson[gameId].success) {
steamData = steamJson[gameId].data;
gameTitle = steamData.name;
} else {
steamData = { error: 'Game not found on Steam store.' };
}
} else {
steamData = { error: `Steam API responded with status ${steamResponse.status}` };
}
} catch (e) {
console.error(`Error fetching Steam API for game ${gameId}:`, e.message);
steamData = { error: 'Failed to fetch from Steam API', details: e.message };
}
// 2. Dynamically Scrape download data if we have a title
let downloadData = null;
if (gameTitle) {
console.log(`Searching FitGirl for: ${gameTitle}...`);
downloadData = await scrapeFitGirl(gameTitle);
}
if (!downloadData) {
return res.status(404).json({
id: gameId,
steam_data: steamData,
error: 'Nah bro we can\'t find any download links for this game on fitgirl.'
});
}
// Return the combined Response (matching original structure)
res.json({
id: gameId,
steam_data: steamData,
download_data: downloadData
});
});
// Helper function to scrape links directly from FitGirl website
async function scrapeFitGirl(gameTitle) {
try {
// Search for the game title on FitGirl site
const searchUrl = `https://fitgirl-repacks.site/?s=${encodeURIComponent(gameTitle)}`;
const searchResponse = await fetch(searchUrl);
if (!searchResponse.ok) return null;
const searchHtml = await searchResponse.text();
// Find the first post link in search results
const postLinkMatch = searchHtml.match(/<h1 class="entry-title"><a href="(https:\/\/fitgirl-repacks\.site\/[^"]+)"/);
if (!postLinkMatch) return null;
const postUrl = postLinkMatch[1];
// Fetch the actual post page
const postResponse = await fetch(postUrl);
if (!postResponse.ok) return null;
const postHtml = await postResponse.text();
// Extract links using regex (hosters like fuckingfast, datanodes, etc., and magnet links)
const links = [];
const linkRegex = /href="((?:https?:\/\/(?:fuckingfast\.co|datanodes\.to|multiupload\.io|1337x\.to|tapochek\.net|datanodes\.to)[^"]+)|(?:magnet:\?xt=[^"]+))"/g;
let match;
while ((match = linkRegex.exec(postHtml)) !== null) {
const url = match[1];
// Determine category based on URL
let category = 'Other';
if (url.startsWith('magnet:')) {
category = 'Magnet';
} else if (url.includes('1337x')) {
category = '1337x (Torrent)';
} else if (url.includes('tapochek.net')) {
category = 'Tapochek (Torrent)';
} else if (url.includes('.torrent')) {
category = 'Torrent File';
} else if (url.includes('fuckingfast.co')) {
category = 'FuckingFast';
} else if (url.includes('datanodes.to')) {
category = 'DataNodes';
} else if (url.includes('multiupload.io')) {
category = 'MultiUpload';
} else {
category = 'Direct Link';
}
if (!links.some(l => l.url === url)) {
links.push({ category, url });
}
}
if (links.length === 0) return null;
return {
parsed_links: links,
// You can optionally add more fields here if needed, but keeping it minimal to match previous structure
};
} catch (error) {
console.error('Scraping error:', error);
return null;
}
}
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});