v6d3music/v6d3music/core/real_url.py
2022-12-24 16:37:05 +00:00

44 lines
1.3 KiB
Python

import asyncio
import os
from v6d3music.core.caching import Caching
from v6d3music.utils.bytes_hash import bytes_hash
from v6d3music.utils.tor_prefix import tor_prefix
from adaas.cachedb import RemoteCache
adaas_available = bool(os.getenv('adaasurl'))
if adaas_available:
print('running real_url through adaas')
async def _resolve_url(url: str, tor: bool) -> str:
args = []
if tor:
args.extend(tor_prefix())
args.extend(
[
'yt-dlp', '--no-playlist', '-f', 'bestaudio', '-g', '--', url,
]
)
ap = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE)
code = await ap.wait()
if code:
raise RuntimeError(code)
assert ap.stdout is not None
return (await ap.stdout.readline()).decode()[:-1]
async def real_url(caching: Caching, url: str, override: bool, tor: bool) -> str:
if adaas_available and not tor:
return await RemoteCache().real_url(url, override, tor)
hurl: str = bytes_hash(url.encode())
if not override:
curl: str | None = caching.get(hurl)
if curl is not None:
print('using cached', hurl)
return curl
rurl: str = await _resolve_url(url, tor)
caching.schedule_cache(hurl, rurl, override, tor)
return rurl