Studydrive Downloader

Download Studydrive documents

// ==UserScript==
// @name         Studydrive Downloader
// @namespace    http://tampermonkey.net/
// @version      2024-10-14
// @description  Download Studydrive documents
// @author       You
// @match        https://www.studydrive.net/*/doc/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=studydrive.net
// @grant        GM_download
// @grant        GM_registerMenuCommand
// @license MIT
// ==/UserScript==

(function() {
	'use strict';

	async function download() {
		if(!PDFView.pdfDocument.getData) {
			alert("ERROR: Could not get pdf data, maybe the mechanics have changed");
		}

		const blobData = await PDFView.pdfDocument.getData();
		const blobUrl = await URL.createObjectURL(new Blob([blobData], {
			type: "application/pdf"
		}));

		let fileName;
		try {
			fileName = document.querySelector("#main-container h1").textContent;
		} catch {
			fileName = "document.pdf"; // Fallback name
		}

		GM_download(blobUrl, fileName);
	}

	function setupDownloadButton() {
		const downloadButton = document.querySelector("button[data-specific-auth-trigger=download]");
		if (downloadButton) {
			// Replace original download button with copy so that we get rid of the original click listeners
			const buttonCopy = downloadButton.cloneNode(true);
			downloadButton.parentNode.replaceChild(buttonCopy, downloadButton);
			buttonCopy.addEventListener('click', download);
			console.log("Download button was setup up correctly");
			return true;
		} else {
			//console.log("Download button was not found");
			return false;
		}
	}


	// Try setting up the download button multiple times to avoid timing issues
	const setupDownloadButtonInterval = setInterval(() => {
		if(setupDownloadButton()) {
			clearInterval(setupDownloadButtonInterval);
		}
	}, 500);

	// Register a menu command as a backup method to start the download
	GM_registerMenuCommand("Download", download)

})();