Raw Source
alch_emi / Talkgroup CSV Downloader

// ==UserScript==
// @name        Talkgroup CSV Downloader
// @namespace   Violentmonkey Scripts
// @match       https://www.radioreference.com/db/sid/*
// @grant       none
// @version     1.0
// @author      Alch-Emi
// @description Download talkgroups from radioreference.com in a CSV compatible with TrunkRecorder
// @updateURL https://codeberg.org/alch_emi/talkgroup-csv-downloader/raw/branch/main/script.user.js
// @license GPL-3.0-only
// ==/UserScript==
// This is a bit hastily thrown together, but it should work for most systems.
//
// To use:
// - Navigate to the page for a system on radioreference.com.  These pages have the URL /db/sid/#### where # is a digit, and have a "Talkgroups" section with some tables.
// - Click the blue "Menu" button in the top-right-ish area, then click "Download as CSV"
// - If all goes well, you should get a save-as dialog

(() => {
	const into_pairs = a => Object.values(Object.groupBy(a, (_, i) => Math.floor(i/2)));
	const get_csv_headers = () => Array.from(document.querySelectorAll("#DataTables_Table_0 > thead > tr > th")).map(e => e.innerText.trim().replace("DEC", "Decimal").replace("HEX", "Hex")).concat(["Category"]);
	const get_table_elements = () => Array.from(document.getElementById("talkgroups").children).filter(c => (c.className == "row"&&c.getElementsByTagName("h5").length > 0)||c.classList.contains("dataTables_wrapper"));
	const elements_to_rows = table_elements => into_pairs(table_elements).flatMap(([a, b]) => Array.from(b.querySelectorAll(".data-text > tr")).map(r => Array.from(r.children).map(c => c.innerText).concat([a.getElementsByTagName("h5")[0].innerText.trim()])));
	const rows_to_csv = headers => rows => headers + "\n" + rows.join("\n");

	function save(data, mime) {
		const blob = new Blob([data], { type: mime })
		const link = document.createElement("a");
		link.href = URL.createObjectURL(blob);
		link.download = "ChanList.csv";
		link.click();
		URL.revokeObjectURL(link.href);
	}

	const go = () => save(rows_to_csv(get_csv_headers())(elements_to_rows(get_table_elements())), "text/plain");

	function rewire_download_button() {
		const button = document.querySelector("a.dropdown-item[href$=\"/download\"]");
		button.removeAttribute("href");
		button.onclick = go;
		button.innerHTML = "<i class=\"cil-cloud-download mr-2\"></i>Download as CSV";
	}

	rewire_download_button();
})();