61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
import asyncio
|
|
import json
|
|
|
|
import secrets
|
|
import time
|
|
|
|
import websockets
|
|
|
|
import response
|
|
|
|
|
|
# TODO: config
|
|
HOST = '127.0.0.1'
|
|
PORT = 5678
|
|
|
|
# TODO: make dict with functions creating YoutubeDL for each site instead of this set
|
|
SITES = {'youtube', 'yandex'}
|
|
|
|
sessions = {}
|
|
|
|
|
|
def generate_key() -> str:
|
|
return hex(time.time_ns()) + secrets.token_hex(2)
|
|
|
|
|
|
async def handler(socket: websockets.WebSocketServerProtocol) -> None:
|
|
async for message in socket:
|
|
data = json.loads(await socket.recv())
|
|
if 'action' not in data:
|
|
await socket.send(response.error_field('action'))
|
|
return
|
|
match data['action']:
|
|
case 'init': # create session
|
|
if data.get('site') not in SITES:
|
|
await socket.send(response.error_field('site'))
|
|
return
|
|
key = generate_key()
|
|
sessions[key] = "" # TODO
|
|
await socket.send(response.ok_init(key))
|
|
case 'list': # list tracks in album
|
|
if 'url' not in data:
|
|
await socket.send(response.error_field('url'))
|
|
return
|
|
await socket.send(response.ok_playlist(['title 1', 'title 2'])) # TODO
|
|
case 'download': # download by URL
|
|
if 'url' not in data:
|
|
await socket.send(response.error_field('url'))
|
|
return
|
|
# TODO: start thread and send all yt-dlp's output to client
|
|
await socket.send(response.OK)
|
|
case _:
|
|
await socket.send(response.error_field('action'))
|
|
|
|
|
|
async def main() -> None:
|
|
async with websockets.serve(handler, HOST, PORT):
|
|
await asyncio.Future()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(main())
|