initial work on s3, config is shared between client and server... now with changed files...

This commit is contained in:
Christoph Stahl 2022-11-10 20:59:59 +01:00
parent 2a72e842e3
commit b27b0f994a
5 changed files with 82 additions and 27 deletions

View file

@ -1,13 +1,17 @@
import asyncio import asyncio
import socketio import socketio
from traceback import print_exc from traceback import print_exc
from json import load
from .sources import YoutubeSource from .sources import Source, configure_sources
from .entry import Entry from .entry import Entry
sio = socketio.AsyncClient() sio = socketio.AsyncClient()
sources = {"youtube": YoutubeSource()} with open("./syng-client.json") as f:
source_config = load(f)
sources = configure_sources(source_config, client=True)
currentLock = asyncio.Semaphore(0) currentLock = asyncio.Semaphore(0)
state = { state = {
@ -78,10 +82,11 @@ async def handle_connect():
await sio.emit("register-client", {"secret": "test"}) await sio.emit("register-client", {"secret": "test"})
@sio.on("register-client") @sio.on("client-registered")
async def handle_register(data): async def handle_register(data):
if data["success"]: if data["success"]:
print("Registered") print("Registered")
await sio.emit("config", {"sources": source_config})
asyncio.create_task(playerTask()) asyncio.create_task(playerTask())
asyncio.create_task(bufferTask()) asyncio.create_task(bufferTask())
else: else:

View file

@ -9,7 +9,7 @@ from aiohttp import web
import socketio import socketio
from .entry import Entry from .entry import Entry
from .sources import YoutubeSource from .sources import configure_sources
# socketio = SocketIO(app, cors_allowed_origins='*') # socketio = SocketIO(app, cors_allowed_origins='*')
# sio = socketio.AsyncServer() # sio = socketio.AsyncServer()
@ -17,12 +17,10 @@ from .sources import YoutubeSource
sio = socketio.AsyncServer(cors_allowed_origins="*", logger=True, engineio_logger=True) sio = socketio.AsyncServer(cors_allowed_origins="*", logger=True, engineio_logger=True)
app = web.Application() app = web.Application()
sio.attach(app) sio.attach(app)
sources = {"youtube": YoutubeSource()}
admins = set()
admin_secrets = ["admin"] admin_secrets = ["admin"]
client_secrets = ["test"] client_secrets = ["test"]
clients = set() sources = {}
class Queue(deque): class Queue(deque):
@ -57,6 +55,7 @@ async def handle_state(sid, data: dict[str, Any]):
@sio.on("append") @sio.on("append")
async def handle_append(sid, data: dict[str, Any]): async def handle_append(sid, data: dict[str, Any]):
print(f"append: {data}") print(f"append: {data}")
source_obj = sources[data["source"]] source_obj = sources[data["source"]]
entry = await Entry.from_source(data["performer"], data["id"], source_obj) entry = await Entry.from_source(data["performer"], data["id"], source_obj)
@ -66,39 +65,63 @@ async def handle_append(sid, data: dict[str, Any]):
@sio.on("get-next") @sio.on("get-next")
async def handle_next(sid, data: dict[str, Any]): async def handle_next(sid, data: dict[str, Any]):
if sid in clients: async with sio.session(sid) as session:
print(f"get-next request from client {sid}") if "client" in session and session["client"]:
current = await queue.popleft() print(f"get-next request from client {sid}")
print(f"Sending {current} to client {sid}") current = await queue.popleft()
print(f"new state: {queue.to_dict()}") print(f"Sending {current} to client {sid}")
await sio.emit("next", current.to_dict(), room=sid) print(f"new state: {queue.to_dict()}")
await sio.emit("next", current.to_dict(), room=sid)
@sio.on("register-client") @sio.on("register-client")
async def handle_register_client(sid, data: dict[str, Any]): async def handle_register_client(sid, data: dict[str, Any]):
if data["secret"] in client_secrets: if data["secret"] in client_secrets:
print(f"Registerd new client {sid}") print(f"Registerd new client {sid}")
clients.add(sid) await sio.save_session(sid, {"client": True})
await sio.emit("register-client", {"success": True}, room=sid) sio.enter_room(sid, "clients")
await sio.emit("client-registered", {"success": True}, room=sid)
else: else:
await sio.emit("register-client", {"success": False}, room=sid) await sio.emit("client-registered", {"success": False}, room=sid)
@sio.on("config")
async def handle_config(sid, data):
async with sio.session(sid) as session:
if "client" in session and session["client"]:
sources.update(configure_sources(data["sources"], client=False))
print(f"Updated Config: {sources}")
@sio.on("register-admin") @sio.on("register-admin")
async def handle_register_admin(sid, data: dict[str, str]): async def handle_register_admin(sid, data: dict[str, str]):
if data["secret"] in admin_secrets: if data["secret"] in admin_secrets:
print(f"Registerd new admin {sid}") print(f"Registerd new admin {sid}")
admins.add(sid) await sio.save_session(sid, {"admin": True})
await sio.emit("register-admin", {"success": True}, room=sid) await sio.emit("register-admin", {"success": True}, room=sid)
else: else:
await sio.emit("register-admin", {"success": False}, room=sid) await sio.emit("register-admin", {"success": False}, room=sid)
@sio.on("get-config")
async def handle_config(sid, data):
async with sio.session(sid) as session:
if "admin" in session and session["admin"]:
await sio.emit("config", list(sources.keys()))
@sio.on("skip") @sio.on("skip")
async def handle_skip(sid, data={}): async def handle_skip(sid, data={}):
if sid in admins: async with sio.session(sid) as session:
for client in clients: if "admin" in session and session["admin"]:
await sio.emit("skip", room=client) await sio.emit("skip", room="client")
@sio.on("disconnect")
async def handle_disconnect(sid, data={}):
async with sio.session(sid) as session:
if "client" in session and session["client"]:
sio.leave_room(sid, "clients")
@sio.on("search") @sio.on("search")

View file

@ -1,2 +1,16 @@
from .source import Source, available_sources
from .youtube import YoutubeSource from .youtube import YoutubeSource
from .source import Source from .s3 import S3Source
def configure_sources(configs: dict, client) -> dict[str, Source]:
print(available_sources)
configured_sources = {}
for source, config in configs.items():
if source in available_sources:
configured_sources[source] = available_sources[source](config)
if client:
configured_sources[source].init_client()
else:
configured_sources[source].init_server()
return configured_sources

View file

@ -29,3 +29,12 @@ class Source:
async def skip_current(self) -> None: async def skip_current(self) -> None:
pass pass
def init_server(self) -> None:
pass
def init_client(self) -> None:
pass
available_sources = {}

View file

@ -5,28 +5,29 @@ from functools import partial
from pytube import YouTube, Search, Channel, innertube from pytube import YouTube, Search, Channel, innertube
from mpv import MPV from mpv import MPV
from .source import Source, async_in_thread from .source import Source, async_in_thread, available_sources
from ..entry import Entry from ..entry import Entry
from ..result import Result from ..result import Result
class YoutubeSource(Source): class YoutubeSource(Source):
def __init__(self): def __init__(self, config):
super().__init__() super().__init__()
self.innertube_client = innertube.InnerTube(client="WEB") self.innertube_client = innertube.InnerTube(client="WEB")
self.channels = ["/c/CCKaraoke"] self.channels = config["channels"] if "channels" in config else []
@async_in_thread @async_in_thread
def play(self, ident: str) -> None: def play(self, ident: str) -> None:
self.player = MPV( player = MPV(
input_default_bindings=True, input_default_bindings=True,
input_vo_keyboard=True, input_vo_keyboard=True,
osc=True, osc=True,
ytdl=True, ytdl=True,
script_opts="ytdl_hook-ytdl_path=yt-dlp", script_opts="ytdl_hook-ytdl_path=yt-dlp",
) )
self.player.play(ident) player.play(ident)
self.player.wait_for_playback() player.wait_for_playback()
del player
async def skip_current(self) -> None: async def skip_current(self) -> None:
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
@ -112,3 +113,6 @@ class YoutubeSource(Source):
except KeyError: except KeyError:
pass pass
return list_of_videos return list_of_videos
available_sources["youtube"] = YoutubeSource