stream-api/backend/stream.py

303 lines
11 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
2021-05-14 16:57:26 +00:00
import sys
2021-05-11 12:45:33 +00:00
import os
import re
2021-05-14 13:10:12 +00:00
import base64
import logging
2021-09-26 12:19:03 +00:00
import distutils.util
2021-05-14 17:13:18 +00:00
import asyncio
2021-04-30 08:49:10 +00:00
import tornado.web
import tornado.routing
2021-05-20 11:09:00 +00:00
import stream_providers
2021-06-04 08:38:34 +00:00
import aiohttp
2021-05-13 07:16:47 +00:00
2021-05-14 16:57:26 +00:00
logging.basicConfig(format='[%(filename)s:%(lineno)d] %(message)s', stream=sys.stdout, level=logging.INFO)
2021-05-13 07:16:47 +00:00
logger = logging.getLogger(__name__)
2021-04-30 08:49:10 +00:00
providers = {}
providers["nrk"] = "https://tv.nrk.no"
2021-08-03 07:26:24 +00:00
providers["nrk_web"] = "https://nrk.no"
2021-04-30 08:49:10 +00:00
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-05-22 17:08:44 +00:00
nextcloud_server = os.environ.get("NEXTCLOUD_SERVER")
if nextcloud_server is not None:
providers["nextcloud"] = nextcloud_server
2021-09-02 13:27:51 +00:00
seafile_server = os.environ.get("SEAFILE_SERVER")
if seafile_server is not None:
providers["seafile"] = seafile_server
2021-05-14 09:31:30 +00:00
playlist = None
icecast_server = os.environ.get("ICECAST_SERVER")
stream_server = os.environ.get("STREAM_SERVER")
proxy_server = os.environ.get("PROXY_SERVER")
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
2021-05-14 16:03:53 +00:00
def local(self):
2021-06-03 14:39:17 +00:00
timeout = aiohttp.ClientTimeout(total=5)
2021-05-14 16:03:53 +00:00
return aiohttp.ClientSession(timeout=timeout)
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-31 10:59:25 +00:00
async def proxy_url(self, urls):
if not isinstance(proxy_server, str):
return urls
2021-05-14 16:03:53 +00:00
jdata = None
2021-05-31 10:59:25 +00:00
data_list = []
for url in urls:
data = {}
data["upstream"] = url
2021-05-14 13:10:12 +00:00
data["proxy"] = self.proxy
2021-05-31 10:59:25 +00:00
data["proxied"] = isinstance(self.proxy, str)
data_list.append(data)
2021-05-14 14:47:09 +00:00
try:
2021-05-14 16:03:53 +00:00
async with self.local() as session:
2021-05-14 14:47:09 +00:00
resp = await session.post(proxy_server, json=data_list)
text = await resp.text()
jdata = json.loads(text)
except Exception as e:
logger.info(e)
2021-05-31 10:59:25 +00:00
if isinstance(jdata, list):
ret_data = []
2021-05-31 12:46:51 +00:00
for src, dst in zip(urls, jdata):
if isinstance(src, str):
ret_data.append(dst)
2021-05-31 10:59:25 +00:00
else:
ret_data.append(None)
return ret_data
2021-05-14 13:30:37 +00:00
else:
2021-05-31 10:59:25 +00:00
return urls
2021-05-14 13:10:12 +00:00
2021-05-11 12:00:43 +00:00
proxies = {}
new_providers = {}
2021-05-08 17:08:54 +00:00
for key in providers:
2021-07-23 15:23:57 +00:00
expr = re.compile(f'^{key}_proxy(_[a-z][a-z])?[0-9]+$', re.IGNORECASE)
matches = list(filter(expr.match, os.environ.keys()))
2021-05-11 12:19:17 +00:00
current = []
current_keys = set()
current_keys.add(key)
countries = []
empty = True
for match in matches:
country_groups = expr.match(match.lower()).groups()
country = None
pos = len(country_groups) - 1
if pos >= 0:
2021-07-23 15:30:22 +00:00
country_temp = country_groups[pos]
if isinstance(country_temp, str):
country = country_temp.strip("_")
current_keys.add(f'{key}_{country}')
proxy = os.environ.get(match)
2021-05-11 12:19:17 +00:00
if proxy is not None:
current.append(proxy)
countries.append(country)
if country is None:
empty = False
for elem in current_keys:
proxies[elem] = []
new_providers[elem] = providers[key]
print(proxies)
for proxy, country in zip(current, countries):
new_key = key
if country is not None:
new_key = f'{key}_{country}'
proxies[new_key].append(ProxyElem(proxy))
for elem in current_keys:
if len(proxies[elem]) == 0:
proxies[elem].append(ProxyElem(None))
providers = new_providers
2021-04-30 11:55:10 +00:00
2021-05-29 08:33:10 +00:00
proxy_keys = []
for proxy_provider in proxies.values():
for proxy in proxy_provider:
if isinstance(proxy, ProxyElem) and isinstance(proxy.proxy, str):
proxy_keys.append(proxy.proxy)
stream_providers.setup(proxy_keys)
2021-05-14 09:31:30 +00:00
class UpstreamHandler():
2021-05-14 13:10:12 +00:00
def __init__(self):
self.provider = None
2021-09-26 12:19:03 +00:00
self.raw = False
2021-05-31 10:59:25 +00:00
self.valid = False
2021-06-04 08:45:30 +00:00
self.proxy = ProxyElem(None)
2021-05-14 09:31:30 +00:00
self.upstream = None
2021-06-04 08:37:04 +00:00
async def test_socks(self, proxy):
2021-06-04 09:02:19 +00:00
if not hasattr(proxy, "proxy") or not isinstance(proxy.proxy, str):
2021-06-04 08:53:57 +00:00
return (True, ProxyElem(None))
2021-06-04 08:37:04 +00:00
try:
2021-06-04 09:02:19 +00:00
splitted = proxy.proxy.rsplit(":", 1)
2021-06-04 08:37:04 +00:00
host = proxy
port = 1080
if len(splitted) == 2:
host = splitted[0]
port = splitted[1]
future = asyncio.open_connection(host=host, port=port)
await asyncio.wait_for(future, timeout=1)
except Exception as e:
return (False, proxy)
else:
return (True, proxy)
2021-05-14 13:10:12 +00:00
async def setup(self, handler):
self.provider = handler.get_query_argument("provider", None)
2021-09-26 12:19:03 +00:00
raw_str = handler.get_query_argument("raw", None)
if isinstance(raw_str, str):
try:
self.raw = bool(distutils.util.strtobool(raw_str))
except ValueError as e:
logger.info(e)
2021-05-14 13:10:12 +00:00
if self.provider in providers.keys():
2021-05-31 10:59:25 +00:00
self.valid = True
2021-05-14 09:31:30 +00:00
path = handler.request.path
2021-07-23 15:38:59 +00:00
if self.provider.startswith("nextcloud"):
2021-05-25 10:14:49 +00:00
path = path.removesuffix("/").removesuffix("download").removesuffix("/")
2021-07-23 15:38:59 +00:00
elif self.provider.startswith("youtube"):
2021-05-25 10:14:49 +00:00
path = path.removeprefix("/")
2021-06-04 08:37:04 +00:00
self.upstream = providers[self.provider] + path
2021-05-14 21:18:51 +00:00
proxy_list = proxies.get(self.provider)
2021-05-14 09:31:30 +00:00
if isinstance(proxy_list, list):
2021-05-14 17:57:08 +00:00
futures = []
2021-05-14 21:18:51 +00:00
for current in proxy_list:
2021-06-04 09:02:19 +00:00
future = asyncio.create_task(self.test_socks(current))
2021-06-04 08:37:04 +00:00
futures.append(future)
2021-05-14 17:57:08 +00:00
for future in asyncio.as_completed(futures):
2021-06-04 08:37:04 +00:00
success, current = await future
if success:
self.proxy = current
2021-05-14 19:55:56 +00:00
break
for future in futures:
if not future.done():
future.cancel()
2021-05-06 13:23:43 +00:00
if icecast_server is not None and stream_server is not None:
2021-05-13 13:24:22 +00:00
try:
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"
except Exception as e:
logger.info(e)
2021-05-06 13:23:43 +00:00
2021-05-12 07:50:51 +00:00
template_html = None
2021-05-31 10:59:25 +00:00
template_script = None
2021-05-10 15:47:34 +00:00
videojs_version = None
2021-05-19 13:54:42 +00:00
font_awesome_version = None
2021-05-13 09:15:40 +00:00
custom_style = None
2021-05-23 19:48:10 +00:00
favicon = 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:
2021-05-31 10:59:25 +00:00
template_script = tornado.template.Template(f.read().strip())
2021-05-19 13:54:42 +00:00
with open("/app/version/video.js.txt", "r") as f:
2021-05-10 15:40:38 +00:00
videojs_version = f.read().strip()
2021-05-19 13:54:42 +00:00
with open("/app/version/chromecast.txt", "r") as f:
2021-05-13 09:15:40 +00:00
chromecast_version = f.read().strip()
2021-05-19 13:54:42 +00:00
with open("/app/version/font-awesome.txt", "r") as f:
font_awesome_version = f.read().strip()
2021-05-23 19:48:10 +00:00
with open("/app/favicon.png", "rb") as f:
favicon = f.read()
2021-05-13 09:15:40 +00:00
with open("/app/style.css", "r") as f:
2021-06-09 13:01:19 +00:00
custom_style = f.read()
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-04-30 08:49:10 +00:00
class MainHandler(tornado.web.RequestHandler):
2021-05-14 13:43:24 +00:00
async def handle_any(self, redir):
2021-05-14 13:10:12 +00:00
handler = UpstreamHandler()
await handler.setup(self)
2021-05-31 10:59:25 +00:00
if handler.valid:
2021-09-26 12:19:03 +00:00
if handler.raw:
await self.handle_raw(handler)
else:
await self.handle_render(handler)
2021-05-09 16:43:28 +00:00
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)
2021-05-14 09:31:30 +00:00
self.write("Stream not found. (provider missing)")
2021-09-26 12:19:03 +00:00
async def get_data(self, handler):
video_info = None
meta = None
title = None
2021-05-31 10:59:25 +00:00
if template_script is not None and template_html is not None:
provider_data = None
2021-07-23 15:38:59 +00:00
if handler.provider.startswith("nextcloud"):
2021-05-31 10:59:25 +00:00
provider_data = await stream_providers.get_nextcloud(handler.upstream, handler.proxy, logger)
2021-09-02 13:27:51 +00:00
elif handler.provider.startswith("seafile"):
provider_data = await stream_providers.get_seafile(handler.upstream, handler.proxy, logger)
2021-05-31 10:59:25 +00:00
else:
provider_data = await stream_providers.get_any(handler.upstream, handler.proxy, logger)
proxied = await handler.proxy.proxy_url([provider_data.upstream(), provider_data.thumbnail()])
video_info = {}
video_info["upstream"] = proxied[0]
video_info["poster"] = proxied[1]
video_info["ctype"] = provider_data.ctype()
2021-09-26 12:19:03 +00:00
meta = provider_data.meta()
title = provider_data.title()
return (video_info, meta, title)
async def handle_raw(self, handler):
video_info, meta, title = await self.get_data(handler)
if video_info is not None:
self.redirect(url=video_info["upstream"], status=303)
else:
self.set_status(404)
self.write("HTML template missing.")
async def handle_render(self, handler):
video_info, meta, title = await self.get_data(handler)
if video_info is not None:
2021-05-31 10:59:25 +00:00
script = template_script.generate(info=json.dumps(video_info))
b64 = str(base64.b64encode(script), "ascii")
script_file = f'data:text/javascript;charset=utf-8;base64,{b64}'
2021-05-20 16:33:51 +00:00
data["script"] = script_file
2021-05-14 09:31:30 +00:00
data["videojs_version"] = videojs_version
data["chromecast_version"] = chromecast_version
2021-05-19 13:54:42 +00:00
data["font_awesome_version"] = font_awesome_version
2021-09-26 12:19:03 +00:00
rendered_html = template_html.generate(data=data, meta=meta, title=title)
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-14 13:10:12 +00:00
async def get(self):
2021-05-14 13:43:24 +00:00
await self.handle_any(True)
2021-05-14 13:10:12 +00:00
async def head(self):
2021-05-14 13:43:24 +00:00
await self.handle_any(False)
2021-05-01 18:01:24 +00:00
2021-06-09 13:01:19 +00:00
class PlaylistHandler(tornado.web.RequestHandler):
2021-05-01 18:01:24 +00:00
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-06-09 13:01:19 +00:00
2021-05-13 07:16:47 +00:00
class IconHandler(tornado.web.RequestHandler):
def get(self):
2021-05-23 19:48:10 +00:00
self.set_header("Content-Type", "image/png")
self.write(favicon)
2021-06-09 13:01:19 +00:00
class StyleHandler(tornado.web.RequestHandler):
def get(self):
self.set_header("Content-Type", "text/css; charset=utf-8")
self.write(custom_style)
2021-04-30 08:49:10 +00:00
try:
2021-05-01 18:01:24 +00:00
handlers = []
2021-06-09 13:01:19 +00:00
handlers.append((tornado.routing.PathMatches("/sources.m3u8"), PlaylistHandler))
2021-05-13 07:16:47 +00:00
handlers.append((tornado.routing.PathMatches("/favicon.ico"), IconHandler))
2021-06-09 13:01:19 +00:00
handlers.append((tornado.routing.PathMatches("/style.css"), StyleHandler))
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()