Update index.js
Browse files191 unmodified lines1921931941951961971981992001951961971981992002022032042052012022032042052072082092102112122132142062072082092102172182192202212222232242252262272282292302312322332342352362372382392112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622442632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line3333343353363373383392562572583403413423433443453463473483493503513522623533542642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043553063563083093103573583593603613623633643652 unmodified lines36836937037137237337437537637737832537938038138238338438538638738833338939039139213 unmodified lines4064074083534094104114124 unmodified lines4174184193644204214224231 unmodified line42542642737242842943043143243343443539 unmodified lines475476477418478479480481482483484485486487488489490491492493494191 unmodified lines }});
app.get('/player_api.php', async (req, res) => { const { username, password, ...otherParams } = req.query; const connections = await readDB(DB_PATH.connections); const connection = connections.find(c => c.iptvUsername === username && c.iptvPassword === password );// XMLTV Routeapp.get('/xmltv.php', async (req, res) => { try { const { username, password } = req.query; console.log('XMLTV request for username:', username);
if (!connection) { logger.warn('Invalid player API access', { username }); return res.status(401).send(); } const connection = await db.collection('connections').findOne({ iptvUsername: username, iptvPassword: password });
// If there are no additional parameters, return the standard auth response if (Object.keys(otherParams).length === 0) { const serverUrl = new URL(req.protocol + '://' + req.get('host')); // Convert expireDate to Unix timestamp if it exists let expTimestamp = null; if (connection.expireDate) { expTimestamp = Math.floor(new Date(connection.expireDate).getTime() / 1000); if (!connection) { console.log('Invalid XMLTV access - no connection found for:', username); return res.status(401).json({ error: 'Invalid credentials' }); }
return res.json({ user_info: { username: username, password: password, message: "", auth: 1, status: "Active", exp_date: expTimestamp, is_trial: "0", active_cons: "0", created_at: "1691612677", max_connections: "1", allowed_output_formats: ["m3u8", "ts"] }, server_info: { url: serverUrl.hostname, port: serverUrl.port || "80", https_port: "443", server_protocol: serverUrl.protocol.replace(":", ""), rtmp_port: "0", timezone: "America/New_York", timestamp_now: Math.floor(Date.now() / 1000), time_now: new Date().toISOString().replace('T', ' ').slice(0, 19) const targetUrl = `${connection.targetUrl}/xmltv.php?username=${connection.targetUsername}&password=${connection.targetPassword}`; console.log('Proxying XMLTV request to:', targetUrl);
const headers = { 'accept': 'application/xml,text/xml,*/*', 'accept-language': req.headers['accept-language'], 'user-agent': req.headers['user-agent'] };
const response = await fetch(targetUrl, { headers, timeout: 30000 });
if (!response.ok) { throw new Error(`Target server responded with status: ${response.status}`); }
res.status(response.status); const responseHeaders = { 'Content-Type': 'application/xml; charset=utf-8', 'Access-Control-Allow-Origin': '*', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' };
Object.entries(responseHeaders).forEach(([key, value]) => { if (value) { res.setHeader(key, value); } });
response.body.pipe(res);
response.body.on('error', (error) => { console.error('Error streaming XMLTV response:', error); if (!res.headersSent) { res.status(502).send('Error streaming XMLTV data'); } });
} catch (error) { console.error('XMLTV proxy error:', error); if (!res.headersSent) { res.status(502).json({ error: 'Failed to fetch XMLTV data', message: error.message }); } }});
// If there are additional parameters, proxy the request to the original server// Player API Routeapp.get('/player_api.php', async (req, res) => { try { console.log('Player API Request received with query:', req.query); const { username, password, ...otherParams } = req.query;
if (!username || !password) { console.log('Missing credentials'); return res.status(401).json({ user_info: { auth: 0, status: "Active", error: "Missing credentials" } }); }
const connection = await db.collection('connections').findOne({ iptvUsername: username, iptvPassword: password });
console.log('Connection found:', connection ? 'Yes' : 'No');
if (!connection) { console.log('No connection found for credentials'); return res.status(401).json({ user_info: { auth: 0, status: "Active", error: "Invalid credentials" } }); }
if (Object.keys(otherParams).length === 0) { console.log('Sending auth response'); const serverUrl = new URL(req.protocol + '://' + req.get('host')); let expTimestamp = connection.expireDate ? Math.floor(new Date(connection.expireDate).getTime() / 1000) : Math.floor(Date.now() / 1000) + (30 * 24 * 60 * 60); // Default 30 days
const response = { user_info: { username: username, password: password, message: "Successfully logged in", auth: 1, status: "Active", exp_date: expTimestamp, is_trial: "0", active_cons: "0", created_at: Math.floor(connection.createdAt?.getTime() / 1000) || Math.floor(Date.now() / 1000), max_connections: "1", allowed_output_formats: ["m3u8", "ts"] }, server_info: { url: serverUrl.hostname, port: serverUrl.port || "80", https_port: "443", server_protocol: serverUrl.protocol.replace(":", ""), rtmp_port: "0", timezone: "America/New_York", timestamp_now: Math.floor(Date.now() / 1000), time_now: new Date().toISOString().replace('T', ' ').slice(0, 19) } };
console.log('Sending response:', response); return res.json(response); }
console.log('Proxying request to target server with params:', otherParams); const queryParams = new URLSearchParams({ username: connection.targetUsername, password: connection.targetPassword,1 unmodified line }).toString();
const targetUrl = `${connection.targetUrl}/player_api.php?${queryParams}`; console.log('Target URL:', targetUrl);
const response = await fetch(targetUrl, { headers: { 'User-Agent': req.headers['user-agent'], 'Authorization': `Basic ${Buffer.from(`${connection.targetUsername}:${connection.targetPassword}`).toString('base64')}` } 'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0', 'Accept': 'application/json', 'Connection': 'keep-alive' }, timeout: 10000 });
if (!response.ok) { console.log('Target server error:', response.status); throw new Error(`Target server responded with status: ${response.status}`); }
const data = await response.json(); logger.info('Player API proxied', { username, params: otherParams }); console.log('Successfully received data from target server'); res.json(data); } catch (error) { logger.error('Player API proxy error', { error, username, params: otherParams }); res.status(502).send('Failed to fetch content'); }});
app.get('/xmltv.php', async (req, res) => { const { username, password } = req.query; const connection = await db.collection('connections').findOne({ iptvUsername: username, iptvPassword: password });
if (!connection) { return res.status(401).send(); }
try { const targetUrl = `${connection.targetUrl}/xmltv.php?username=${connection.targetUsername}&password=${connection.targetPassword}`; const headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'accept-language': req.headers['accept-language'], 'user-agent': req.headers['user-agent'] };
const response = await fetch(targetUrl, { headers }); res.status(response.status);
const responseHeaders = { 'Server': 'nginx', 'Date': response.headers.get('date'), 'Content-Type': 'application/xml; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Keep-Alive': 'timeout=15', 'Access-Control-Allow-Origin': '*' };
Object.entries(responseHeaders).forEach(([key, value]) => { if (value) res.setHeader(key, value); });
response.body.pipe(res); } catch (error) { if (!res.headersSent) { res.status(502).send('Failed to fetch XMLTV data'); } console.error('Player API error:', error); res.status(502).json({ error: 'Failed to fetch content', message: error.message, status: 'error' }); }});
2 unmodified lines const { username, password, id } = req.params; const type = req.path.split('/')[1];
console.log('Stream request:', { type, username, id });
const connection = await db.collection('connections').findOne({ iptvUsername: username, iptvPassword: password });
if (!connection) { return res.status(401).send(); console.log('Invalid stream access - no connection found for:', username); return res.status(401).json({ error: 'Invalid credentials' }); }
const targetUrl = `${connection.targetUrl}/${type}/${connection.targetUsername}/${connection.targetPassword}/${id}`; console.log('Proxying stream request to:', targetUrl);
try { const headers = { ...req.headers, 'User-Agent': req.headers['user-agent'], 'User-Agent': req.headers['user-agent'] || 'Mozilla/5.0', 'Range': req.headers.range }; delete headers.host;13 unmodified lines try { res.setHeader(key, value); } catch (err) { console.warn(`Could not set header ${key}`); console.warn(`Could not set header ${key}:`, err.message); } }); res.setHeader('Location', redirectUrl);4 unmodified lines try { res.setHeader(key, value); } catch (err) { console.warn(`Could not set header ${key}`); console.warn(`Could not set header ${key}:`, err.message); } }); 1 unmodified line res.send(buffer); } } catch (error) { res.status(502).json({ error: 'Failed to fetch stream URL' }); console.error('Stream proxy error:', error); res.status(502).json({ error: 'Failed to fetch stream', message: error.message }); }});
39 unmodified linesasync function startServer() { await connectDB(); await initializeAdmin(); app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); console.log('Environment:', process.env.NODE_ENV || 'development'); });}
// Handle errorsprocess.on('unhandledRejection', (error) => { console.error('Unhandled Rejection:', error);});
process.on('uncaughtException', (error) => { console.error('Uncaught Exception:', error); process.exit(1);});
startServer().catch(console.error);index.js+170-97