diff --git a/tampermonkey.js b/tampermonkey.js new file mode 100644 index 0000000..d17234e --- /dev/null +++ b/tampermonkey.js @@ -0,0 +1,89 @@ +// ==UserScript== +// @name Youtube Downloader +// @author Cyka +// @match https://www.youtube.com/* +// @version 1.19 +// @run-at document-idle +// @noframes +// ==/UserScript== + +const API = "https://pocketbase-scratch.site.quack-lab.dev/api/collections/youtubedownload/records"; + +function waitForElement(element, selector) { + return new Promise((resolve) => { + if (element.querySelector(selector)) { + return resolve(element.querySelector(selector)); + } + + const observer = new MutationObserver((mutations) => { + if (element.querySelector(selector)) { + resolve(element.querySelector(selector)); + observer.disconnect(); + } + }); + + observer.observe(element, { + childList: true, + subtree: true, + }); + }); +} + +function parseVideo(videoElement) { + console.log(videoElement); + hookVideo(videoElement); +} + +function hookVideo(videoElement) { + console.log("Hooking", videoElement); + + videoElement.addEventListener( + "mousedown", + function (e) { + if (e.button === 1) { + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); + + const link = videoElement.querySelector("a#video-title-link").href; + console.log(link); + fetch(API, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + link: link, + }), + }).then((res) => { + console.log(res); + res.json().then((data) => console.log(data)); + }); + } + }, + false + ); +} + +async function main() { + const videosContainer = await waitForElement(document, "div#contents.style-scope.ytd-rich-grid-renderer"); + + for (const video of videosContainer.querySelectorAll("ytd-rich-item-renderer")) { + parseVideo(video); + } + + new MutationObserver((mutations) => { + mutations = mutations.filter((mutation) => mutation.addedNodes.length > 0); + + for (const mutation of mutations) { + if (mutation.target.tagName == "YTD-RICH-ITEM-RENDERER") { + parseVideo(mutation.target); + } + } + }).observe(videosContainer, { + childList: true, + subtree: true, + }); +} + +main();