You've already forked RadioPlayer
mirror of
https://github.com/radio95-rnt/RadioPlayer.git
synced 2026-02-26 21:53:54 +01:00
man this api
This commit is contained in:
169
modules/web.html
169
modules/web.html
@@ -33,11 +33,11 @@
|
|||||||
ul.playlist li.selected{background:rgba(62, 165, 255, 0.305)}
|
ul.playlist li.selected{background:rgba(62, 165, 255, 0.305)}
|
||||||
.controls{display:flex; gap:8px; margin-top:8px}
|
.controls{display:flex; gap:8px; margin-top:8px}
|
||||||
.two-col{display:flex; gap:8px; align-items:flex-start; height:100%}
|
.two-col{display:flex; gap:8px; align-items:flex-start; height:100%}
|
||||||
.box{display:flex; flex-direction:column; gap:8px}
|
.box{display:flex; flex-direction:column; gap:8px; flex-grow: 1; overflow: hidden;}
|
||||||
.listbox{height:100%; min-height:220px; overflow:auto; border-radius:6px; background:var(--card); padding:8px; font-size:14px}
|
.listbox{height:100%; min-height:220px; overflow:auto; border-radius:6px; background:var(--card); padding:8px; font-size:14px; scrollbar-width: none;}
|
||||||
.listbox div.item{padding:6px; border-radius:6px}
|
.listbox div.item{padding:6px; border-radius:6px}
|
||||||
.listbox div.item:hover{background:rgba(255,255,255,0.02); cursor:pointer}
|
.listbox div.item:hover{background:rgba(255,255,255,0.02); cursor:pointer}
|
||||||
.listbox div.item.selected{background:rgba(62,166,255,0.08)}
|
.listbox div.item.selected{background:rgba(62, 165, 255, 0.305)}
|
||||||
.small{font-size:12px; color:var(--muted)}
|
.small{font-size:12px; color:var(--muted)}
|
||||||
.row{display:flex; gap:8px; align-items:center}
|
.row{display:flex; gap:8px; align-items:center}
|
||||||
.muted{color:var(--muted); font-size:13px}
|
.muted{color:var(--muted); font-size:13px}
|
||||||
@@ -107,13 +107,13 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const HOST = "192.168.1.93";
|
const WS_URL = `ws://192.168.1.93:3001`;
|
||||||
const WS_URL = `ws://${HOST}:3001`; // WebSocket endpoint
|
|
||||||
|
|
||||||
let ws = null;
|
let ws = null;
|
||||||
let reconnectDelay = 1000;
|
let reconnectDelay = 1000;
|
||||||
let playlist = [];
|
let playlist = [];
|
||||||
let putQueue = []; // if available via HTTP
|
let lastplaylist_len = 0;
|
||||||
|
let putQueue = [];
|
||||||
let currentTrackPath = "";
|
let currentTrackPath = "";
|
||||||
let selectedPlaylistIndex = null;
|
let selectedPlaylistIndex = null;
|
||||||
let selectedDir = null;
|
let selectedDir = null;
|
||||||
@@ -145,10 +145,9 @@
|
|||||||
|
|
||||||
ws.addEventListener("message", (evt) => {
|
ws.addEventListener("message", (evt) => {
|
||||||
try {
|
try {
|
||||||
const msg = JSON.parse(evt.data);
|
handleMessage(JSON.parse(evt.data));
|
||||||
handleMessage(msg);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn("Bad msg", evt.data);
|
console.warn("Bad msg", evt.data);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -165,13 +164,12 @@
|
|||||||
renderPlaylist();
|
renderPlaylist();
|
||||||
} else if(msg.event === "new_track"){
|
} else if(msg.event === "new_track"){
|
||||||
// msg.data contains index, track, next_track
|
// msg.data contains index, track, next_track
|
||||||
const t = msg.data;
|
applyTrackState(msg.data);
|
||||||
applyTrackState(t);
|
|
||||||
} else if(msg.event === "progress"){
|
} else if(msg.event === "progress"){
|
||||||
applyProgressState(msg.data);
|
applyProgressState(msg.data);
|
||||||
} else if(msg.event === "dirs"){
|
} else if(msg.event === "toplay") {
|
||||||
updateDirs(d.dirs);
|
putQueue = msg.response.data;
|
||||||
} else if(msg.status || msg.response || msg.error){
|
} else if(msg.status || msg.response || msg.error) {
|
||||||
// simple ack or response from server for commands
|
// simple ack or response from server for commands
|
||||||
console.debug("ws ack", msg);
|
console.debug("ws ack", msg);
|
||||||
}
|
}
|
||||||
@@ -217,6 +215,8 @@
|
|||||||
const ul = document.getElementById("playlist-ul");
|
const ul = document.getElementById("playlist-ul");
|
||||||
ul.innerHTML = "";
|
ul.innerHTML = "";
|
||||||
let currentIndex = null;
|
let currentIndex = null;
|
||||||
|
if(lastplaylist_len === playlist.length + putQueue.length) return;
|
||||||
|
else lastplaylist_len = playlist.length + putQueue.length;
|
||||||
// if server gives index with progress use that, otherwise try infer
|
// if server gives index with progress use that, otherwise try infer
|
||||||
// We'll ask server for state if needed
|
// We'll ask server for state if needed
|
||||||
// Build lines similar to your Tkinter logic
|
// Build lines similar to your Tkinter logic
|
||||||
@@ -229,9 +229,7 @@
|
|||||||
li.textContent = `${String(idx).padStart(2,'0')}: ${displayPath}`;
|
li.textContent = `${String(idx).padStart(2,'0')}: ${displayPath}`;
|
||||||
li.dataset.path = path;
|
li.dataset.path = path;
|
||||||
li.dataset.idx = i;
|
li.dataset.idx = i;
|
||||||
li.addEventListener("click", () => {
|
li.addEventListener("click", () => { selectPlaylistItem(i, li); });
|
||||||
selectPlaylistItem(i, li);
|
|
||||||
});
|
|
||||||
ul.appendChild(li);
|
ul.appendChild(li);
|
||||||
});
|
});
|
||||||
// highlight current: try to find index that matches currentTrackPath
|
// highlight current: try to find index that matches currentTrackPath
|
||||||
@@ -239,18 +237,25 @@
|
|||||||
const child = ul.children[i];
|
const child = ul.children[i];
|
||||||
const p = child.dataset.path;
|
const p = child.dataset.path;
|
||||||
if(p && currentTrackPath.includes(p)){
|
if(p && currentTrackPath.includes(p)){
|
||||||
child.classList.add("current");
|
child.classList.add("current");
|
||||||
currentIndex = i;
|
currentIndex = i;
|
||||||
} else child.classList.remove("current");
|
} else child.classList.remove("current");
|
||||||
}
|
}
|
||||||
// scroll to current
|
// scroll to current
|
||||||
if(currentIndex !== null){
|
if(currentIndex !== null){
|
||||||
const el = ul.children[currentIndex];
|
const el = ul.children[currentIndex];
|
||||||
|
putQueue.forEach(element => {
|
||||||
|
console.log(element)
|
||||||
|
});
|
||||||
if(el) el.scrollIntoView({block:'center'});
|
if(el) el.scrollIntoView({block:'center'});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectPlaylistItem(i, el){
|
function selectPlaylistItem(i, el){
|
||||||
|
if(el.classList.contains("selected")) {
|
||||||
|
el.classList.remove("selected");
|
||||||
|
return;
|
||||||
|
}
|
||||||
// single-select visual
|
// single-select visual
|
||||||
const ul = document.getElementById("playlist-ul");
|
const ul = document.getElementById("playlist-ul");
|
||||||
Array.from(ul.children).forEach(c => c.classList.remove("selected"));
|
Array.from(ul.children).forEach(c => c.classList.remove("selected"));
|
||||||
@@ -262,7 +267,7 @@
|
|||||||
const dirsBox = document.getElementById("dirs-box");
|
const dirsBox = document.getElementById("dirs-box");
|
||||||
dirsBox.innerHTML = "Loading...";
|
dirsBox.innerHTML = "Loading...";
|
||||||
try {
|
try {
|
||||||
// basePath = data.base || "";
|
basePath = payload.base || "";
|
||||||
const files = payload.files || [];
|
const files = payload.files || [];
|
||||||
const dirs = payload.dirs || [];
|
const dirs = payload.dirs || [];
|
||||||
dirsBox.innerHTML = "";
|
dirsBox.innerHTML = "";
|
||||||
@@ -277,85 +282,88 @@
|
|||||||
const node = document.createElement("div");
|
const node = document.createElement("div");
|
||||||
node.className = "item";
|
node.className = "item";
|
||||||
node.textContent = f;
|
node.textContent = f;
|
||||||
node.addEventListener("click", () => onDirClicked(f, node));
|
node.addEventListener("click", () => {
|
||||||
|
Array.from(dirsBox.children).forEach(c=>c.classList.remove("selected"));
|
||||||
|
node.classList.add("selected"); selectedSubFile = f;
|
||||||
|
});
|
||||||
dirsBox.appendChild(node);
|
dirsBox.appendChild(node);
|
||||||
});
|
});
|
||||||
}catch(e){
|
} catch(e) {
|
||||||
dirsBox.innerHTML = "Error fetching dirs: "+e.message;
|
dirsBox.innerHTML = "Error fetching dirs: "+e.message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function onDirClicked(name, node){
|
function onDirClicked(name, node){
|
||||||
// highlight selection
|
// highlight selection
|
||||||
Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
|
Array.from(document.getElementById("dirs-box").children).forEach(c => c.classList.remove("selected"));
|
||||||
node.classList.add("selected");
|
node.classList.add("selected");
|
||||||
selectedDir = name;
|
selectedDir = name;
|
||||||
updateSubdirFiles(name);
|
updateSubdirFiles(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function updateSubdirFiles(dirname){
|
async function updateSubdirFiles(dirname){
|
||||||
const sub = document.getElementById("subdir-box");
|
const sub = document.getElementById("subdir-box");
|
||||||
document.getElementById("current-subdir").textContent = dirname;
|
document.getElementById("current-subdir").textContent = dirname;
|
||||||
sub.innerHTML = "Loading...";
|
sub.innerHTML = "Loading...";
|
||||||
try{
|
try{
|
||||||
const res = await fetch(`${API_BASE}/dir/${encodeURIComponent(dirname)}`, {cache:'no-cache'});
|
const res = await fetch(`${API_BASE}/dir/${encodeURIComponent(dirname)}`, {cache:'no-cache'});
|
||||||
if(!res.ok) throw new Error(res.statusText);
|
if(!res.ok) throw new Error(res.statusText);
|
||||||
const files = await res.json();
|
const files = await res.json();
|
||||||
sub.innerHTML = "";
|
sub.innerHTML = "";
|
||||||
files.sort().forEach(f => {
|
files.sort().forEach(f => {
|
||||||
const node = document.createElement("div");
|
const node = document.createElement("div");
|
||||||
node.className = "item";
|
node.className = "item";
|
||||||
node.textContent = f;
|
node.textContent = f;
|
||||||
node.addEventListener("click", () => {
|
node.addEventListener("click", () => {
|
||||||
Array.from(sub.children).forEach(c=>c.classList.remove("selected"));
|
Array.from(sub.children).forEach(c=>c.classList.remove("selected"));
|
||||||
node.classList.add("selected"); selectedSubFile = f;
|
node.classList.add("selected"); selectedSubFile = f;
|
||||||
});
|
});
|
||||||
sub.appendChild(node);
|
sub.appendChild(node);
|
||||||
});
|
});
|
||||||
}catch(e){
|
}catch(e){
|
||||||
sub.innerHTML = "Error: "+e.message;
|
sub.innerHTML = "Error: "+e.message;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Buttons actions ----------
|
// ---------- Buttons actions ----------
|
||||||
document.getElementById("skip-btn").addEventListener("click", () => {
|
document.getElementById("skip-btn").addEventListener("click", () => {
|
||||||
if(ws && ws.readyState === WebSocket.OPEN){
|
if(ws && ws.readyState === WebSocket.OPEN){
|
||||||
ws.send(JSON.stringify({action:"skip"}));
|
ws.send(JSON.stringify({action:"skip"}));
|
||||||
} else {
|
} else {
|
||||||
// fallback to HTTP endpoint
|
// fallback to HTTP endpoint
|
||||||
fetch(`${API_BASE}/skip`, {method:'POST'}).catch(()=>alert("Skip failed"));
|
fetch(`${API_BASE}/skip`, {method:'POST'}).catch(()=>alert("Skip failed"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById("readd-btn").addEventListener("click", () => {
|
document.getElementById("readd-btn").addEventListener("click", () => {
|
||||||
if(selectedPlaylistIndex == null){
|
if(selectedPlaylistIndex == null){
|
||||||
alert("Select a playlist item to re-add.");
|
alert("Select a playlist item to re-add.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const selected = playlist[selectedPlaylistIndex];
|
const selected = playlist[selectedPlaylistIndex];
|
||||||
if(!selected) { alert("Invalid selection"); return; }
|
if(!selected) { alert("Invalid selection"); return; }
|
||||||
const path = selected.path;
|
const path = selected.path;
|
||||||
sendAddToToplay([path]);
|
sendAddToToplay([path]);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById("add-file-btn").addEventListener("click", () => {
|
document.getElementById("add-file-btn").addEventListener("click", () => {
|
||||||
// add selected item from dirs (only if it's a file)
|
// add selected item from dirs (only if it's a file)
|
||||||
const dirEls = document.getElementById("dirs-box").children;
|
const dirEls = document.getElementById("dirs-box").children;
|
||||||
let sel = null;
|
let sel = null;
|
||||||
for(let c of dirEls) if(c.classList.contains("selected")) { sel = c; break; }
|
for(let c of dirEls) if(c.classList.contains("selected")) { sel = c; break; }
|
||||||
if(!sel) { alert("Select file or directory from left list"); return; }
|
if(!sel) { alert("Select file or directory from left list"); return; }
|
||||||
const name = sel.textContent;
|
const name = sel.textContent;
|
||||||
// only add if it looks like a file (has extension)
|
// only add if it looks like a file (has extension)
|
||||||
if(name.indexOf('.') === -1){ alert("Select a file (not a directory) or use subdir files"); return; }
|
if(name.indexOf('.') === -1){ alert("Select a file (not a directory) or use subdir files"); return; }
|
||||||
const full = basePath.replace(/\/$/,'') + '/' + name;
|
const full = basePath.replace(/\/$/,'') + '/' + name;
|
||||||
sendAddToToplay([full]);
|
sendAddToToplay([full]);
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById("add-sub-file-btn").addEventListener("click", () => {
|
document.getElementById("add-sub-file-btn").addEventListener("click", () => {
|
||||||
if(!selectedDir) { alert("Select a directory first"); return; }
|
if(!selectedDir) { alert("Select a directory first"); return; }
|
||||||
if(!selectedSubFile) { alert("Select a file from subdirectory"); return; }
|
if(!selectedSubFile) { alert("Select a file from subdirectory"); return; }
|
||||||
const full = basePath.replace(/\/$/,'') + '/' + selectedDir + '/' + selectedSubFile;
|
const full = basePath.replace(/\/$/,'') + '/' + selectedDir + '/' + selectedSubFile;
|
||||||
sendAddToToplay([full]);
|
sendAddToToplay([full]);
|
||||||
});
|
});
|
||||||
|
|
||||||
function sendAddToToplay(songs){
|
function sendAddToToplay(songs){
|
||||||
@@ -364,12 +372,7 @@
|
|||||||
ws.send(JSON.stringify({action:"request_state", what:"playlist"}));
|
ws.send(JSON.stringify({action:"request_state", what:"playlist"}));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post-initialization
|
|
||||||
connectWs();
|
connectWs();
|
||||||
|
|
||||||
// expose for debugging
|
|
||||||
window._radio95 = {connectWs, playlist, updateSubdirFiles};
|
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ async def ws_handler(websocket: ServerConnection, shared_data: dict, imc_q: mult
|
|||||||
await websocket.send(json.dumps({"event": "state", "data": initial}))
|
await websocket.send(json.dumps({"event": "state", "data": initial}))
|
||||||
|
|
||||||
async for raw in websocket:
|
async for raw in websocket:
|
||||||
try: msg = json.loads(raw)
|
try: msg: dict = json.loads(raw)
|
||||||
except Exception:
|
except Exception:
|
||||||
await websocket.send(json.dumps({"error": "invalid json"}))
|
await websocket.send(json.dumps({"error": "invalid json"}))
|
||||||
continue
|
continue
|
||||||
@@ -50,10 +50,10 @@ async def ws_handler(websocket: ServerConnection, shared_data: dict, imc_q: mult
|
|||||||
break
|
break
|
||||||
await asyncio.sleep(0.05)
|
await asyncio.sleep(0.05)
|
||||||
if result is None: await websocket.send(json.dumps({"error": "timeout", "code": 504}))
|
if result is None: await websocket.send(json.dumps({"error": "timeout", "code": 504}))
|
||||||
else: await websocket.send(json.dumps({"status": "ok", "response": result}))
|
else: await websocket.send(json.dumps({"status": "ok", "response": result, "event": "toplay"}))
|
||||||
elif action == "request_state":
|
elif action == "request_state":
|
||||||
# supports requesting specific parts if provided
|
# supports requesting specific parts if provided
|
||||||
what = msg.get("what")
|
what = msg.get("what", "")
|
||||||
try:
|
try:
|
||||||
if what == "playlist": payload = json.loads(shared_data.get("playlist", "[]"))
|
if what == "playlist": payload = json.loads(shared_data.get("playlist", "[]"))
|
||||||
elif what == "track": payload = json.loads(shared_data.get("track", "{}"))
|
elif what == "track": payload = json.loads(shared_data.get("track", "{}"))
|
||||||
@@ -68,24 +68,25 @@ async def ws_handler(websocket: ServerConnection, shared_data: dict, imc_q: mult
|
|||||||
}
|
}
|
||||||
except Exception: payload = {}
|
except Exception: payload = {}
|
||||||
await websocket.send(json.dumps({"event": "state", "data": payload}))
|
await websocket.send(json.dumps({"event": "state", "data": payload}))
|
||||||
else:
|
elif action == "request_dir":
|
||||||
await websocket.send(json.dumps({"error": "unknown action"}))
|
what: str = msg.get(what, "")
|
||||||
|
try:
|
||||||
|
dir = Path(MAIN_PATH_DIR, what).resolve()
|
||||||
|
payload = {"files": [i.name for i in list(dir.iterdir()) if i.is_file()], "dirs": [i.name for i in list(dir.iterdir()) if i.is_dir()], "base": str(dir)}
|
||||||
|
except Exception: payload = {}
|
||||||
|
await websocket.send(json.dumps({"event": "state", "data": payload}))
|
||||||
|
else: await websocket.send(json.dumps({"error": "unknown action"}))
|
||||||
|
|
||||||
async def broadcast_worker(shared_data: dict, ws_q: multiprocessing.Queue, clients: set):
|
async def broadcast_worker(ws_q: multiprocessing.Queue, clients: set):
|
||||||
"""
|
"""
|
||||||
Reads messages from ws_q (a blocking multiprocessing.Queue) using run_in_executor
|
Reads messages from ws_q (a blocking multiprocessing.Queue) using run_in_executor
|
||||||
and broadcasts them to all connected clients.
|
and broadcasts them to all connected clients.
|
||||||
"""
|
"""
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
while True:
|
while True:
|
||||||
# blocking get executed in default threadpool so we don't block the event loop
|
|
||||||
msg = await loop.run_in_executor(None, ws_q.get)
|
msg = await loop.run_in_executor(None, ws_q.get)
|
||||||
if msg is None:
|
if msg is None: break
|
||||||
# sentinel to shut down
|
|
||||||
break
|
|
||||||
# msg expected to be serializable (e.g. {"event": "playlist", "data": ...})
|
|
||||||
payload = json.dumps(msg)
|
payload = json.dumps(msg)
|
||||||
# send concurrently; ignore per-client errors (client may disconnect)
|
|
||||||
if clients:
|
if clients:
|
||||||
coros = []
|
coros = []
|
||||||
for ws in list(clients):
|
for ws in list(clients):
|
||||||
@@ -94,15 +95,10 @@ async def broadcast_worker(shared_data: dict, ws_q: multiprocessing.Queue, clien
|
|||||||
|
|
||||||
|
|
||||||
async def _safe_send(ws, payload: str, clients: set):
|
async def _safe_send(ws, payload: str, clients: set):
|
||||||
try:
|
try: await ws.send(payload)
|
||||||
await ws.send(payload)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
# remove dead websocket
|
try: clients.discard(ws)
|
||||||
try:
|
except Exception: pass
|
||||||
clients.discard(ws)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def websocket_server_process(shared_data: dict, imc_q: multiprocessing.Queue, ws_q: multiprocessing.Queue):
|
def websocket_server_process(shared_data: dict, imc_q: multiprocessing.Queue, ws_q: multiprocessing.Queue):
|
||||||
"""
|
"""
|
||||||
@@ -123,7 +119,7 @@ def websocket_server_process(shared_data: dict, imc_q: multiprocessing.Queue, ws
|
|||||||
# start server
|
# start server
|
||||||
server = await websockets.serve(handler_wrapper, "0.0.0.0", 3001)
|
server = await websockets.serve(handler_wrapper, "0.0.0.0", 3001)
|
||||||
# background task: broadcast worker
|
# background task: broadcast worker
|
||||||
broadcaster = asyncio.create_task(broadcast_worker(shared_data, ws_q, clients))
|
broadcaster = asyncio.create_task(broadcast_worker(ws_q, clients))
|
||||||
# run forever until server closes
|
# run forever until server closes
|
||||||
await server.wait_closed()
|
await server.wait_closed()
|
||||||
# ensure broadcaster stops
|
# ensure broadcaster stops
|
||||||
|
|||||||
Reference in New Issue
Block a user