samipote

Untitled

Aug 26th, 2023
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.45 KB | None | 0 0
  1. const express = require('express');
  2. const mongoose = require('mongoose');
  3. const cors = require('cors');
  4. const path = require('path');
  5. const methodOverride = require('method-override');
  6. const request = require('request');
  7. const restream = require('restream');
  8. const app = express();
  9. app.set('host', 'sportswatcher.ddns.net');
  10. const fs = require('fs');
  11. const fetch = require('node-fetch');
  12. const http = require('http').createServer(app);
  13. const { exec } = require('child_process');
  14. const { spawn } = require('child_process');
  15. const io = require('socket.io')(http, {
  16. cors: {
  17. origin: "*", // Adjust this according to your needs
  18. methods: ["GET", "POST"],
  19. debug : true,
  20. transports: ['websocket']
  21. }
  22. });
  23.  
  24.  
  25. app.use(express.json()); // Parse JSON bodies
  26. app.use(express.urlencoded({ extended: true })); // Parse URL-encoded bodies
  27. app.use(cors()); // Enable CORS
  28. app.use(methodOverride('_method')); // Enable method override
  29.  
  30. // Replace with your MongoDB connection string
  31. const connectionString = 'mongodb://localhost:27017/streaming';
  32.  
  33. // Connect to MongoDB
  34. mongoose
  35. .connect(connectionString, {
  36. useNewUrlParser: true,
  37. useUnifiedTopology: true,
  38. })
  39. .then(() => {
  40. console.log('Connected to MongoDB');
  41. })
  42. .catch((error) => {
  43. console.error('Failed to connect to MongoDB', error);
  44. });
  45.  
  46. // Define a Mongoose schema for our Game model
  47. const gameSchema = new mongoose.Schema({
  48. title: String,
  49. streamLink: String,
  50. sport: String,
  51. });
  52.  
  53. const chatMessageSchema = new mongoose.Schema({
  54. username: String,
  55. content: String,
  56. timestamp: { type: Date, default: Date.now }
  57. });
  58.  
  59. const ChatMessage = mongoose.model('ChatMessage', chatMessageSchema);
  60.  
  61. io.on('connection', (socket) => {
  62. console.log('a user connected');
  63.  
  64. socket.on('chat message', (msg) => {
  65. io.emit('message', msg); // broadcasting the message to all clients
  66. });
  67.  
  68. socket.on('disconnect', () => {
  69. console.log('user disconnected');
  70. });
  71. });
  72.  
  73. // Create the Game model
  74. const Game = mongoose.model('Game', gameSchema);
  75.  
  76. // Serve static files from the public directory
  77. app.use(express.static(path.join(__dirname, 'public')));
  78.  
  79. const proxyAddress = 'http://localhost:8080/';
  80. process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
  81.  
  82. // A function that returns a modified URL for .ts files
  83. function getTSURL(targetURL) {
  84. const baseURL = getBaseURL();
  85. return baseURL + 'ts/' + targetURL.replace('https://', '');
  86. }
  87.  
  88. app.get('/chat-messages', async (req, res) => {
  89. try {
  90. const messages = await ChatMessage.find().sort({timestamp: -1}).limit(50); // get the last 50 messages
  91. res.send(messages);
  92. } catch (error) {
  93. res.status(500).send(error);
  94. }
  95. });
  96.  
  97. app.use('/proxy/', (req, res) => {
  98. const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl;
  99. const { pathname, search } = new URL(fullURL);
  100. const targetURL = pathname.replace('/proxy/', 'https://') + search;
  101.  
  102. const curl = spawn('curl', [
  103. '-H', 'Origin: https://www.nolive.me',
  104. '-H', 'Referer: https://www.nolive.me/',
  105. '-H', 'User-Agent: Mozilla/5.0...',
  106. // Add any other headers you need
  107. targetURL
  108. ]);
  109.  
  110. curl.stdout.pipe(res);
  111. curl.stderr.on('data', (data) => {
  112. console.error(`curl stderr: ${data}`);
  113. });
  114.  
  115. curl.on('close', (code) => {
  116. if (code !== 0) {
  117. console.error(`curl process exited with code ${code}`);
  118. }
  119. });
  120. });
  121.  
  122. // A new route for handling .ts requests
  123. app.use('/ts/', (req, res) => {
  124. const fullURL = req.protocol + '://' + req.get('host') + req.originalUrl;
  125. const { pathname, search } = new URL(fullURL);
  126. const targetURL = pathname.replace('/ts/', 'https://') + search;
  127. const proxyHeaders = {
  128. 'Origin': 'https://www.nolive.me',
  129. 'Referer': 'https://www.nolive.me/',
  130. 'User-Agent': 'Mozilla/5.0...',
  131. 'Host': 'ed-t3.edghst.me'
  132. }
  133.  
  134. const proxyRequestOptions = {
  135. url: targetURL,
  136. method: req.method,
  137. headers: proxyHeaders,
  138. followRedirect: true
  139. };
  140. const proxyRequest = request(proxyRequestOptions);
  141.  
  142. proxyRequest.on('response', function(sourceResponse) {
  143. Object.keys(sourceResponse.headers).forEach(headerKey => {
  144. res.setHeader(headerKey, sourceResponse.headers[headerKey]);
  145. });
  146. let contentType = sourceResponse.headers['content-type'];
  147. if (!contentType || contentType === 'application/octet-stream') {
  148. res.setHeader('Content-Type', 'video/MP2T');
  149. }
  150. res.setHeader('Access-Control-Allow-Origin', '*');
  151. sourceResponse.pipe(res);
  152. });
  153.  
  154. proxyRequest.on('error', function(err) {
  155. console.error('Proxy Error for URL:', targetURL, 'Error:', err.message);
  156. res.status(500).send('Proxy Error');
  157. });
  158.  
  159. res.on('error', (err) => {
  160. console.error('Error during response pipe:', err);
  161. });
  162.  
  163. req.pipe(restream()).pipe(proxyRequest);
  164. });
  165.  
  166. function getBaseURL() {
  167. return `http://${app.get('host')}/`;
  168. }
  169.  
  170. app.get('/', (req, res) => {
  171. res.render('main.ejs');
  172. });
  173.  
  174. // Route for serving the admin panel
  175. app.get('/admin', async (req, res) => {
  176. try {
  177. const games = await Game.find();
  178. res.render('admin.ejs', { videos: games });
  179. } catch (error) {
  180. res.status(500).send(error);
  181. }
  182. });
  183.  
  184. // Route for getting all games
  185. app.get('/games', async (req, res) => {
  186. try {
  187. const games = await Game.find();
  188. res.send(games);
  189. } catch (error) {
  190. res.status(500).send(error);
  191. }
  192. });
  193.  
  194. // Route for creating a new game
  195. app.post('/games', async (req, res) => {
  196. try {
  197. const game = new Game(req.body);
  198. await game.save();
  199. res.redirect('/admin');
  200. } catch (error) {
  201. res.status(500).send(error);
  202. }
  203. });
  204.  
  205. app.put('/games/:id', async (req, res) => {
  206. try {
  207. const { id } = req.params;
  208. const { title, streamLink, sport } = req.body;
  209. const updatedGame = await Game.findByIdAndUpdate(id, { title, streamLink, sport }, { new: true });
  210. res.redirect('/admin');
  211. } catch (error) {
  212. res.status(500).send(error);
  213. }
  214. });
  215.  
  216. // Route for deleting a game
  217. app.delete('/games/:id', async (req, res) => {
  218. try {
  219. await Game.deleteOne({ _id: req.params.id });
  220. res.redirect('/admin');
  221. } catch (error) {
  222. res.status(500).send(error);
  223. }
  224. });
  225. io.on('connect_error', (error) => {
  226. console.log('Connection Error: ', error);
  227. });
  228. // Start the server
  229. const port = process.env.PORT || 3000;
  230. http.listen(port, () => console.log(`Server running on port ${port}`));
Advertisement
Add Comment
Please, Sign In to add comment