cyp/app/js/mpd.js

72 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-03-20 03:45:23 +08:00
import * as parser from "./parser.js";
let ws;
let commandQueue = [];
2019-03-20 23:20:17 +08:00
let current;
2019-03-20 03:45:23 +08:00
function onMessage(e) {
2019-03-20 23:20:17 +08:00
if (current) {
let lines = JSON.parse(e.data);
let last = lines.pop();
if (last.startsWith("OK")) {
current.resolve(lines);
} else {
current.reject(last);
}
current = null;
2019-03-20 03:45:23 +08:00
}
processQueue();
}
function onError(e) {
console.error(e);
ws = null; // fixme
}
function onClose(e) {
console.warn(e);
ws = null; // fixme
}
function processQueue() {
2019-03-20 23:20:17 +08:00
if (current || commandQueue.length == 0) { return; }
current = commandQueue.shift();
ws.send(current.cmd);
2019-03-20 03:45:23 +08:00
}
2019-03-20 05:56:39 +08:00
export function escape(str) {
return str.replace(/(['"\\])/g, "\\$1");
}
2019-03-20 03:45:23 +08:00
2019-03-20 05:56:39 +08:00
export async function command(cmd) {
2019-03-20 23:20:17 +08:00
if (cmd instanceof Array) { cmd = ["command_list_begin", ...cmd, "command_list_end"].join("\n"); }
return new Promise((resolve, reject) => {
commandQueue.push({cmd, resolve, reject});
2019-03-20 05:56:39 +08:00
processQueue();
});
2019-03-20 03:45:23 +08:00
}
2019-03-20 23:20:17 +08:00
export async function commandAndStatus(cmd) {
let lines = await command([cmd, "status", "currentsong"]);
return parser.linesToStruct(lines);
}
export async function status() {
2019-03-20 03:45:23 +08:00
let lines = await command(["status", "currentsong"]);
return parser.linesToStruct(lines);
}
export async function init() {
return new Promise((resolve, reject) => {
try {
2019-03-20 23:20:17 +08:00
ws = new WebSocket("ws://localhost:8080");
2019-03-20 03:45:23 +08:00
} catch (e) { reject(e); }
2019-03-20 23:20:17 +08:00
current = {resolve, reject};
2019-03-20 03:45:23 +08:00
ws.addEventListener("error", onError);
ws.addEventListener("message", onMessage);
ws.addEventListener("close", onClose);
});
}