stream-api/stream.py
2021-05-01 20:01:24 +02:00

74 lines
2.4 KiB
Python
Executable File

#!/usr/bin/env python3
import streamlink
import tornado.web
import tornado.routing
import requests
import os
providers = {}
providers["nrk"] = "https://tv.nrk.no"
providers["svt"] = "https://svtplay.se"
providers["youtube"] = "https://youtu.be"
providers["twitch"] = "https://twitch.tv"
proxies = {}
proxies["nrk"] = streamlink.Streamlink()
proxies["svt"] = streamlink.Streamlink()
proxies["youtube"] = streamlink.Streamlink()
proxies["twitch"] = streamlink.Streamlink()
for key in proxies:
proxy = os.environ.get(key.upper() + "_PROXY")
proxies[key].set_option("http-timeout", 2.0)
if proxy is not None:
proxies[key].set_option("https-proxy", proxy)
class MainHandler(tornado.web.RequestHandler):
def handle_any(self, write):
provider = self.get_query_argument("provider", None)
endpoint = None
if provider is not None and provider in providers.keys():
proxy = proxies.get(provider)
src = providers[provider] + self.request.uri
try:
resp = requests.get(src)
if resp is not None:
src = resp.url
except Exception as e:
print(e)
else:
try:
streams = proxy.streams(src)
for key in reversed(streams):
stream = streams.get(key)
if hasattr(stream, "url"):
endpoint = stream.url
break
except Exception as e:
print(str(e))
endpoint = None
if endpoint is None:
self.set_status(404, reason="stream not found")
else:
self.redirect(endpoint, status=303)
def get(self):
self.handle_any(True)
def head(self):
self.handle_any(False)
class FileHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("Content-Type", "text/plain; charset=utf-8")
with open("/app/sources.m3u8", "r") as f:
self.write(f.read())
try:
handlers = []
handlers.append((tornado.routing.PathMatches("/sources.m3u8"), FileHandler))
handlers.append((tornado.routing.AnyMatches(), MainHandler))
app_web = tornado.web.Application(handlers)
app_web.listen(8080)
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
print()