diff --git a/backend/stream.py b/backend/stream.py index 276cc8b..c549caf 100755 --- a/backend/stream.py +++ b/backend/stream.py @@ -8,8 +8,6 @@ import logging import asyncio import tornado.web import tornado.routing -import aiohttp -import aiohttp_socks import stream_providers logging.basicConfig(format='[%(filename)s:%(lineno)d] %(message)s', stream=sys.stdout, level=logging.INFO) @@ -73,17 +71,6 @@ class ProxyElem(): else: return urls -class AsyncSessionData(): - def __init__(self, resp, current): - self.resp = resp - self.current = current -class AsyncSession(): - def __init__(self, resp, current): - self.sdata = AsyncSessionData(resp, current) - async def task(self): - resp = await self.sdata.resp - return AsyncSessionData(resp, self.sdata.current) - proxies = {} for key in providers: proxies[key] = [] @@ -111,6 +98,20 @@ class UpstreamHandler(): self.valid = False self.proxy = None self.upstream = None + async def test_socks(self, proxy): + try: + splitted = proxy.rsplit(":", 1) + 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) async def setup(self, handler): self.provider = handler.get_query_argument("provider", None) if self.provider in providers.keys(): @@ -120,38 +121,21 @@ class UpstreamHandler(): path = path.removesuffix("/").removesuffix("download").removesuffix("/") elif self.provider == "youtube": path = path.removeprefix("/") - src = providers[self.provider] + path + self.upstream = providers[self.provider] + path proxy_list = proxies.get(self.provider) if isinstance(proxy_list, list): futures = [] - sessions = [] for current in proxy_list: - session = current.session() - sessions.append(session) - future = AsyncSession(session.head(src), current) - task = asyncio.create_task(future.task()) - futures.append(task) - done = False + future = asyncio.create_task(self.test_socks(current)) + futures.append(future) for future in asyncio.as_completed(futures): - try: - result = await future - resp = result.resp - except Exception as e: - logger.info(e) - else: - done = True - new_url = str(resp.url) - if new_url.lower().startswith("https://consent.youtube.com"): - self.upstream = src - else: - self.upstream = new_url - self.proxy = result.current + success, current = await future + if success: + self.proxy = current break for future in futures: if not future.done(): future.cancel() - for session in sessions: - await session.close() if icecast_server is not None and stream_server is not None: try: