Update index.js
Browse files9 unmodified lines1011121314151617181920213 unmodified lines25262728293031323334353637383 unmodified lines424344454647484950515211 unmodified lines646566676869701 unmodified line7273747576777819 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712863 unmodified lines1921931941951961971981992002012022032042052062072082092102112122132142152166 unmodified lines2232242252262272282295 unmodified lines2352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722734 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930030117 unmodified lines3193203213223233243253263273283293303311 unmodified line3333343353363373383393404 unmodified lines34534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638717 unmodified lines4054064074084094104114124132 unmodified lines4164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934949 unmodified linesconst app = express();const PORT = process.env.PORT || 3000;// MongoDB connectionconst MONGODB_URI = process.env.MONGODB_URI || 'mongodb+srv://new-iptv-manage:<db_password>@cluster0.o0eba.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0';// Validate MongoDB URIif (!MONGODB_URI.startsWith('mongodb://') && !MONGODB_URI.startsWith('mongodb+srv://')) {console.error('Invalid MongoDB URI. Must start with mongodb:// or mongodb+srv://');process.exit(1);}3 unmodified linestry {const client = await MongoClient.connect(MONGODB_URI);db = client.db();console.log('Connected to MongoDB');} catch (error) {console.error('MongoDB connection error:', error);process.exit(1);}}// Middlewareapp.use(express.json());app.use(express.urlencoded({ extended: true }));app.use(session({3 unmodified linesstore: MongoStore.create({mongoUrl: MONGODB_URI,collectionName: 'sessions',ttl: 24 * 60 * 60 // 1 day})}));// Auth check middlewareapp.use((req, res, next) => {const protectedPages = ['/hideme/dashboard.html', '/hideme/admin.html'];const loginPage = '/hideme/index.html';11 unmodified linesapp.use(express.static('public'));// Auth middlewareconst auth = (req, res, next) => {if (!req.session.userId) {return res.status(401).json({ error: 'Unauthorized' });1 unmodified linenext();};// Admin Settings Routeapp.post('/api/admin/update', auth, async (req, res) => {try {const { newUsername, newPassword, currentPassword } = req.body;19 unmodified lines}});// API Routesapp.post('/api/login', async (req, res) => {try {const { username, password } = req.body;console.log('Login attempt for username:', username);const user = await db.collection('users').findOne({ username });if (!user) {console.log('User not found:', username);return res.status(401).json({ error: 'Invalid credentials' });}const isValidPassword = await bcrypt.compare(password, user.password);console.log('Password valid:', isValidPassword);if (isValidPassword) {req.session.userId = user._id;console.log('Login successful for user:', username);res.json({ success: true });} else {console.log('Invalid password for user:', username);res.status(401).json({ error: 'Invalid credentials' });}} catch (error) {console.error('Login error:', error);res.status(500).json({ error: 'Login failed' });}});63 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'],6 unmodified lines});if (!response.ok) {throw new Error(`Target server responded with status: ${response.status}`);}res.status(response.status);5 unmodified lines};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" }});4 unmodified linesiptvPassword: 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,17 unmodified linestimestamp_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',4 unmodified lines});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'});}});// Stream routesapp.get(['/live/:username/:password/:id', '/movie/:username/:password/:id', '/series/:username/:password/:id'], async (req, res) => {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) {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 = {17 unmodified linesObject.entries(originalHeaders).forEach(([key, value]) => {try {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}:`, err.message);}});res.setHeader('Location', redirectUrl);res.end();2 unmodified linesresponse.headers.forEach((value, key) => {try {res.setHeader(key, value);} catch (err) {console.warn(`Could not set header ${key}:`, err.message);}});const buffer = await response.buffer();res.send(buffer);}} catch (error) {console.error('Stream proxy error:', error);res.status(502).json({error: 'Failed to fetch stream',message: error.message});}});// Initialize admin userasync function initializeAdmin() {try {// First, drop existing users collection to ensure clean stateawait db.collection('users').drop().catch(() => console.log('No users collection to drop'));// Create admin userconst defaultUsername = process.env.ADMIN_USERNAME || 'admin';const defaultPassword = process.env.ADMIN_PASSWORD || 'admin';console.log('Creating admin user with username:', defaultUsername);const hashedPassword = await bcrypt.hash(defaultPassword, 10);const result = await db.collection('users').insertOne({username: defaultUsername,password: hashedPassword,createdAt: new Date(),isAdmin: true});console.log('Admin user created successfully:', {username: defaultUsername,id: result.insertedId,timestamp: new Date()});// Verify the user was createdconst verifyUser = await db.collection('users').findOne({ username: defaultUsername });if (verifyUser) {console.log('Verified admin user exists in database');} else {console.error('Failed to verify admin user creation');}} catch (error) {console.error('Error initializing admin user:', error);throw error;}}// Start serverasync 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);9 unmodified lines1011121314151617183 unmodified lines22232425262728293031323 unmodified lines3637383940414243444511 unmodified lines5758596061621 unmodified line64656667686919 unmodified lines899091929394959697989910010110210310410510610710810911011163 unmodified lines1751761771781791801811821831841851861871881891901911921936 unmodified lines2002012022032042052065 unmodified lines2122132142152162172182192202212222232242252262272282292302312322334 unmodified lines23823924024124224324424524624724824925025125225325425525625717 unmodified lines2752762772782792802812822831 unmodified line2852862872882892904 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632717 unmodified lines3453463473483493503512 unmodified lines3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973989 unmodified linesconst app = express();const PORT = process.env.PORT || 3000;const MONGODB_URI = process.env.MONGODB_URI || 'mongodb+srv://new-iptv-manage:<db_password>@cluster0.o0eba.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0';if (!MONGODB_URI.startsWith('mongodb://') && !MONGODB_URI.startsWith('mongodb+srv://')) {process.exit(1);}3 unmodified linestry {const client = await MongoClient.connect(MONGODB_URI);db = client.db();} catch (error) {process.exit(1);}}app.use(express.json());app.use(express.urlencoded({ extended: true }));app.use(session({3 unmodified linesstore: MongoStore.create({mongoUrl: MONGODB_URI,collectionName: 'sessions',ttl: 24 * 60 * 60})}));app.use((req, res, next) => {const protectedPages = ['/hideme/dashboard.html', '/hideme/admin.html'];const loginPage = '/hideme/index.html';11 unmodified linesapp.use(express.static('public'));const auth = (req, res, next) => {if (!req.session.userId) {return res.status(401).json({ error: 'Unauthorized' });1 unmodified linenext();};app.post('/api/admin/update', auth, async (req, res) => {try {const { newUsername, newPassword, currentPassword } = req.body;19 unmodified lines}});app.post('/api/login', async (req, res) => {try {const { username, password } = req.body;const user = await db.collection('users').findOne({ username });if (!user) {return res.status(401).json({ error: 'Invalid credentials' });}const isValidPassword = await bcrypt.compare(password, user.password);if (isValidPassword) {req.session.userId = user._id;res.json({ success: true });} else {res.status(401).json({ error: 'Invalid credentials' });}} catch (error) {res.status(500).json({ error: 'Login failed' });}});63 unmodified lines}});app.get('/xmltv.php', async (req, res) => {try {const { username, password } = req.query;const connection = await db.collection('connections').findOne({iptvUsername: username,iptvPassword: password});if (!connection) {return res.status(401).json({ error: 'Invalid credentials' });}const targetUrl = `${connection.targetUrl}/xmltv.php?username=${connection.targetUsername}&password=${connection.targetPassword}`;const headers = {'accept': 'application/xml,text/xml,*/*','accept-language': req.headers['accept-language'],6 unmodified lines});if (!response.ok) {throw new Error(`Target server error: ${response.status}`);}res.status(response.status);5 unmodified lines};Object.entries(responseHeaders).forEach(([key, value]) => {if (value) res.setHeader(key, value);});response.body.pipe(res);} catch (error) {if (!res.headersSent) {res.status(502).json({ error: 'Failed to fetch XMLTV data' });}}});app.get('/player_api.php', async (req, res) => {try {const { username, password, ...otherParams } = req.query;if (!username || !password) {return res.status(401).json({user_info: { auth: 0, status: "Active", error: "Missing credentials" }});4 unmodified linesiptvPassword: password});if (!connection) {return res.status(401).json({user_info: { auth: 0, status: "Active", error: "Invalid credentials" }});}if (Object.keys(otherParams).length === 0) {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);return res.json({user_info: {username: username,password: password,17 unmodified linestimestamp_now: Math.floor(Date.now() / 1000),time_now: new Date().toISOString().replace('T', ' ').slice(0, 19)}});}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'] || 'Mozilla/5.0',4 unmodified lines});if (!response.ok) {throw new Error(`Target server error: ${response.status}`);}const data = await response.json();res.json(data);} catch (error) {res.status(502).json({error: 'Failed to fetch content',status: 'error'});}});app.get(['/live/:username/:password/:id', '/movie/:username/:password/:id', '/series/:username/:password/:id'], async (req, res) => {const { 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).json({ error: 'Invalid credentials' });}const targetUrl = `${connection.targetUrl}/${type}/${connection.targetUsername}/${connection.targetPassword}/${id}`;try {const headers = {17 unmodified linesObject.entries(originalHeaders).forEach(([key, value]) => {try {res.setHeader(key, value);} catch (err) {}});res.setHeader('Location', redirectUrl);res.end();2 unmodified linesresponse.headers.forEach((value, key) => {try {res.setHeader(key, value);} catch (err) {}});const buffer = await response.buffer();res.send(buffer);}} catch (error) {res.status(502).json({ error: 'Failed to fetch stream' });}});async function initializeAdmin() {try {await db.collection('users').drop().catch(() => {});const defaultUsername = process.env.ADMIN_USERNAME || 'admin';const defaultPassword = process.env.ADMIN_PASSWORD || 'admin';const hashedPassword = await bcrypt.hash(defaultPassword, 10);await db.collection('users').insertOne({username: defaultUsername,password: hashedPassword,createdAt: new Date(),isAdmin: true});} catch (error) {throw error;}}async function startServer() {await connectDB();await initializeAdmin();app.listen(PORT);}process.on('unhandledRejection', (error) => {});process.on('uncaughtException', (error) => {process.exit(1);});startServer();
index.js+18-114