v6d3music/v6d3music/core/real_url.py
2023-01-15 08:51:29 +00:00

45 lines
1.3 KiB
Python

import asyncio
import os
from adaas.cachedb import *
from v6d3music.core.caching import *
from v6d3music.utils.bytes_hash import *
from v6d3music.utils.tor_prefix import *
__all__ = ('real_url',)
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, True)
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