cyp/app/js/yt.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-03-29 04:43:18 +08:00
import * as mpd from "./lib/mpd.js";
import * as html from "./lib/html.js";
2019-03-31 05:05:33 +08:00
import * as conf from "./conf.js";
2019-03-29 04:43:18 +08:00
let node;
2019-04-15 00:09:42 +08:00
const decoder = new TextDecoder("utf-8");
function decodeChunk(byteArray) {
2019-04-15 03:02:21 +08:00
// \r => \n
return decoder.decode(byteArray).replace(/\u000d/g, "\n");
2019-04-15 00:09:42 +08:00
}
2019-03-29 04:43:18 +08:00
2019-04-15 03:02:21 +08:00
async function post(q) {
let pre = node.querySelector("pre");
html.clear(pre);
2019-03-29 04:43:18 +08:00
2019-04-15 03:02:21 +08:00
node.classList.add("pending");
2019-03-31 05:05:33 +08:00
2019-03-29 04:43:18 +08:00
let body = new URLSearchParams();
2019-04-15 03:02:21 +08:00
body.set("q", q);
2019-03-29 04:43:18 +08:00
let response = await fetch("/youtube", {method:"POST", body});
2019-03-31 05:05:33 +08:00
2019-04-15 00:09:42 +08:00
let reader = response.body.getReader();
while (true) {
let { done, value } = await reader.read();
if (done) { break; }
2019-04-15 03:02:21 +08:00
pre.textContent += decodeChunk(value);
pre.scrollTop = pre.scrollHeight;
2019-04-15 00:09:42 +08:00
}
reader.releaseLock();
2019-03-31 05:05:33 +08:00
2019-04-15 03:02:21 +08:00
node.classList.remove("pending");
2019-03-31 05:05:33 +08:00
if (response.status == 200) {
mpd.command(`update ${mpd.escape(conf.ytPath)}`);
}
2019-03-29 04:43:18 +08:00
}
2019-04-15 03:02:21 +08:00
function download() {
let url = prompt("Please enter a YouTube URL:");
if (!url) { return; }
post(url);
}
function search() {
let q = prompt("Please enter a search string:");
if (!q) { return; }
post(`ytsearch:${q}`);
}
function clear() {
html.clear(node.querySelector("pre"));
}
2019-03-29 04:43:18 +08:00
export async function activate() {}
export function init(n) {
node = n;
2019-04-15 03:02:21 +08:00
node.querySelector(".download").addEventListener("click", e => download());
node.querySelector(".search-download").addEventListener("click", e => search());
node.querySelector(".clear").addEventListener("click", e => clear());
2019-03-29 04:43:18 +08:00
}