Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
- const express = require('express');
- const mongoose = require('mongoose');
- const cors = require('cors');
- const path = require('path');
- const methodOverride = require('method-override');
- const axios = require('axios'); // Import axios
- const app = express();
- app.set('host', 'sportswatcher.ddns.net');
- const fs = require('fs');
- const fetch = require('node-fetch');
- app.use(express.json()); // Parse JSON bodies
- app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
- app.use(cors()); // Enable CORS
- app.use(methodOverride('_method')); // Enable method override
- const https = require('https');
- const agent = new https.Agent({
- rejectUnauthorized: false // or 'TLSv1_3_method', 'TLSv1_1_method', 'TLSv1_method'
- });
- // Replace with your MongoDB connection string
- const connectionString = 'mongodb://localhost:27017/streaming';
- // Connect to MongoDB
- mongoose
- .connect(connectionString, { useNewUrlParser: true, useUnifiedTopology: true, })
- .then(() => {
- console.log('Connected to MongoDB');
- })
- .catch((error) => {
- console.error('Failed to connect to MongoDB', error);
- });
- // Define a Mongoose schema for our Game model
- const gameSchema = new mongoose.Schema({
- title: String,
- streamLink: String,
- sport: String,
- });
- // Create the Game model
- const Game = mongoose.model('Game', gameSchema);
- // Serve static files from the public directory
- app.use(express.static(path.join(__dirname, 'public')));
- const proxyAddress = 'http://localhost:8080/';
- // A function that returns a modified URL for .ts files
- function getTSURL(targetURL) {
- const baseURL = getBaseURL();
- return baseURL + 'ts/' + targetURL.replace('https://', '');
- }
- function resolveURL(base, relative) {
- const baseURL = new URL(base);
- return new URL(relative, baseURL).toString();
- }
- app.use('/proxy/', async (req, res, next) => {
- const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl;
- const { pathname, search } = new URL(fullURL);
- console.log(`Received request for URL: ${fullURL}`);
- const targetURL = pathname.replace('/proxy/', 'https://') + search;
- if (path.extname(targetURL).toLowerCase() === '.m3u8') {
- try {
- const m3u8Response = await fetch(targetURL);
- let m3u8Content = await m3u8Response.text();
- m3u8Content = m3u8Content.split('\n').map(line => {
- if (line.endsWith('.ts')) {
- const tsURL = line.startsWith('http') ? line : resolveURL(targetURL, line);
- return getTSURL(tsURL);
- } else {
- return line;
- }
- }).join('\n');
- res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
- res.setHeader('Access-Control-Allow-Origin', '*');
- res.send(m3u8Content);
- } catch (err) {
- console.error('Failed to fetch m3u8:', err.message);
- res.status(500).send('Proxy Error');
- }
- return;
- }
- // Use axios instead of request and restream
- try {
- const proxyResponse = await axios.get(targetURL, {
- headers: { ...req.headers },
- httpsAgent: agent
- });
- Object.keys(proxyResponse.headers).forEach(headerKey => {
- res.setHeader(headerKey, proxyResponse.headers[headerKey]);
- });
- let contentType = proxyResponse.headers['content-type'];
- if (!contentType || contentType === 'application/octet-stream') {
- const extname = path.extname(targetURL).toLowerCase();
- if (extname === '.m4s') {
- res.setHeader('Content-Type', 'application/dash+xml');
- } else if (extname === '.ts') {
- res.setHeader('Content-Type', 'video/MP2T');
- } else {
- res.setHeader('Content-Type', 'application/x-mpegURL');
- }
- }
- res.setHeader('Access-Control-Allow-Origin', '*');
- proxyResponse.data.pipe(res); // Pipe the data stream to the response
- } catch (err) {
- console.error('Proxy Error for URL:', targetURL, 'Error:', err.message);
- res.status(500).send('Proxy Error');
- }
- });
- // A new route for handling .ts requests
- app.use('/ts/', async (req, res) => { // Use async function
- const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl;
- const { pathname, search } = new URL(fullURL);
- console.log(`Received request for URL: ${fullURL}`);
- const targetURL = pathname.replace('/ts/', 'https://') + search;
- // Use axios instead of request and restream
- try {
- const proxyResponse = await axios.get(targetURL, {
- headers: { ...req.headers },
- httpsAgent: agent
- });
- Object.keys(proxyResponse.headers).forEach(headerKey => {
- res.setHeader(headerKey, proxyResponse.headers[headerKey]);
- });
- let contentType = proxyResponse.headers['content-type'];
- if (!contentType || contentType === 'application/octet-stream') {
- res.setHeader('Content-Type', 'video/MP2T');
- }
- res.setHeader('Access-Control-Allow-Origin', '*');
- proxyResponse.data.pipe(res); // Pipe the data stream to the response
- } catch (err) {
- console.error('Proxy Error for URL:', targetURL, 'Error:', err.message);
- res.status(500).send('Proxy Error');
- }
- });
- function getBaseURL() {
- return `http://${app.get('host')}/`;
- }
- app.get('/', (req, res) => {
- res.render('main.ejs');
- });
- // Route for serving the admin panel
- app.get('/admin', async (req, res) => {
- try {
- const games = await Game.find();
- res.render('admin.ejs', { videos: games });
- } catch (error) {
- res.status(500).send(error);
- }
- });
- // Route for getting all games
- app.get('/games', async (req, res) => {
- try {
- const games = await Game.find();
- res.send(games);
- } catch (error) {
- res.status(500).send(error);
- }
- });
- // Route for creating a new game
- app.post('/games', async (req, res) => {
- try {
- const game = new Game(req.body);
- await game.save();
- res.redirect('/admin');
- } catch (error) {
- res.status(500).send(error);
- }
- });
- app.put('/games/:id', async (req, res) => {
- try {
- const { id } = req.params;
- const { title, streamLink, sport } = req.body;
- const updatedGame = await Game.findByIdAndUpdate(id, { title, streamLink, sport }, { new: true });
- res.redirect('/admin');
- } catch (error) {
- res.status(500).send(error);
- }
- });
- // Route for deleting a game
- app.delete('/games/:id', async (req, res) => {
- try {
- await Game.deleteOne({ _id: req.params.id });
- res.redirect('/admin');
- } catch (error) {
- res.status(500).send(error);
- }
- });
- // Start the server
- const port = process.env.PORT || 3000;
- app.listen(port, () => console.log(`Server running on port ${port}`));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement