54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
import asyncio
|
|
import os
|
|
from typing import Optional
|
|
from adaas.cachedb import RemoteCache
|
|
|
|
from v6d3music.core.cache_url import cache_db, cache_url
|
|
from v6d3music.utils.bytes_hash import bytes_hash
|
|
from v6d3music.utils.tor_prefix import tor_prefix
|
|
|
|
|
|
adaas_available = bool(os.getenv('adaasurl'))
|
|
if adaas_available:
|
|
print('running real_url through adaas')
|
|
|
|
|
|
_tasks = set()
|
|
|
|
|
|
def _schedule_cache(hurl: str, rurl: str, override: bool, tor: bool):
|
|
task = asyncio.create_task(cache_url(hurl, rurl, override, tor))
|
|
_tasks.add(task)
|
|
task.add_done_callback(_tasks.discard)
|
|
|
|
|
|
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(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: Optional[str] = cache_db.get(f'url:{hurl}', None)
|
|
if curl is not None:
|
|
print('using cached', hurl)
|
|
return curl
|
|
rurl: str = await _resolve_url(url, tor)
|
|
_schedule_cache(hurl, rurl, override, tor)
|
|
return rurl
|