Update index.js
Browse files191 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472481 unmodified line2502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123132 unmodified lines31631731831932032132232332432532632732832933033133233333433533613 unmodified lines3503513523533543553564 unmodified lines3613623633643653663671 unmodified line36937037137237337437539 unmodified lines415416417418419420421191 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);if (!connection) {logger.warn('Invalid player API access', { username });return res.status(401).send();}// If there are no additional parameters, return the standard auth responseif (Object.keys(otherParams).length === 0) {const serverUrl = new URL(req.protocol + '://' + req.get('host'));// Convert expireDate to Unix timestamp if it existslet expTimestamp = null;if (connection.expireDate) {expTimestamp = Math.floor(new Date(connection.expireDate).getTime() / 1000);}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)}});}// If there are additional parameters, proxy the request to the original servertry {const queryParams = new URLSearchParams({username: connection.targetUsername,password: connection.targetPassword,1 unmodified line}).toString();const targetUrl = `${connection.targetUrl}/player_api.php?${queryParams}`;const response = await fetch(targetUrl, {headers: {'User-Agent': req.headers['user-agent'],'Authorization': `Basic ${Buffer.from(`${connection.targetUsername}:${connection.targetPassword}`).toString('base64')}`}});const data = await response.json();logger.info('Player API proxied', { username, params: otherParams });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');}}});2 unmodified linesconst { username, password, id } = req.params;const type = req.path.split('/')[1];const connection = await db.collection('connections').findOne({iptvUsername: username,iptvPassword: password});if (!connection) {return res.status(401).send();}const targetUrl = `${connection.targetUrl}/${type}/${connection.targetUsername}/${connection.targetPassword}/${id}`;try {const headers = {...req.headers,'User-Agent': req.headers['user-agent'],'Range': req.headers.range};delete headers.host;13 unmodified linestry {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}`);}});res.setHeader('Location', redirectUrl);4 unmodified linestry {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}`);}});1 unmodified lineres.send(buffer);}} catch (error) {res.status(502).json({ error: 'Failed to fetch stream URL' });}});39 unmodified linesasync function startServer() {await connectDB();await initializeAdmin();app.listen(PORT, () => console.log(`Server running on port ${PORT}`));}startServer().catch(console.error);191 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line3333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643652 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139213 unmodified lines4064074084094104114124 unmodified lines4174184194204214224231 unmodified line42542642742842943043143243343443539 unmodified lines475476477478479480481482483484485486487488489490491492493494191 unmodified lines}});// XMLTV Routeapp.get('/xmltv.php', async (req, res) => {try {const { username, password } = req.query;console.log('XMLTV request for username:', username);const connection = await db.collection('connections').findOne({iptvUsername: username,iptvPassword: password});if (!connection) {console.log('Invalid XMLTV access - no connection found for:', username);return res.status(401).json({ error: 'Invalid credentials' });}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});}}});// 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 daysconst 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'] || '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();console.log('Successfully received data from target server');res.json(data);} catch (error) {console.error('Player API error:', error);res.status(502).json({error: 'Failed to fetch content',message: error.message,status: 'error'});}});2 unmodified linesconst { 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) {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'] || 'Mozilla/5.0','Range': req.headers.range};delete headers.host;13 unmodified linestry {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}:`, err.message);}});res.setHeader('Location', redirectUrl);4 unmodified linestry {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}:`, err.message);}});1 unmodified lineres.send(buffer);}} catch (error) {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 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