cyp/app/js/elements/yt.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-03-10 05:24:31 +08:00
import * as html from "../html.js";
import * as conf from "../conf.js";
2020-03-13 06:03:26 +08:00
import { escape } from "../mpd.js";
2020-03-10 05:24:31 +08:00
import Component from "../component.js";
2020-03-09 21:26:39 +08:00
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
2020-03-09 21:26:39 +08:00
class YT extends Component {
_onAppLoad() {
this.querySelector(".download").addEventListener("click", _ => this._download());
this.querySelector(".search-download").addEventListener("click", _ => this._search());
this.querySelector(".clear").addEventListener("click", _ => this._clear());
}
2019-03-31 05:05:33 +08:00
2020-03-09 21:26:39 +08:00
_download() {
let url = prompt("Please enter a YouTube URL:");
if (!url) { return; }
2019-03-31 05:05:33 +08:00
2020-03-09 21:26:39 +08:00
this._post(url);
2019-04-15 00:09:42 +08:00
}
2019-03-31 05:05:33 +08:00
2020-03-09 21:26:39 +08:00
_search() {
let q = prompt("Please enter a search string:");
if (!q) { return; }
2019-04-15 03:02:21 +08:00
2020-03-09 21:26:39 +08:00
this._post(`ytsearch:${q}`);
2019-03-31 05:05:33 +08:00
}
2019-03-29 04:43:18 +08:00
2020-03-09 21:26:39 +08:00
_clear() {
html.clear(this.querySelector("pre"));
}
2019-04-15 03:02:21 +08:00
2020-03-09 21:26:39 +08:00
async _post(q) {
let pre = this.querySelector("pre");
html.clear(pre);
2019-04-15 03:02:21 +08:00
2020-03-09 21:26:39 +08:00
this.classList.add("pending");
2019-04-15 03:02:21 +08:00
2020-03-09 21:26:39 +08:00
let body = new URLSearchParams();
body.set("q", q);
let response = await fetch("/youtube", {method:"POST", body});
2019-04-15 03:02:21 +08:00
2020-03-09 21:26:39 +08:00
let reader = response.body.getReader();
while (true) {
let { done, value } = await reader.read();
if (done) { break; }
pre.textContent += decodeChunk(value);
pre.scrollTop = pre.scrollHeight;
}
reader.releaseLock();
2019-03-29 04:43:18 +08:00
2020-03-09 21:26:39 +08:00
this.classList.remove("pending");
if (response.status == 200) {
2020-03-13 06:03:26 +08:00
this._mpd.command(`update ${escape(conf.ytPath)}`);
2020-03-09 21:26:39 +08:00
}
}
_onComponentChange(c, isThis) {
this.hidden = !isThis;
}
2019-03-29 04:43:18 +08:00
}
2020-03-09 21:26:39 +08:00
customElements.define("cyp-yt", YT);