stream-api/backend/stream.py

279 lines
9.0 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-14 13:10:12 +00:00
import base64
2022-02-13 13:15:33 +00:00
import dataclasses
from typing import Optional, cast, Any
2021-05-14 13:10:12 +00:00
import logging
2021-05-14 17:13:18 +00:00
import asyncio
2021-04-30 08:49:10 +00:00
import tornado.web
import tornado.routing
2022-01-30 12:15:42 +00:00
import config
2021-05-20 11:09:00 +00:00
import stream_providers
2021-05-13 07:16:47 +00:00
2022-02-04 16:44:47 +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__)
2022-02-04 16:36:36 +00:00
2022-02-04 16:44:47 +00:00
class UpstreamHandler:
2021-05-14 13:10:12 +00:00
def __init__(self):
2022-02-01 19:54:51 +00:00
self.provider: Optional[str] = None
self.raw: bool = False
self.valid: bool = False
self.proxy: config.ProxyElem = config.ProxyElem(None, None)
self.direct: bool = False
self.upstream: Optional[str] = None
2022-02-04 16:36:36 +00:00
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):
2022-01-30 12:38:01 +00:00
return (True, config.ProxyElem(None, 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)
2022-04-03 13:26:36 +00:00
except Exception as e:
logger.info(e)
2021-06-04 08:37:04 +00:00
return (False, proxy)
else:
return (True, proxy)
2022-02-04 16:36:36 +00:00
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)
2021-12-27 17:13:54 +00:00
direct_str = handler.get_query_argument("direct", None)
2022-02-04 16:36:36 +00:00
2022-02-04 16:44:47 +00:00
true_values = ["y", "yes", "t", "true", "on", "1"]
2021-12-27 17:13:54 +00:00
if isinstance(direct_str, str):
try:
2022-02-04 16:44:47 +00:00
self.direct = direct_str.lower() in true_values
2021-12-27 17:13:54 +00:00
except ValueError as e:
logger.info(e)
2021-09-26 12:19:03 +00:00
if isinstance(raw_str, str):
try:
2022-02-04 16:44:47 +00:00
self.raw = raw_str.lower() in true_values
2021-09-26 12:19:03 +00:00
except ValueError as e:
logger.info(e)
2022-02-04 16:44:47 +00:00
if self.provider in config.providers:
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("/")
2022-01-30 12:38:01 +00:00
self.upstream = config.providers[self.provider] + path
2021-12-27 17:13:54 +00:00
if not self.direct:
2022-01-30 12:38:01 +00:00
proxy_list = config.proxies.get(self.provider)
2021-12-27 17:13:54 +00:00
if isinstance(proxy_list, list):
futures = []
for current in proxy_list:
future = asyncio.create_task(self.test_socks(current))
futures.append(future)
for future in asyncio.as_completed(futures):
success, current = await future
if success:
self.proxy = current
break
for future in futures:
if not future.done():
future.cancel()
2021-05-14 19:55:56 +00:00
2022-02-01 19:54:51 +00:00
2022-02-13 13:15:33 +00:00
@dataclasses.dataclass
class VideoInfo:
upstream: None | str = None
download: None | str = None
poster: None | str = None
ctype: None | str = None
2022-02-05 20:56:06 +00:00
class NoDataError(Exception):
pass
class MissingTemplateError(Exception):
pass
2021-04-30 08:49:10 +00:00
class MainHandler(tornado.web.RequestHandler):
2022-02-04 16:44:47 +00:00
async def handle_any(self):
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:
2022-02-04 16:36:36 +00:00
logger.info("provider missing %s", 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)")
2022-02-04 16:36:36 +00:00
2022-02-05 20:56:06 +00:00
async def get_data(self, handler) -> tuple[dict[str, str], str, str]:
2021-09-26 12:19:03 +00:00
video_info = None
2022-02-05 20:56:06 +00:00
if config.template_script is None or config.template_html is None:
raise MissingTemplateError()
provider_data = None
if handler.provider.startswith("nextcloud"):
provider_data = await stream_providers.get_nextcloud(
handler.upstream, handler.proxy, logger
)
elif handler.provider.startswith("seafile"):
provider_data = await stream_providers.get_seafile(
handler.upstream, handler.proxy, logger
)
else:
provider_data = await stream_providers.get_any(
handler.upstream, handler.proxy, logger
)
if provider_data is None:
raise NoDataError()
2022-02-13 13:15:33 +00:00
video_info = VideoInfo()
video_info.ctype = provider_data.ctype()
2022-02-05 20:56:06 +00:00
if handler.direct:
2022-02-13 13:15:33 +00:00
video_info.upstream = provider_data.upstream()
video_info.poster = provider_data.thumbnail()
2022-02-05 20:56:06 +00:00
else:
proxied = await handler.proxy.proxy_url(
[
2022-02-12 12:51:17 +00:00
config.LinkWithType(
upstream=provider_data.upstream(),
ctype=provider_data.proxy_ctype(),
),
2022-02-13 13:15:33 +00:00
config.LinkWithType(
upstream=provider_data.upstream(),
ctype=provider_data.proxy_ctype(),
download=True,
),
2022-02-12 13:01:30 +00:00
config.LinkWithType(
upstream=provider_data.thumbnail(),
),
2022-02-05 20:56:06 +00:00
]
)
2022-02-13 13:15:33 +00:00
video_info.upstream = proxied[0]
video_info.download = proxied[1]
if (
isinstance(video_info.ctype, str)
and "mpegurl" in video_info.ctype.lower()
):
video_info.download = None
video_info.poster = proxied[2]
return (
dataclasses.asdict(video_info),
provider_data.meta(),
provider_data.title(),
)
2022-02-04 16:36:36 +00:00
2021-09-26 12:19:03 +00:00
async def handle_raw(self, handler):
2022-02-05 20:56:06 +00:00
try:
video_info = (await self.get_data(handler))[0]
2021-09-26 12:19:03 +00:00
self.redirect(url=video_info["upstream"], status=303)
2022-02-05 20:56:06 +00:00
except NoDataError:
2021-09-26 12:19:03 +00:00
self.set_status(404)
2022-02-05 21:03:32 +00:00
self.write("Video not found.")
2022-02-05 20:56:06 +00:00
except MissingTemplateError:
self.set_status(404)
2022-02-05 21:03:32 +00:00
self.write("HTML template missing.")
2022-02-04 16:36:36 +00:00
2021-09-26 12:19:03 +00:00
async def handle_render(self, handler):
2022-02-05 20:56:06 +00:00
try:
video_info, meta, title = await self.get_data(handler)
except NoDataError:
2021-05-09 16:49:40 +00:00
self.set_status(404)
2022-02-05 21:03:32 +00:00
self.write("Video not found.")
2022-02-05 20:56:06 +00:00
return
except MissingTemplateError:
self.set_status(404)
2022-02-05 21:03:32 +00:00
self.write("HTML template missing.")
2022-02-05 20:56:06 +00:00
return
script = config.template_script.generate(info=json.dumps(video_info))
b64 = str(base64.b64encode(script), "ascii")
data = {}
script_file = f"data:text/javascript;charset=utf-8;base64,{b64}"
data["script"] = script_file
data["videojs_version"] = config.videojs_version
data["chromecast_version"] = config.chromecast_version
data["font_awesome_version"] = config.font_awesome_version
rendered_html = config.template_html.generate(data=data, meta=meta, title=title)
self.write(rendered_html)
2022-02-04 16:36:36 +00:00
2021-05-14 13:10:12 +00:00
async def get(self):
2022-02-04 16:44:47 +00:00
await self.handle_any()
2022-02-04 16:36:36 +00:00
2021-05-14 13:10:12 +00:00
async def head(self):
2022-02-04 16:44:47 +00:00
await self.handle_any()
2021-05-01 18:01:24 +00:00
2022-02-04 16:36:36 +00:00
def data_received(self, _):
pass
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")
2022-01-30 12:38:01 +00:00
self.write(config.playlist)
2021-06-09 13:01:19 +00:00
2022-02-04 16:36:36 +00:00
def data_received(self, _):
pass
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")
2022-01-30 12:38:01 +00:00
self.write(config.favicon)
2021-06-09 13:01:19 +00:00
2022-02-04 16:36:36 +00:00
def data_received(self, _):
pass
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")
2022-01-30 12:38:01 +00:00
self.write(config.custom_style)
2022-02-04 16:36:36 +00:00
def data_received(self, _):
pass
2021-04-30 08:49:10 +00:00
try:
2022-02-04 16:36:36 +00:00
handlers: list[tuple[tornado.routing.Matcher, tornado.web.RequestHandler]] = []
2022-02-04 16:44:47 +00:00
handlers.append(
(
cast(tornado.routing.Matcher, tornado.routing.PathMatches("/sources.m3u8")),
cast(tornado.web.RequestHandler, PlaylistHandler),
)
)
handlers.append(
(
cast(tornado.routing.Matcher, tornado.routing.PathMatches("/favicon.ico")),
cast(tornado.web.RequestHandler, IconHandler),
)
)
handlers.append(
(
cast(tornado.routing.Matcher, tornado.routing.PathMatches("/style.css")),
cast(tornado.web.RequestHandler, StyleHandler),
)
)
handlers.append(
(
cast(tornado.routing.Matcher, tornado.routing.AnyMatches()),
cast(tornado.web.RequestHandler, MainHandler),
)
)
2022-02-04 16:36:36 +00:00
app_web = tornado.web.Application(cast(Any, handlers))
2021-04-30 08:49:10 +00:00
app_web.listen(8080)
tornado.ioloop.IOLoop.current().start()
except KeyboardInterrupt:
print()