musicdlp/backend/main.py

66 lines
1.5 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
import ydl_wrap
2024-05-02 16:18:27 +03:00
type SocketT = websockets.WebSocketServerProtocol
2024-05-02 16:18:27 +03:00
async def handler(socket: SocketT) -> None:
ydls = ydl_pool.Downloaders()
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
2024-05-05 18:04:18 +03:00
await socket.send(response.playlist(
await ydl_wrap.get_playlist_items(
ydls.get_ydl(data['site']),
data['url'],
)
))
case 'download': # download by URL
ret = await ydl_wrap.download(
ydls.get_ydl(data['site']),
data['url'],
data.get('items'),
)
2024-05-05 18:04:18 +03:00
await socket.send(response.dl_end(ret))
# TODO: cancellation
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)