stream-api/stream.py

304 lines
12 KiB
Python
Raw Normal View History

2021-04-30 08:49:10 +00:00
#!/usr/bin/env python3
2021-05-11 12:45:33 +00:00
import json
import urllib.parse
import re
import os
2021-04-30 08:49:10 +00:00
import streamlink
import tornado.web
import tornado.routing
2021-04-30 11:26:55 +00:00
import requests
2021-05-12 07:59:02 +00:00
import base64
2021-05-13 07:16:47 +00:00
import logging
logging.basicConfig(format='[%(filename)s:%(lineno)d] %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
2021-04-30 08:49:10 +00:00
providers = {}
providers["nrk"] = "https://tv.nrk.no"
providers["svt"] = "https://svtplay.se"
2021-05-11 12:00:43 +00:00
providers["youtube"] = "https://www.youtube.com/watch?v="
2021-04-30 11:26:55 +00:00
providers["twitch"] = "https://twitch.tv"
2021-04-30 08:49:10 +00:00
2021-05-11 12:00:43 +00:00
class ProxyElem():
def __init__(self, proxy):
self.proxy = proxy
self.req = {}
if proxy is not None:
self.req["http"] = "socks5://" + proxy
self.req["https"] = "socks5://" + proxy
2021-05-13 08:04:39 +00:00
def stream(self):
session = streamlink.Streamlink()
session.set_option("http-timeout", 2.0)
2021-05-13 08:26:59 +00:00
if self.proxy is not None:
2021-05-13 08:04:39 +00:00
session.set_option("https-proxy", "socks5://" + self.proxy)
session.set_option("http-proxy", "socks5://" + self.proxy)
return session
2021-05-11 14:33:18 +00:00
def __repr__(self):
2021-05-13 06:31:50 +00:00
return str(self.proxy)
2021-05-11 14:33:18 +00:00
2021-05-11 12:00:43 +00:00
proxies = {}
2021-05-08 17:08:54 +00:00
for key in providers:
2021-05-11 12:19:17 +00:00
proxies[key] = []
current = []
for i in range(0,9):
proxy = os.environ.get(f'{key}_proxy{i}'.upper())
if proxy is not None:
current.append(proxy)
if len(current) == 0:
proxies[key].append(ProxyElem(None))
else:
for proxy in current:
proxies[key].append(ProxyElem(proxy))
2021-04-30 11:55:10 +00:00
2021-05-06 13:23:43 +00:00
playlist = None
icecast_server = os.environ.get("ICECAST_SERVER")
stream_server = os.environ.get("STREAM_SERVER")
2021-05-08 17:08:54 +00:00
proxy_server = os.environ.get("PROXY_SERVER")
2021-05-06 13:54:18 +00:00
2021-05-06 13:23:43 +00:00
if icecast_server is not None and stream_server is not None:
with open("/app/sources.json", "r") as f:
data = json.loads(f.read())
playlist = "#EXTM3U\n"
for key in data:
current = data[key]
name = current["name"]
radio = current["radio"]
if radio:
playlist += f'#EXTINF:0 radio="true", {name}\n'
playlist += icecast_server + key + "\n"
else:
playlist += f'#EXTINF:0 radio="false", {name}\n'
playlist += stream_server + key + "\n"
2021-05-12 07:50:51 +00:00
template_html = None
template_js = None
2021-05-13 12:22:11 +00:00
template_embed = tornado.template.Template('<iframe src="{{ origin }}?provider={{ provider }}&render=true"></iframe>')
2021-05-13 11:29:49 +00:00
2021-05-10 15:47:34 +00:00
videojs_version = None
2021-05-12 12:57:50 +00:00
castjs_version = None
2021-05-13 09:15:40 +00:00
custom_style = None
2021-05-09 16:49:40 +00:00
try:
with open("/app/index.html", "r") as f:
2021-05-12 07:50:51 +00:00
template_html = tornado.template.Template(f.read().strip())
with open("/app/script.js", "r") as f:
template_js = tornado.template.Template(f.read().strip())
2021-05-10 15:40:38 +00:00
with open("/app/videojs-version.txt", "r") as f:
videojs_version = f.read().strip()
2021-05-13 09:15:40 +00:00
with open("/app/chromecast-version.txt", "r") as f:
chromecast_version = f.read().strip()
with open("/app/style.css", "r") as f:
custom_style_raw = bytes(f.read().strip(), "utf-8")
b64 = str(base64.b64encode(custom_style_raw), "ascii")
custom_style = f'data:text/css;charset=utf-8;base64,{b64}'
2021-05-10 15:40:38 +00:00
except Exception as e:
2021-05-13 07:16:47 +00:00
logger.info(e)
2021-05-10 15:40:38 +00:00
2021-05-09 10:37:36 +00:00
def get_proxy_url(proxy, current, path):
data = {}
data["upstream"] = urllib.parse.urljoin(current, path)
2021-05-09 19:12:14 +00:00
data["proxied"] = True
2021-05-09 10:37:36 +00:00
ret = None
2021-05-09 19:12:14 +00:00
if proxy is None:
data["proxied"] = False
else:
data["proxy"] = proxy
if proxy_server is None:
2021-05-09 10:37:36 +00:00
return data["upstream"]
presp = requests.post(proxy_server, json=data)
return presp.text
2021-05-11 22:15:01 +00:00
def upstream_type(current, proxy):
2021-05-11 23:08:20 +00:00
if proxy is None:
resp = requests.head(current)
else:
resp = requests.head(current, proxies=proxy.req)
2021-05-11 22:15:01 +00:00
return resp.headers.get("Content-Type", "binary/octet-stream")
2021-05-12 08:04:13 +00:00
def rewrite(current, provider, proxy):
2021-05-11 12:00:43 +00:00
resp = requests.get(current, proxies=proxy.req)
2021-05-08 22:49:52 +00:00
ndata = None
if resp.text is not None:
2021-05-10 14:24:31 +00:00
links = []
2021-05-08 17:08:54 +00:00
for line in resp.text.splitlines():
2021-05-09 10:37:36 +00:00
if line.startswith("#EXT-X-KEY:METHOD="):
matches = re.findall(r'(?<=URI=").+(?=")', line)
if len(matches) == 1:
2021-05-10 14:24:31 +00:00
ldata = {}
ldata["upstream"] = urllib.parse.urljoin(current, matches[0])
2021-05-11 12:00:43 +00:00
ldata["proxy"] = proxy.proxy
ldata["proxied"] = isinstance(proxy.proxy, str)
2021-05-10 14:24:31 +00:00
links.append(ldata)
elif line.startswith("#"):
pass
else:
ldata = {}
ldata["upstream"] = urllib.parse.urljoin(current, line)
2021-05-11 12:00:43 +00:00
ldata["proxy"] = proxy.proxy
ldata["proxied"] = isinstance(proxy.proxy, str)
2021-05-10 14:24:31 +00:00
links.append(ldata)
2021-05-11 12:00:43 +00:00
if isinstance(proxy_server, str):
ndata = ""
presp = requests.post(proxy_server, json=links)
if isinstance(presp.text, str):
links = json.loads(presp.text)
for line in resp.text.splitlines():
if line.startswith("#EXT-X-KEY:METHOD="):
matches = re.findall(r'(?<=URI=").+(?=")', line)
if len(matches) == 1:
new_url = links.pop(0)
ndata += re.sub(r'URI=".+"', f'URI="{new_url}"', line)
elif line.startswith("#"):
ndata += line
else:
ndata += links.pop(0)
ndata += "\n"
2021-05-10 14:24:31 +00:00
return ndata
2021-05-08 17:08:54 +00:00
2021-04-30 08:49:10 +00:00
class MainHandler(tornado.web.RequestHandler):
2021-05-06 13:54:18 +00:00
def handle_any(self, write):
2021-04-30 08:49:10 +00:00
provider = self.get_query_argument("provider", None)
2021-05-13 11:29:49 +00:00
render = self.get_query_argument("render", "false")
embed = self.get_query_argument("embed", "false")
2021-05-09 16:43:28 +00:00
if isinstance(provider, str):
2021-05-13 11:29:49 +00:00
if render.lower() == "true":
self.handle_render(provider)
elif embed.lower() == "true":
self.handle_embed(provider)
2021-05-09 16:43:28 +00:00
else:
self.handle_stream(provider, write)
else:
2021-05-13 07:16:47 +00:00
logger.info(f'provider missing {self.request.uri}')
2021-05-09 16:43:28 +00:00
self.set_status(404)
if write:
2021-05-13 06:42:10 +00:00
self.write("Stream not found. (provider missing)")
2021-05-09 16:43:28 +00:00
2021-05-13 11:29:49 +00:00
def handle_render(self, provider):
2021-05-12 07:54:38 +00:00
if template_js is not None and template_html is not None:
2021-05-13 12:22:11 +00:00
origin = self.request.path
2021-05-13 12:25:29 +00:00
if stream_server is not None:
2021-05-13 12:22:11 +00:00
origin = f'{stream_server}{self.request.path}'
2021-05-13 12:25:29 +00:00
stream_path = f'{origin}?provider={provider}'
2021-05-12 07:50:51 +00:00
rendered_js = template_js.generate(stream=stream_path);
2021-05-13 11:02:20 +00:00
b64_js = str(base64.b64encode(rendered_js), "ascii")
script = f'data:text/javascript;charset=utf-8;base64,{b64_js}'
2021-05-13 12:22:11 +00:00
rendered_html = template_html.generate(script=script, videojs_version=videojs_version, chromecast_version=chromecast_version, custom_style=custom_style, provider=provider, origin=origin)
2021-05-12 07:54:38 +00:00
self.write(rendered_html)
2021-05-09 16:49:40 +00:00
else:
self.set_status(404)
self.write("HTML template missing.")
2021-05-13 11:29:49 +00:00
def handle_embed(self, provider):
2021-05-13 12:22:11 +00:00
origin = self.request.path
2021-05-13 12:25:29 +00:00
if stream_server is not None:
2021-05-13 12:22:11 +00:00
origin = f'{stream_server}{self.request.path}'
2021-05-13 11:29:49 +00:00
embed_json = {}
embed_json["version"] = "1.0"
embed_json["type"] = "video"
2021-05-13 12:22:11 +00:00
embed_json["html"] = str(template_embed.generate(origin=origin, provider=provider), "utf-8")
2021-05-13 11:29:49 +00:00
self.set_header("Content-Type", "application/json+oembed; charset=utf-8")
self.write(json.dumps(embed_json))
2021-05-09 16:49:40 +00:00
2021-05-09 16:43:28 +00:00
def handle_stream(self, provider, write):
2021-05-08 17:12:21 +00:00
upstream = None
2021-05-08 17:08:54 +00:00
proxy = None
2021-05-09 16:43:28 +00:00
if provider in providers.keys():
2021-05-11 12:00:43 +00:00
path = self.request.path
if provider == "youtube":
path = path.strip("/")
2021-05-11 22:00:54 +00:00
src = providers[provider] + path
2021-05-11 12:45:33 +00:00
proxy_list = None
2021-05-11 14:33:18 +00:00
proxy_iter = None
2021-05-11 12:45:33 +00:00
proxy_list_orig = proxies.get(provider)
if isinstance(proxy_list_orig, list):
proxy_list = proxy_list_orig.copy()
2021-05-11 14:33:18 +00:00
proxy_iter = proxy_list_orig.copy()
2021-05-11 12:19:17 +00:00
if isinstance(proxy_list, list):
2021-05-11 14:33:18 +00:00
for i in proxy_iter:
current_list = proxy_list.copy()
current = proxy_list.pop()
proxy_list = [current] + proxy_list
2021-05-11 12:19:17 +00:00
try:
2021-05-12 12:01:28 +00:00
resp = requests.head(src, allow_redirects=True, proxies=current.req, timeout=2)
2021-05-11 12:19:17 +00:00
if resp is not None:
2021-05-13 07:16:47 +00:00
logger.info(src)
2021-05-11 12:19:17 +00:00
src = resp.url
except Exception as e:
2021-05-13 07:16:47 +00:00
logger.info(e)
2021-05-11 12:19:17 +00:00
else:
2021-05-11 14:33:18 +00:00
proxies[provider] = current_list
proxy = current
2021-05-11 13:55:58 +00:00
break
2021-05-11 12:19:17 +00:00
if proxy is not None:
2021-04-30 11:26:55 +00:00
try:
2021-05-13 08:04:39 +00:00
logger.info(proxy)
streams = proxy.stream().streams(src)
2021-05-13 07:24:20 +00:00
except Exception as e:
logger.info(e)
else:
2021-04-30 11:26:55 +00:00
for key in reversed(streams):
stream = streams.get(key)
2021-05-13 07:16:47 +00:00
logger.info(stream)
2021-04-30 11:26:55 +00:00
if hasattr(stream, "url"):
2021-05-08 17:12:21 +00:00
upstream = stream.url
2021-04-30 11:26:55 +00:00
break
2021-05-13 07:16:47 +00:00
else:
logger.info(f'invalid provider ({provider})')
2021-05-06 13:54:18 +00:00
self.set_status(404)
if write:
2021-05-13 06:42:10 +00:00
self.write("Stream not found. (invalid provider)")
2021-05-13 07:16:47 +00:00
return
if upstream is None:
logger.info(f'invalid upstream ({provider})')
self.set_status(404)
if write:
self.write("Stream not found. (invalid upstream)")
2021-04-30 11:26:55 +00:00
else:
2021-05-11 22:15:01 +00:00
ctype = upstream_type(upstream, proxy)
2021-05-11 22:17:44 +00:00
data = None
2021-05-11 22:22:55 +00:00
if "mpegurl" in ctype.lower():
2021-05-11 22:15:01 +00:00
data = rewrite(upstream, provider, proxy)
else:
ldata = {}
ldata["upstream"] = upstream
ldata["proxy"] = proxy.proxy
ldata["proxied"] = isinstance(proxy.proxy, str)
links = [ldata]
2021-05-13 07:16:47 +00:00
if isinstance(proxy_server, str):
try:
resp = requests.post(proxy_server, json=links)
if isinstance(resp.text, str):
new_links = json.loads(resp.text)
if isinstance(new_links, list) and len(new_links) == 1:
upstream = new_links.pop()
except Exception as e:
logger.info(e)
2021-05-08 22:49:52 +00:00
if data is None:
self.redirect(upstream, status=303)
else:
self.set_header("Content-Type", "application/vnd.apple.mpegurl")
self.write(data)
2021-04-30 15:51:09 +00:00
def get(self):
2021-05-06 13:54:18 +00:00
self.handle_any(True)
2021-04-30 15:51:09 +00:00
def head(self):
2021-05-06 13:54:18 +00:00
self.handle_any(False)
2021-05-01 18:01:24 +00:00
class FileHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("Content-Type", "text/plain; charset=utf-8")
2021-05-06 13:23:43 +00:00
self.write(playlist)
2021-05-13 07:16:47 +00:00
class IconHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("Content-Type", "text/plain; charset=utf-8")
self.set_status(204)
2021-04-30 08:49:10 +00:00
try:
2021-05-01 18:01:24 +00:00
handlers = []
handlers.append((tornado.routing.PathMatches("/sources.m3u8"), FileHandler))
2021-05-13 07:16:47 +00:00
handlers.append((tornado.routing.PathMatches("/favicon.ico"), IconHandler))
2021-05-01 18:01:24 +00:00
handlers.append((tornado.routing.AnyMatches(), MainHandler))
app_web = tornado.web.Application(handlers)
2021-04-30 08:49:10 +00:00
app_web.listen(8080)
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
print()