Naijaping

Untitled

Oct 9th, 2025
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask import Flask, request, Response
  2. import streamlink
  3. import requests
  4. import re
  5.  
  6. app = Flask(__name__)
  7.  
  8.  
  9. def modify_m3u8_content(content):
  10.     def replace_mpd_urls(line):
  11.         if line.startswith("http") and ".mpd" in line:
  12.             scheme = request.scheme
  13.             host = request.host
  14.             return re.sub(r'^(https?://[^\s]+\.mpd)', lambda match: f'{scheme}://{host}/stream?url={match.group(1)}', line)
  15.         return line
  16.  
  17.     return "\n".join(replace_mpd_urls(line) for line in content.splitlines())
  18.  
  19. @app.route('/playlist.m3u8')
  20. def get_custom_m3u8():
  21.     url = request.args.get('url')
  22.     if not url:
  23.         return "Error: No URL provided", 400
  24.     response = requests.get(url)
  25.     if response.status_code != 200:
  26.         return "Error fetching M3U8 playlist", 500
  27.     modified_content = modify_m3u8_content(response.text)
  28.     return Response(modified_content, content_type='application/vnd.apple.mpegurl')
  29.  
  30. def generate_stream(url):
  31.     session = streamlink.Streamlink()
  32.     streams = session.streams(url)
  33.    
  34.     if "best" not in streams:
  35.         raise ValueError("No valid stream found.")
  36.  
  37.     stream = streams["best"]
  38.     fd = stream.open()
  39.  
  40.     try:
  41.         while True:
  42.             chunk = fd.read(8192)
  43.             if not chunk:
  44.                 break
  45.             yield chunk
  46.     finally:
  47.         fd.close()
  48.  
  49. @app.route('/')
  50. def home():
  51.     return '''<h1>Streamlink Flask App</h1>
  52.              <form action="/stream" method="get">
  53.                <label for="url">Enter URL:</label>
  54.                <input type="text" id="url" name="url" required>
  55.                <button type="submit">Stream</button>
  56.              </form>'''
  57.  
  58. @app.route('/stream')
  59. def stream():
  60.     url = request.args.get('url')
  61.     if not url:
  62.         return "Error: No URL provided", 400
  63.    
  64.     try:
  65.         return Response(generate_stream(url), content_type='video/mp4')
  66.     except ValueError as e:
  67.         return f"Error: {e}", 400
  68.  
  69. if __name__ == '__main__':
  70.     app.run(host='0.0.0.0', port=5000, debug=True)
  71.  
Advertisement
Add Comment
Please, Sign In to add comment