From c1ab35efa3716a501b10fcf0d33457895ccd9f82 Mon Sep 17 00:00:00 2001 From: Roy Olav Purser Date: Sat, 8 May 2021 19:08:54 +0200 Subject: [PATCH] add proxy --- stream.py | 36 ++++++++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/stream.py b/stream.py index 0cac783..e9918df 100755 --- a/stream.py +++ b/stream.py @@ -5,6 +5,7 @@ import tornado.routing import requests import json import os +import urllib.parse providers = {} providers["nrk"] = "https://tv.nrk.no" @@ -13,20 +14,22 @@ 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() +proxies_raw = {} -for key in proxies: +for key in providers: + proxies[key] = streamlink.Streamlink() 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) + #proxies[key].set_option("https-proxy", proxy) + splitted = proxy.split(":", 1) + if len(splitted) == 2: + proxies_raw[key] = splitted[1].lstrip("/") playlist = None icecast_server = os.environ.get("ICECAST_SERVER") stream_server = os.environ.get("STREAM_SERVER") +proxy_server = os.environ.get("PROXY_SERVER") if icecast_server is not None and stream_server is not None: with open("/app/sources.json", "r") as f: @@ -43,12 +46,32 @@ if icecast_server is not None and stream_server is not None: playlist += f'#EXTINF:0 radio="false", {name}\n' playlist += stream_server + key + "\n" +def rewrite(current, endpoint, proxy): + resp = requests.get(current) + ndata = resp.text + if resp.text is not None and proxy_server is not None: + ndata = "" + for line in resp.text.splitlines(): + if line.startswith("#"): + ndata += line + else: + data = {} + data["upstream"] = urllib.parse.urljoin(current, line) + data["proxy"] = proxy + presp = requests.post(proxy_server, json=data) + ndata += presp.text + ndata += "\n" + print(ndata) + class MainHandler(tornado.web.RequestHandler): def handle_any(self, write): provider = self.get_query_argument("provider", None) endpoint = None + proxy = None + proxy_raw = None if provider is not None and provider in providers.keys(): proxy = proxies.get(provider) + proxy_raw = proxies_raw.get(provider) src = providers[provider] + self.request.uri try: resp = requests.get(src) @@ -72,6 +95,7 @@ class MainHandler(tornado.web.RequestHandler): if write: self.write("stream not found") else: + rewrite(endpoint, "", proxy_raw) self.redirect(endpoint, status=303) def get(self): self.handle_any(True)