musicdlp/backend/main.py

71 lines
1.7 KiB
Python
Raw Normal View History

2024-05-02 16:18:27 +03:00
import asyncio
import json
import websockets
2024-05-03 19:57:20 +03:00
import config
2024-05-02 16:18:27 +03:00
import response
import ydl_pool
2024-05-02 16:18:27 +03:00
type SocketT = websockets.WebSocketServerProtocol
async def handler(socket: SocketT) -> None:
2024-05-08 12:52:36 +03:00
async def ydl_log_handler(level: response.YdlLogLevel, msg: str) -> None:
try:
await socket.send(response.ydl_log(level, msg))
except:
pass
ydls = ydl_pool.Downloader(
ydl_pool.YdlLogger(
ydl_log_handler,
asyncio.get_event_loop(),
)
)
2024-05-03 13:39:29 +03:00
async for message in socket:
try:
data = json.loads(message)
match data['action']:
case 'list': # list tracks in album
ydls.choose_ydl(data['site'])
2024-05-05 18:04:18 +03:00
await socket.send(response.playlist(
await ydls.get_playlist_items(data['url']),
))
case 'download': # download by URL
ydls.choose_ydl(data['site'])
ret = await ydls.download(
data['url'],
data.get('items'),
)
2024-05-08 12:52:36 +03:00
await socket.send(response.ydl_end(ret))
case _:
raise ValueError('invalid "action" field value')
except websockets.ConnectionClosed:
break
except Exception as ex:
if not socket.closed:
await socket.send(response.error(ex))
ydls.cleanup()
2024-05-02 16:18:27 +03:00
async def main() -> None:
2024-05-03 19:57:20 +03:00
cfg = config.get()
async with websockets.serve(handler, cfg.host, cfg.port):
2024-05-02 16:18:27 +03:00
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main(), debug=True)