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
|
2024-05-03 17:42:53 +03:00
|
|
|
import ydl_pool
|
2024-05-02 16:18:27 +03:00
|
|
|
|
|
|
|
|
2024-05-03 19:10:42 +03:00
|
|
|
type SocketT = websockets.WebSocketServerProtocol
|
|
|
|
|
|
|
|
|
|
|
|
async def handler(socket: SocketT) -> None:
|
2024-05-03 17:42:53 +03:00
|
|
|
|
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 17:42:53 +03:00
|
|
|
|
2024-05-03 13:39:29 +03:00
|
|
|
async for message in socket:
|
2024-05-03 17:42:53 +03:00
|
|
|
|
|
|
|
try:
|
|
|
|
data = json.loads(message)
|
|
|
|
|
|
|
|
match data['action']:
|
|
|
|
|
|
|
|
case 'list': # list tracks in album
|
2024-05-05 18:23:20 +03:00
|
|
|
ydls.choose_ydl(data['site'])
|
2024-05-05 18:04:18 +03:00
|
|
|
await socket.send(response.playlist(
|
2024-05-05 18:23:20 +03:00
|
|
|
await ydls.get_playlist_items(data['url']),
|
2024-05-03 17:42:53 +03:00
|
|
|
))
|
|
|
|
|
|
|
|
case 'download': # download by URL
|
2024-05-05 18:23:20 +03:00
|
|
|
ydls.choose_ydl(data['site'])
|
|
|
|
ret = await ydls.download(
|
2024-05-03 19:10:42 +03:00
|
|
|
data['url'],
|
|
|
|
data.get('items'),
|
|
|
|
)
|
2024-05-08 12:52:36 +03:00
|
|
|
await socket.send(response.ydl_end(ret))
|
2024-05-03 17:42:53 +03:00
|
|
|
|
|
|
|
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__':
|
2024-05-03 19:10:42 +03:00
|
|
|
asyncio.run(main(), debug=True)
|