Merge branch 'main' into 95-send-spots-to-xota

# Conflicts:
#	README.md
#	config-example.yml
#	core/config.py
#	server/handlers/api/addspot.py
#	server/handlers/api/options.py
#	static/js/add-spot.js
#	static/js/bands.js
#	static/js/map.js
This commit is contained in:
Ian Renton
2026-08-02 07:47:40 +01:00
509 changed files with 1072 additions and 609 deletions
+307
View File
@@ -0,0 +1,307 @@
// Credentials schema per provider name. Defines the fields to collect and how to label them.
const PROVIDER_CREDENTIAL_SCHEMAS = {
// todo Figure out SOTA authentication
// see e.g. https://github.com/ham2k/app-polo/blob/main/src/extensions/activities/sota/SOTAAccount.jsx
// https://github.com/ham2k/app-polo/blob/main/src/store/apis/apiSOTA/apiSOTA.js
// Refresh token? Way to show user that they need to log in again because cached credentials aren't valid?
// todo type: text/password distinction on text boxes so API keys can be obscured
"SOTA": [
{key: "access_token", label: "SOTA Access Token", help: ""},
{key: "id_token", label: "SOTA ID Token", help: "TODO SOTA authentication to provide this..."}
],
"ParksNPeaks": [
{key: "user_id", label: "Parks N Peaks User ID", help: ""},
{key: "api_key", label: "Parks N Peaks API Key", help: "Get your API key from your Parks N Peaks account."}
],
"ZLOTA": [
{key: "user_id", label: "ZLOTA User ID", help: ""},
{key: "api_key", label: "ZLOTA User PIN", help: "Get your PIN from your ZLOTA account."}
],
"Tiles": [
{
key: "offline_spot_gateway_pin",
label: "Offline Spot Gateway PIN",
help: "Get your PIN from your Tiles on the Air account profile."
}
]
};
// Load server options. Once a successful callback is made from this, we can populate the choice boxes in the form and load
// any saved values from local storage.
function loadOptions() {
$.getJSON('/api/v2/options', function (jsonData) {
// Store options
options = jsonData;
// Populate modes drop-down
$.each(options["modes"], function (i, m) {
$('#mode').append($('<option>', {
value: m,
text: m
}));
});
// Populate SIG drop-down
$.each(options["sigs"], function (i, sig) {
$('#sig').append($('<option>', {
value: sig.name,
text: sig.name
}));
});
// Load reCAPTCHA if a site key is configured (key is inlined into page by server)
if (window._recaptchaSiteKey) {
loadRecaptcha(window._recaptchaSiteKey);
}
// Load settings from settings storage now all the controls are available
loadSettings();
// Update the upstream area for any pre-selected SIG
updateUpstreamArea();
});
}
// Load and inject the reCAPTCHA script
function loadRecaptcha(siteKey) {
window._recaptchaSiteKey = siteKey;
if (!document.getElementById('recaptcha-script')) {
const script = document.createElement('script');
script.id = 'recaptcha-script';
script.src = 'https://www.google.com/recaptcha/api.js?render=explicit&onload=renderRecaptcha';
script.async = true;
script.defer = true;
document.head.appendChild(script);
}
$("#recaptcha-area").show();
}
// Called by reCAPTCHA after its script loads
function renderRecaptcha() {
window._recaptchaWidgetId = grecaptcha.render('recaptcha-widget', {
sitekey: window._recaptchaSiteKey,
size: 'normal'
});
}
// Update the "Send spot to..." area based on the currently selected SIG
function updateUpstreamArea() {
if (!window._allowUpstreamSpotting || !options || !options["spot_submit_providers"]) {
$("#upstream-area").hide();
return;
}
const sig = $("#sig").val();
const providers = (sig && options["spot_submit_providers"][sig]) ? options["spot_submit_providers"][sig] : [];
if (providers.length === 0) {
$("#upstream-area").hide();
return;
}
$("#upstream-area").show();
// Update the provider selector
$("#upstream-provider-select").empty();
$.each(providers, function (i, name) {
$("#upstream-provider-select").append($('<option>', {value: name, text: name}));
});
if (providers.length > 1) {
$("#upstream-provider-label").text("upstream spot sources:");
$("#upstream-provider-select-col").show();
} else {
$("#upstream-provider-label").text(providers[0]);
$("#upstream-provider-select-col").hide();
}
// Show the credentials button if this provider has an authentication mechanism and we need input from the user
updateCredentialsButton();
}
// Update the credentials button visibility based on selected provider
function updateCredentialsButton() {
const providerName = getSelectedUpstreamProvider();
if (providerName && PROVIDER_CREDENTIAL_SCHEMAS[providerName]) {
$("#upstream-credentials-btn").show();
} else {
$("#upstream-credentials-btn").hide();
}
}
// Get the currently selected upstream provider name
function getSelectedUpstreamProvider() {
const providers = (options && options["spot_submit_providers"] && $("#sig").val())
? (options["spot_submit_providers"][$("#sig").val()] || [])
: [];
if (providers.length === 0) return null;
if (providers.length === 1) return providers[0];
return $("#upstream-provider-select").val();
}
// Show the credentials modal for the currently selected upstream provider
function showCredentialsModal() {
const providerName = getSelectedUpstreamProvider();
if (!providerName || !PROVIDER_CREDENTIAL_SCHEMAS[providerName]) return;
const schema = PROVIDER_CREDENTIAL_SCHEMAS[providerName];
const stored = loadCredentials(providerName);
$("#credentials-provider-name").text(providerName);
$("#credentials-fields").empty();
$.each(schema, function (i, field) {
const val = stored[field.key] || "";
let html = '<div class="mb-3">';
html += '<label for="cred-' + field.key + '" class="form-label">' + field.label + '</label>';
html += '<input type="text" class="form-control" id="cred-' + field.key + '" value="' + $('<div>').text(val).html() + '">';
if (field.help) {
html += '<div class="form-text">' + field.help + '</div>';
}
html += '</div>';
$("#credentials-fields").append(html);
});
// Store provider name for saveCredentials()
$("#credentials-modal").data("provider", providerName);
new bootstrap.Modal(document.getElementById('credentials-modal')).show();
}
// Save credentials from the modal to local storage
function saveCredentials() {
const providerName = $("#credentials-modal").data("provider");
if (!providerName || !PROVIDER_CREDENTIAL_SCHEMAS[providerName]) return;
const schema = PROVIDER_CREDENTIAL_SCHEMAS[providerName];
const creds = {};
$.each(schema, function (i, field) {
creds[field.key] = $("#cred-" + field.key).val();
});
localStorage.setItem("upstream-credentials-" + providerName, JSON.stringify(creds));
bootstrap.Modal.getInstance(document.getElementById('credentials-modal')).hide();
}
// Load credentials for a provider from local storage
function loadCredentials(providerName) {
const stored = localStorage.getItem("upstream-credentials-" + providerName);
return stored ? JSON.parse(stored) : {};
}
// Method called to add a spot to the server
function addSpot() {
try {
// Save settings (this will save "your call" for future use)
saveSettings();
// Unpack the user's entered values
const dx = $("#dx-call").val().toUpperCase();
const freqStr = $("#freq").val();
const mode = $("#mode")[0].value;
const sig = $("#sig")[0].value;
const sigRef = $("#sig-ref").val();
const dxGrid = $("#dx-grid").val();
const comment = $("#comment").val();
const de = $("#de-call").val().toUpperCase();
// Prepare the spot object for the server
const spot = {};
spot["dx_call"] = dx;
spot["freq"] = parseFloat(freqStr) * 1000;
if (mode !== "") spot["mode"] = mode;
if (sig !== "") spot["sig"] = sig;
if (sigRef !== "") spot["sig_refs"] = [{sig: sig, id: sigRef}];
if (dxGrid !== "") spot["dx_grid"] = dxGrid;
if (comment !== "") spot["comment"] = comment;
spot["de_call"] = de;
spot["time"] = moment.utc().valueOf() / 1000.0;
// Prepare "handling" structure to tell the server what to do with this spot
const handling = {};
// Add CAPTCHA token if reCAPTCHA is loaded
if (window._recaptchaWidgetId !== undefined) {
handling["captcha_token"] = grecaptcha.getResponse(window._recaptchaWidgetId);
}
// Upstream submission
const submitUpstream = $("#submit-upstream").is(":checked");
const upstreamProviderName = getSelectedUpstreamProvider();
if (submitUpstream && upstreamProviderName) {
handling["submit_upstream"] = true;
handling["upstream_provider"] = upstreamProviderName;
handling["upstream_credentials"] = loadCredentials(upstreamProviderName);
}
$.ajax("/api/v2/spot", {
data: JSON.stringify({spot, handling}),
contentType: 'application/json',
type: 'POST',
timeout: 10000,
success: async function (result) {
// Reset CAPTCHA for next use
if (window._recaptchaWidgetId !== undefined) {
grecaptcha.reset(window._recaptchaWidgetId);
}
if (result && result.startsWith && result.startsWith("Warning")) {
$("#result-good").html("<div class='alert alert-warning fade show mb-0 mt-4' role='alert'><i class='fa-solid fa-triangle-exclamation'></i> " + result + " Returning you to the spots list...</div>");
} else {
$("#result-good").html("<div class='alert alert-success fade show mb-0 mt-4' role='alert'><i class='fa-solid fa-check'></i> Spot submitted. Returning you to the spots list...</div>");
}
$("#result-bad").html("");
setTimeout(() => {
$("#result-good").hide();
window.location.replace("/");
}, 2000);
},
error: function (result) {
if (window._recaptchaWidgetId !== undefined) {
grecaptcha.reset(window._recaptchaWidgetId);
}
if (result.responseText) {
showAddSpotError(result.responseText.slice(1, -1));
} else {
showAddSpotError("The server did not return a response.");
}
}
});
} catch (error) {
showAddSpotError(error);
}
return false;
}
// Show an "add spot" error.
function showAddSpotError(text) {
const div = $("<div class='alert alert-danger alert-dismissible fade show mb-0 mt-4' role='alert'></div>");
div.append("<i class='fa-solid fa-triangle-exclamation'></i> ");
div.append(document.createTextNode(text));
div.append("<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>");
$("#result-bad").empty().append(div);
}
// Force callsign and mode capitalisation
$("#dx-call").change(function () {
$(this).val($(this).val().trim().toUpperCase());
});
$("#de-call").change(function () {
$(this).val($(this).val().trim().toUpperCase());
});
$("#mode").change(function () {
$(this).val($(this).val().trim().toUpperCase());
});
// Update upstream area and credentials button when SIG changes
$("#sig").change(function () {
updateUpstreamArea();
});
// Update credentials button when provider selector changes
$("#upstream-provider-select").change(function () {
updateCredentialsButton();
});
// Startup
$(document).ready(function () {
// Load options
loadOptions();
});
+346
View File
@@ -0,0 +1,346 @@
// How often to query the server?
const REFRESH_INTERVAL_SEC = 60 * 10;
// Last time the alerts list was updated on display.
let lastUpdateTime;
// Storage for the alert data that the server gives us.
let alerts = [];
// Load alerts and populate the table.
function loadAlerts() {
$.ajax({url: '/api/v2/alerts' + buildQueryString(), dataType: 'json', headers: getCredentialHeaders(), success: function (jsonData) {
// Store last updated time
lastUpdateTime = moment.utc();
updateRefreshDisplay();
// Store data
alerts = jsonData;
// Update table
updateTable();
}});
}
// Build a query string for the API, based on the filters that the user has selected.
function buildQueryString() {
let str = "?";
["dx_continent", "source"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&";
}
});
str = str + "limit=" + $("#alerts-to-fetch option:selected").val();
const maxDur = $("#max-duration option:selected").val();
if (maxDur !== "9999999999") {
str = str + "&max_duration=" + maxDur;
}
if ($("#dxpeditions_skip_max_duration_check")[0].checked) {
str = str + "&dxpeditions_skip_max_duration_check=true";
}
return str;
}
// Update the alerts table
function updateTable() {
// Use local time instead of UTC?
const useLocalTime = $("#timeZone")[0].value === "local";
// Table data toggles
const showStartTime = $("#tableShowStartTime")[0].checked;
const showEndTime = $("#tableShowEndTime")[0].checked;
const showDX = $("#tableShowDX")[0].checked;
const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
const showComment = $("#tableShowComment")[0].checked;
const showSource = $("#tableShowSource")[0].checked;
const showRef = $("#tableShowRef")[0].checked;
// Populate table with headers
let table = $("#table");
table.find('thead tr').empty();
if (showStartTime) {
table.find('thead tr').append(`<th class="bg-primary-subtle">${useLocalTime ? "Start&nbsp;(Local)" : "Start&nbsp;UTC"}</th>`);
}
if (showEndTime) {
table.find('thead tr').append(`<th class="bg-primary-subtle">${useLocalTime ? "End&nbsp;(Local)" : "End&nbsp;UTC"}</th>`);
}
if (showDX) {
table.find('thead tr').append(`<th class="bg-primary-subtle">DX</th>`);
}
if (showFreqsModes) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Freq<span class='hideonmobile'>uencie</span>s & Modes</th>`);
}
if (showComment) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Comment</th>`);
}
if (showSource) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Source</th>`);
}
if (showRef) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Ref.</th>`);
}
table.find('tbody').empty();
// Split alerts into three types, each of which will get its own table header: On now, next 24h, and later. "On now"
// is considered to be events with an end_time where start<now<end, or events with no end time that started in the
// last hour.
const onNow = alerts.filter(a => (a["end_time"] != null && a["end_time"] !== 0 && moment.unix(a["end_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore())
|| ((a["end_time"] == null || a["end_time"] === 0) && moment.unix(a["start_time"]).utc().add(1, 'hours').isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore()));
const next24h = alerts.filter(a => moment.unix(a["start_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().subtract(24, 'hours').isBefore());
const later = alerts.filter(a => moment.unix(a["start_time"]).utc().subtract(24, 'hours').isSameOrAfter());
if (onNow.length > 0) {
table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">On Now</td></tr>');
addAlertRowsToTable(table.find('tbody'), onNow);
}
if (next24h.length > 0) {
table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">Starting within 24 hours</td></tr>');
addAlertRowsToTable(table.find('tbody'), next24h);
}
if (later.length > 0) {
table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">Starting later </td></tr>');
addAlertRowsToTable(table.find('tbody'), later);
}
if (onNow.length === 0 && next24h.length === 0 && later.length === 0) {
table.find('tbody').append('<tr class="bg-danger-subtle"><td colspan="100" style="text-align:center;">No alerts match your filters.</td></tr>');
}
}
// Add a row to tbody for each alert in the provided list
function addAlertRowsToTable(tbody, alerts) {
let count = 0;
alerts.forEach(a => {
// Create row
let $tr = $('<tr>');
// Apply striping to the table. We can't just use Bootstrap's table-striped class because we have all sorts of
// extra faff to deal with, like the mobile view having extra rows, and the On Now / Next 24h / Later banners
// which cause the table-striped colouring to go awry.
if (count % 2 === 1) {
$tr.addClass("table-active");
}
// Use local time instead of UTC?
const useLocalTime = $("#timeZone")[0].value === "local";
// Table data toggles
const showStartTime = $("#tableShowStartTime")[0].checked;
const showEndTime = $("#tableShowEndTime")[0].checked;
const showDX = $("#tableShowDX")[0].checked;
const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
const showComment = $("#tableShowComment")[0].checked;
const showSource = $("#tableShowSource")[0].checked;
const showRef = $("#tableShowRef")[0].checked;
// Get times for the alert, and convert to local time if necessary.
const start_time_utc = moment.unix(a["start_time"]).utc();
const start_time_local = start_time_utc.clone().local();
const start_time = useLocalTime ? start_time_local : start_time_utc;
const end_time_utc = moment.unix(a["end_time"]).utc();
const end_time_local = end_time_utc.clone().local();
const end_time = useLocalTime ? end_time_local : end_time_utc;
// Format the times for display. Start time is displayed as e.g. 7 Oct 12:34 unless the time is in a
// different year to the current year, in which case the year is inserted between month and hour.
// If the time is set to local not UTC, and the date in local time is "today", we display that instead.
// End time is displayed the same as above, except if the end date is the same as the start date, in which case
// just e.g. 23:45 is used.
// Overriding all of that, if the start time is 00:00 and the end time is 23:59 when considered in UTC, the
// hours and minutes are stripped out from the display, as we assume the server is just giving us full days.
// Finally, if there is no end date set, "---" is displayed.
const whole_days = start_time_utc.format("HH:mm") === "00:00" &&
(end_time_utc === 0 || end_time_utc.format("HH:mm") === "23:59");
const hours_minutes_format = whole_days ? "" : " HH:mm";
let start_time_formatted = start_time.format("D MMM" + hours_minutes_format);
if (start_time.format("YYYY") !== moment().format("YYYY")) {
start_time_formatted = start_time.format("D MMM YYYY" + hours_minutes_format);
} else if (useLocalTime && start_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
start_time_formatted = start_time.format("[Today]" + hours_minutes_format);
}
let end_time_formatted = "---";
if (end_time_utc > 0 && end_time != null) {
end_time_formatted = whole_days ? start_time_formatted : end_time.format("HH:mm");
if (end_time.format("D MMM") !== start_time.format("D MMM")) {
if (end_time.format("YYYY") !== moment().format("YYYY")) {
end_time_formatted = end_time.format("D MMM YYYY" + hours_minutes_format);
} else if (useLocalTime && end_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
end_time_formatted = end_time.format("[Today]" + hours_minutes_format);
} else {
end_time_formatted = end_time.format("D MMM" + hours_minutes_format);
}
}
}
// Format dx country
let dx_country = a["dx_country"];
if (dx_country == null) {
dx_country = "Unknown or not a country"
}
// Format DX flag
let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
if (a["dx_dxcc_id"] && a["dx_dxcc_id"] != null && a["dx_dxcc_id"] !== 0) {
dx_flag = `<img src="static/img/flags/${a['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`;
}
// Format dx calls
let dx_calls_html = "";
if (a["dx_calls"] != null) {
dx_calls_html = a["dx_calls"].map(call => `<a class='dx-link' href='https://qrz.com/db/${call}' target='_new'>${call}</a>`).join(", ");
}
// Format DXpedition country
let dx_country_html = "";
if (a["is_dxpedition"] === true && a["dx_country"] != null && a["dx_country"] !== "") {
dx_country_html = `<br/>${a["dx_country"]}`;
}
// Format freqs & modes
let freqsModesText = "";
if (a["freqs_modes"] != null) {
freqsModesText = escapeHtml(a["freqs_modes"]);
}
// Format comment
let commentText = "";
if (a["comment"] != null) {
commentText = escapeHtml(a["comment"]);
}
// Sig or fallback to source
let sigSourceText = a["source"];
if (a["sig"]) {
sigSourceText = a["sig"];
}
// Format sig_refs
let sig_refs = "";
if (a["sig_refs"] != null) {
const items = [];
for (let i = 0; i < a["sig_refs"].length; i++) {
if (a["sig_refs"][i]["url"] != null) {
items[i] = `<a href='${encodeURI(a["sig_refs"][i]["url"])}' title='${escapeHtml(a["sig_refs"][i]["name"])}' target='_new' class='sig-ref-link'>${escapeHtml(a["sig_refs"][i]["id"])}</a>`
} else {
items[i] = `${escapeHtml(a["sig_refs"][i]["id"])}`
}
}
sig_refs = items.join(", ");
}
// Populate the row
if (showStartTime) {
$tr.append(`<td class='nowrap'>${start_time_formatted}</td>`);
}
if (showEndTime) {
$tr.append(`<td class='nowrap'>${end_time_formatted}</td>`);
}
if (showDX) {
$tr.append(`<td class='nowrap'><span class='flag-wrapper hideonmobile' title='${dx_country}'>${dx_flag}</span>${dx_calls_html}${dx_country_html}</td>`);
}
if (showFreqsModes) {
$tr.append(`<td class='hideonmobile'>${freqsModesText}</td>`);
}
if (showComment) {
$tr.append(`<td class='hideonmobile'>${commentText}</td>`);
}
if (showSource) {
$tr.append(`<td class='nowrap hideonmobile'><span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> ${sigSourceText}</td>`);
}
if (showRef) {
$tr.append(`<td class='hideonmobile'>${sig_refs}</td>`);
}
tbody.append($tr);
// Second row for mobile view only, containing source, ref, freqs/modes & comment
const $tr2 = $("<tr class='hidenotonmobile'>");
if (count % 2 === 1) {
$tr2.addClass("table-active");
}
const $td2 = $("<td colspan='100'>");
if (showSource) {
$td2.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> `);
}
if (showRef) {
$td2.append(`${sig_refs} `);
}
if (showFreqsModes) {
$td2.append(`${freqsModesText} `);
}
if (showComment) {
$td2.append(`<br/>${commentText} `);
}
$tr2.append($td2);
tbody.append($tr2);
count++;
});
}
// Load server options. Once a successful callback is made from this, we then query alerts.
function loadOptions() {
$.getJSON('/api/v2/options', function (jsonData) {
// Store options
options = jsonData;
// Populate the filters panel
generateMultiToggleFilterCard("#dx-continent-options", "dx_continent", options["continents"]);
generateMultiToggleFilterCard("#source-options", "source", options["alert_sources"]);
// Load URL params. These may select things from the various filter & display options, so the function needs
// to be called after these are set up, but if the URL params ask for "embedded mode", this will suppress
// loading settings, so this needs to be called before that.
loadURLParams();
// Load filters from settings storage
loadSettings();
setColorScheme($("#color-scheme option:selected").val());
// Load alerts and set up the timer
loadAlerts();
setInterval(loadAlerts, REFRESH_INTERVAL_SEC * 1000);
});
}
// Method called when any filter is changed to reload the alerts and persist the filter settings.
function filtersUpdated() {
loadAlerts();
saveSettings();
}
// Update the refresh timing display
function updateRefreshDisplay() {
if (lastUpdateTime != null) {
let secSinceUpdate = moment.duration(moment().diff(lastUpdateTime)).asSeconds();
let count = REFRESH_INTERVAL_SEC;
let updatingString = "Updating..."
if (secSinceUpdate < REFRESH_INTERVAL_SEC) {
count = REFRESH_INTERVAL_SEC - secSinceUpdate;
let number;
if (count <= 60) {
number = count.toFixed(0);
updatingString = "<span class='nowrap'>Updating in " + number + " second" + (number !== "1" ? "s" : "") + ".</span>";
} else {
number = Math.round(count / 60.0).toFixed(0);
updatingString = "<span class='nowrap'>Updating in " + number + " minute" + (number !== "1" ? "s" : "") + ".</span>";
}
}
$("#timing-container").html("Last updated at " + lastUpdateTime.format('HH:mm') + " UTC. " + updatingString);
}
}
// Startup
$(document).ready(function () {
// Call loadOptions(), this will then trigger loading alerts and setting up timers.
loadOptions();
// Update the refresh timing display every second
setInterval(updateRefreshDisplay, 1000);
});
// Reload alerts on becoming visible. This forces a refresh when used as a PWA and the user switches back to the PWA
// after some time has passed with it in the background.
addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadAlerts();
}
});
+328
View File
@@ -0,0 +1,328 @@
// SSE connection for live spot updates
let evtSource;
let restartSSEOnErrorTimeoutId;
// Debounce timer so rapid SSE bursts only trigger one updateBands() call, as these could trigger a flash of the user
// visible content
let updateBandsDebounceId;
// A couple of constants that must match what's in CSS. We need to know them before the content actually renders, so we
// can't just ask the elements themselves for their dimensions.
BAND_COLUMN_HEIGHT_EM = 62;
BAND_COLUMN_CANVAS_WIDTH_EM = 4;
BAND_COLUMN_FONT_SIZE = 16;
BAND_COLUMN_HEIGHT_PX = BAND_COLUMN_HEIGHT_EM * BAND_COLUMN_FONT_SIZE;
BAND_COLUMN_CANVAS_WIDTH_PX = BAND_COLUMN_CANVAS_WIDTH_EM * BAND_COLUMN_FONT_SIZE;
BAND_COLUMN_SPOT_DIV_HEIGHT_PX = BAND_COLUMN_FONT_SIZE * 1.6;
// Load spots and populate the bands display.
function loadSpots() {
// Close any existing SSE connection before fetching fresh data
if (evtSource != null) {
evtSource.close();
}
$.ajax({url: '/api/v2/spots' + buildQueryString(), dataType: 'json', headers: getCredentialHeaders(), success: function (jsonData) {
// Store data
spots = jsonData;
// Update bands display
updateBands();
// Start the ongoing SSE connection
startSSEConnection();
});
}
// Start an SSE connection to receive new spots as they arrive.
function startSSEConnection() {
if (evtSource != null) {
evtSource.close();
}
evtSource = new EventSource('/api/v2/spots/stream' + buildQueryString());
evtSource.onmessage = function (event) {
const newSpot = JSON.parse(event.data);
// Replace any existing spot for this callsign
spots = spots.filter(s => newSpot["dx_call"] !== s["dx_call"]);
spots.unshift(newSpot);
// Debounce. Wait 500ms after the last message before re-rendering to avoid too many ugly flashes
clearTimeout(updateBandsDebounceId);
updateBandsDebounceId = setTimeout(updateBands, 5000);
};
evtSource.onerror = function () {
if (evtSource != null) {
evtSource.close();
}
clearTimeout(restartSSEOnErrorTimeoutId);
restartSSEOnErrorTimeoutId = setTimeout(startSSEConnection, 1000);
};
}
// Remove spots from the display that are older than the selected max age.
function expireOldSpots() {
const maxAgeSeconds = parseInt($("#max-spot-age option:selected").val());
const cutoff = (Date.now() / 1000) - maxAgeSeconds;
const before = spots.length;
spots = spots.filter(s => s["time"] && s["time"] >= cutoff);
if (spots.length !== before) {
updateBands();
}
}
// Build a query string for the API, based on the filters that the user has selected. There's no need for credentials
// in the bands page's version of this, because nothing QRZ.com/HamQTH can provide will affect the display.
function buildQueryString() {
let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&";
}
});
str = str + "max_age=" + $("#max-spot-age option:selected").val();
// Additional filters for the bands view: No dupes, no QRT
str = str + "&dedupe=true&allow_qrt=false";
return str;
}
// Update the bands display
function updateBands() {
// Stop here if nothing to display
const bandsContainer = $("#bands-container");
if (spots.length === 0) {
bandsContainer.html("<div class='alert alert-danger' role='alert'>No spots match your filters.</div>");
return;
}
// Do some harsher de-duping. Because we only display callsign, frequency and mode here, the previous
// de-duplication could have let some through that don't look like dupes on the map, but would do here.
// Typically that's a person activating two programs at the same time, e.g. POTA & WWFF.
const spotList = removeDuplicatesForBandPanel(spots);
// Convert to a map of band names to the spots on that band. Bands with no
// spots in view will not be present.
const bandToSpots = new Map();
options["bands"].forEach(function (band) {
const matchingSpots = spotList.filter(function (s) {
return s.band === band.name;
});
if (matchingSpots.length > 0) {
bandToSpots.set(band.name, matchingSpots);
}
});
// Track if any columns end up taller than expected, so we can resize the container and avoid vertical scroll.
let maxHeightBand = 0;
// Build up table content for each band
const table = $('<table id="bands-table">').append('<thead><tr></tr></thead><tbody><tr></tr></tbody>');
bandToSpots.forEach(function (spotList, bandName) {
// Get the colours for the band from the first spot, and prepare the header
table.find('thead tr').append(`<th style='background-color:${bandToColor(spotList[0].band)}; color:${bandToContrastColor(spotList[0].band)}'>${spotList[0].band}</th>`);
// Get the band data to fetch start and end frequencies
let band = options["bands"].filter(function (b) {
return b.name === bandName;
})[0];
// Print the frequency band markers. This is 41 steps to divide the band evenly into 40 markers. One in every
// four will show the actual frequency, the others will just be dashes.
const bandMarkersDiv = $('<div class="band-markers">');
const freqStep = (band.end_freq - band.start_freq) / 40.0;
for (let i = 0; i <= 40; i++) {
if (i % 4 === 0) {
bandMarkersDiv.append("&mdash;" + ((band.start_freq + i * freqStep) / 1000000).toFixed(3) + "<br/>");
} else if (i % 4 === 2) {
bandMarkersDiv.append("&ndash;<br/>");
} else {
bandMarkersDiv.append("-<br/>");
}
}
// Prepare the spots list
const bandSpotsDiv = $("<div class='band-spots'>");
let lastSpotPxDownBand = -999;
// Sort by frequency so have a consistent order in which to plan where they will appear on the band div.
spotList.sort(function (a, b) {
return a.freq - b.freq;
});
// First calculate how we should be displaying the spots. There are three "modes" to try to place them in a
// visually appealing way:
// 1) Spaced normally, not going over the end of the band, so we populate them forwards.
// 2) Would go over the end, but the spots don't fill the band, so we populate them backwards.
// 3) Spots totally fill the band (or more), so we space them evenly starting at the top.
// In each case, we don't add anything to the DOM yet, we just calculate "pxDownBandLabel" (how far the *top* of
// the label is from the top of the div) and add that as a property to the spot for later use.
if (spotList.length >= BAND_COLUMN_HEIGHT_PX / BAND_COLUMN_SPOT_DIV_HEIGHT_PX) {
// Mode 3.
// Just lay out all spots simply, starting at 0px offset and working down with each one touching.
lastSpotPxDownBand = 0 - BAND_COLUMN_SPOT_DIV_HEIGHT_PX;
spotList.forEach(s => {
lastSpotPxDownBand = lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX;
s["pxDownBandLabel"] = lastSpotPxDownBand;
});
} else {
// Mode 1 or 2. Run through adding things to the list forwards as a test.
spotList.forEach(s => {
// Work out how far down the div to draw it
const percentDownBand = (s.freq - band.start_freq) / (band.end_freq - band.start_freq) * 0.97; // not 100% due to fudge, the first and last dashes are not exactly at the top and bottom of the div as some space is needed for text
let pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX;
if (pxDownBand < lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX) {
pxDownBand = lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap
}
s["pxDownBandLabel"] = pxDownBand;
lastSpotPxDownBand = pxDownBand;
});
// Work out if we overflowed the end.
if (lastSpotPxDownBand <= BAND_COLUMN_HEIGHT_PX) {
// Mode 1. Current positions are fine and there's nothing to do.
} else {
// Mode 2. Repeat the process but backwards, starting at the end and working upwards.
lastSpotPxDownBand = 999999;
spotList.reverse().forEach(s => {
// Work out how far down the div to draw it
const percentDownBand = (s.freq - band.start_freq) / (band.end_freq - band.start_freq) * 0.97; // not 100% due to fudge, the first and last dashes are not exactly at the top and bottom of the div as some space is needed for text
let pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX;
if (pxDownBand > lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX) {
pxDownBand = lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap
}
s["pxDownBandLabel"] = pxDownBand;
lastSpotPxDownBand = pxDownBand;
});
}
}
// Now each spot is tagged with how far down the div it should go, add them to the DOM.
spotList.forEach(s => {
let worked = alreadyWorked(s["dx_call"], s["band"], s["mode"]);
bandSpotsDiv.append(`<div class="band-spot" style="top: ${s['pxDownBandLabel']}px; border-top: 1px solid ${bandToColor(s['band'])}; border-left: 5px solid ${bandToColor(s['band'])}; border-bottom: 1px solid ${bandToColor(s['band'])}; border-right: 1px solid ${bandToColor(s['band'])}; text-decoration: ${worked ? 'line-through' : 'none'};"><span class="band-spot-call">${s.dx_call}${s.dx_ssid != null ? "-" + s.dx_ssid : ""}</span><span class="band-spot-info">${s.dx_call}${s.dx_ssid != null ? "-" + s.dx_ssid : ""} ${(s.freq / 1000000).toFixed(3)} ${s.mode}</span></div>`);
});
// Work out how tall the canvas should be. Normally this is matching the normal band column height, but if some
// spots have gone off the end of the band markers and stretched their div, we need to resize the canvas to
// match, otherwise we have nowhere to draw their connecting lines.
const canvasHeight = Math.max(BAND_COLUMN_HEIGHT_PX, lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX);
maxHeightBand = Math.max(maxHeightBand, canvasHeight);
// Draw horizontal or diagonal lines to join up the "real" frequency with where the spot div ended up
const bandLinesCanvas = $(`<canvas class='band-lines-canvas' width='${BAND_COLUMN_CANVAS_WIDTH_PX}px' height='${canvasHeight}px' style='height:${canvasHeight}px !important;'>`);
spotList.forEach(s => {
// Work out how far down the div to draw it
const percentDownBand = (s.freq - band.start_freq) / (band.end_freq - band.start_freq) * 0.97; // not 100% due to fudge, the first and last dashes are not exactly at the top and bottom of the div as some space is needed for text
const pxDownBandFreq = (percentDownBand + 0.015) * BAND_COLUMN_HEIGHT_PX; // same fudge but add half to put the left end of the line in the right place
const pxDownBandLabel = s["pxDownBandLabel"] + (BAND_COLUMN_SPOT_DIV_HEIGHT_PX / 1.75); // line should be to the vertical text-centre spot, not to the top corner
// Draw the line on the canvas
const ctx = bandLinesCanvas[0].getContext('2d');
ctx.beginPath();
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.strokeStyle = bandToColor(s['band']);
ctx.moveTo(0, pxDownBandFreq);
ctx.lineTo(BAND_COLUMN_CANVAS_WIDTH_PX, pxDownBandLabel);
ctx.stroke();
});
// Assemble the table cell
const td = $("<td>");
const container = $("<div class='band-container'>");
container.append(bandLinesCanvas);
container.append(bandMarkersDiv);
container.append(bandSpotsDiv);
td.append(container);
table.find('tbody tr').append(td);
});
// Update the DOM with the band HTML
bandsContainer.html(table);
// Increase the height of the bands container so we don't have any vertical scroll bars except the browser ones
bandsContainer.css("min-height", `${maxHeightBand + 42}px`);
// Desktop mouse wheel to scroll bands horizontally if used on the headers
table.find('thead tr').on("wheel", () => {
bandsContainer.scrollLeft(bandsContainer.scrollLeft() + event.deltaY / 10.0);
return false;
});
}
// Iterate through a temporary list of spots, merging duplicates in a way suitable for the band panel. If two or more
// spots with the activator, mode and frequency are found, these will be merged and reduced until only one remains,
// with the best data. Note that unlike removeDuplicates(), which operates on the main spot map, this operates only
// on the temporary array of spots provided as an argument, and returns the output, for use when constructing the
// band panel.
function removeDuplicatesForBandPanel(spotList) {
const spotsToRemove = [];
spotList.forEach(function (check) {
spotList.forEach(function (s) {
if (s !== check) {
if (s.dx_call === check.dx_call && s.freq === check.freq && s.mode === check.mode) {
// Find which one to keep and which to delete
const checkSpotNewer = check.time > s.time;
const deleteSpot = checkSpotNewer ? s : check;
// Aggregate list of spots to remove
spotsToRemove.push(deleteSpot.uid);
}
}
});
});
// Perform the removal
return spotList.filter(s => !spotsToRemove.includes(s.uid));
}
// Load server options. Once a successful callback is made from this, we then query spots and set up the timer to query
// spots repeatedly.
function loadOptions() {
$.getJSON('/api/v2/options', function (jsonData) {
// Store options
options = jsonData;
// First pass loading settings, so we can load the band colour scheme before the filters that need to use it
loadSettings();
setColorScheme($("#color-scheme option:selected").val());
setBandColorScheme($("#band-color-scheme option:selected").val());
// Add CSS for band toggle buttons
addBandToggleColourCSS(options["bands"]);
// Populate the filters panel
generateBandsMultiToggleFilterCard(options["bands"]);
generateSIGsMultiToggleFilterCard(options["sigs"]);
generateMultiToggleFilterCard("#dx-continent-options", "dx_continent", options["continents"]);
generateMultiToggleFilterCard("#de-continent-options", "de_continent", options["continents"]);
generateModesMultiToggleFilterCard(options["modes"]);
generateSourcesMultiToggleFilterCard(options["spot_sources"], spotProvidersEnabledByDefault);
// Load URL params. These may select things from the various filter & display options, so the function needs
// to be called after these are set up, but if the URL params ask for "embedded mode", this will suppress
// loading settings, so this needs to be called before that.
loadURLParams();
// Load settings from settings storage now all the controls are available
loadSettings();
// Load spots and start SSE for live updates
loadSpots();
// Set up spot expiry checker
setInterval(expireOldSpots, 60 * 1000);
});
}
// Method called when any display property is changed to reload the bands display and persist settings.
function displayUpdated() {
updateBands();
saveSettings();
}
// Startup
$(document).ready(function () {
// Close SSE connection cleanly when navigating away
window.addEventListener('beforeunload', function () {
if (evtSource != null) {
evtSource.close();
}
});
// Call loadOptions(), this will then trigger loading spots and setting up timers.
loadOptions();
});
+277
View File
@@ -0,0 +1,277 @@
// Storage for the options that the server gives us. This will define our filters.
let options = {};
// Normally load user settings from local storage, unless embedded mode is in use
let useLocalStorage = true;
// Save settings to local storage. Suppressed if "use local storage" is false.
function saveSettings() {
if (useLocalStorage) {
// Find all storeable UI elements, store a key of "element id:property name" mapped to the value of that
// property. For a checkbox, that's the "checked" property.
$(".storeable-checkbox").each(function () {
localStorage.setItem("#" + $(this)[0].id + ":checked", JSON.stringify($(this)[0].checked));
});
$(".storeable-select").each(function () {
localStorage.setItem("#" + $(this)[0].id + ":value", JSON.stringify($(this)[0].value));
});
$(".storeable-text").each(function () {
localStorage.setItem("#" + $(this)[0].id + ":value", JSON.stringify($(this)[0].value));
});
// Password fields are only saved if the corresponding "remember password" checkbox is ticked.
$(".password-field").each(function () {
const pwKey = "#" + $(this)[0].id + ":value";
const rememberCheckboxId = $(this).data("remember-checkbox");
if (rememberCheckboxId && $("#" + rememberCheckboxId)[0] && $("#" + rememberCheckboxId)[0].checked) {
localStorage.setItem(pwKey, JSON.stringify($(this)[0].value));
} else {
localStorage.removeItem(pwKey);
}
});
}
}
// Load settings from local storage and set up the filter selectors. Suppressed if "use local storage" is false.
function loadSettings() {
if (useLocalStorage) {
// Find all local storage entries and push their data to the corresponding UI element
Object.keys(localStorage).forEach(function (key) {
if (key.startsWith("#") && key.includes(":")) {
// Split the key back into an element ID and a property
const split = key.split(":");
$(split[0]).prop(split[1], JSON.parse(localStorage.getItem(key)));
}
});
}
}
// Load and apply any URL params. This is used for "embedded mode" where another site can embed a version of
// Spothole and provide its own interface options rather than using the user's saved ones. These may select things
// from the various filter & display options, so this function needs to be called after these are set up, but if
// the URL params ask for "embedded mode", this will suppress loading settings, so this needs to be called before
// that occurs..
function loadURLParams() {
let params = new URLSearchParams(document.location.search);
// Handle embedded mode. We set a global to e.g. suppress loading/saving settings, and apply an attribute to the
// top-level html element to use CSS selectors to remove bits of UI.
let embedded = params.get("embedded");
if (embedded != null && embedded === "true") {
useLocalStorage = false;
$("html").attr("embedded-mode", "true");
}
// Handle other params
updateSelectFromParam(params, "color-scheme", "color-scheme");
updateSelectFromParam(params, "time-zone", "time-zone"); // Only on Spots and Alerts pages
updateSelectFromParam(params, "limit", "spots-to-fetch"); // Only on Spots page
updateSelectFromParam(params, "limit", "alerts-to-fetch"); // Only on Alerts page
updateSelectFromParam(params, "max_age", "max-spot-age"); // Only on Map & Bands pages
updateFilterFromParam(params, "band", "band");
updateFilterFromParam(params, "sig", "sig");
updateFilterFromParam(params, "source", "source");
updateFilterFromParam(params, "mode", "mode");
updateFilterFromParam(params, "dx_continent", "dx_continent");
updateFilterFromParam(params, "de_continent", "de_continent");
}
// Update an HTML select element so that its value matches the given parameter
function updateSelectFromParam(params, paramName, selectID) {
let v = params.get(paramName);
if (v != null) {
$("#" + selectID).prop("value", v);
// Extra check if this is the "color scheme" select
if (selectID === "color-scheme") {
setColorScheme(v);
}
}
}
// Update a set of HTML checkbox elements describing a filter of the given name, so that any items named in the
// parameter (as a comma-separated list) will be enabled, and all others disabled. e.g. if paramName is
// "filter-band" and the params contain "filter-band=20m,40m", and prefix is "band", then #filter-button-band-30m
// would be disabled but #filter-button-band-20m and #filter-button-band-40m would be enabled.
function updateFilterFromParam(params, paramName, filterName) {
let v = params.get(paramName);
if (v != null) {
// First uncheck all options for the filter
$(".filter-button-" + filterName).prop("checked", false);
// Now find out which ones should be enabled
let s = v.split(",");
s.forEach(val => $("#filter-button-" + filterName + "-" + val).prop("checked", true));
}
}
// For a parameter, such as dx_continent, get the query string for the current filter options.
function getQueryStringFor(parameter) {
return parameter + "=" + encodeURIComponent(getSelectedFilterOptions(parameter));
}
// For a parameter, such as dx_continent, get the filter options that are currently selected in the UI.
function getSelectedFilterOptions(parameter) {
return $(".filter-button-" + parameter).filter(function () {
return this.checked;
}).map(function () {
return this.value;
}).get().join(",");
}
// For a parameter, such as dx_continent, return true if all possible options are enabled. (In this case, we don't need
// to bother sending this as one of the query parameters to the API; no parameter provided implies "send everything".)
function allFilterOptionsSelected(parameter) {
const filter = $(".filter-button-" + parameter).filter(function () {
return !this.checked;
}).get();
return filter.length === 0;
}
// Generate a filter card with inline checkboxes plus All/None links.
function generateMultiToggleFilterCard(elementID, filterQuery, options) {
const $row = $('<div>');
options.forEach(o => {
$row.append(`<div class="form-check form-check-inline"><input type="checkbox" class="form-check-input filter-button-${filterQuery} storeable-checkbox" id="filter-button-${filterQuery}-${o}" value="${o}" autocomplete="off" onClick="filtersUpdated()" checked><label class="form-check-label" for="filter-button-${filterQuery}-${o}">${o}</label></div>`);
});
$(elementID).append($row);
$(elementID).append(`<div class="mt-1"><a href="#" onclick="toggleFilterButtons('${filterQuery}', true); return false;">All</a> &nbsp; <a href="#" onclick="toggleFilterButtons('${filterQuery}', false); return false;">None</a></div>`);
}
// Method called when "All" or "None" is clicked
function toggleFilterButtons(filterQuery, state) {
$(".filter-button-" + filterQuery).each(function () {
$(this).prop('checked', state);
});
filtersUpdated();
}
// When the "use local time" field is changed, reload the table and save settings
function timeZoneUpdated() {
updateTable();
saveSettings();
}
// When one of the column toggle checkboxes are changed, reload the table and save settings
function columnsUpdated() {
updateTable();
saveSettings();
}
// Function to set the colour scheme based on the state of the UI select box
function setColorSchemeFromUI() {
let theme = $("#color-scheme option:selected").val();
if (theme !== "") {
setColorScheme(theme);
saveSettings();
}
}
// Function to set the color scheme. Supported values: "dark", "light", "auto"
function setColorScheme(mode) {
let effectiveModeDark = mode === "dark";
if (mode === "auto") {
effectiveModeDark = window.matchMedia('(prefers-color-scheme: dark)').matches
}
$("html").attr("data-bs-theme", effectiveModeDark ? "dark" : "light");
const metaThemeColor = document.querySelector("meta[name=theme-color]");
metaThemeColor.setAttribute("content", effectiveModeDark ? "black" : "white");
const metaAppleStatusBarStyle = document.querySelector("meta[name=apple-mobile-web-app-status-bar-style]");
metaAppleStatusBarStyle.setAttribute("content", effectiveModeDark ? "black-translucent" : "white-translucent");
}
// Startup function to determine whether to use light or dark mode, or leave as auto
function usePreferredTheme() {
// Work out if we have ever explicitly saved the value of our select box. If so, we set our colour scheme now based
// on that. If not, we let the select stay with nothing selected, so that the server sets it to whatever the
// server's default is when the options call is retrieved.
let val = localStorage.getItem("#color-scheme:value");
if (val != null) {
setColorScheme(JSON.parse(val));
}
}
// Sets up a listener on the OS light-dark theme change. If the Spothole user theme is set to Auto, the UI will be
// updated, otherwise if the Spothole user theme is forced to light or dark, that preference will remain.
function listenForOSThemeChange() {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
setColorScheme($("#color-scheme option:selected").val());
});
}
// Panel toggle functions
const PANELS = [
{area: "#filters-area", button: "#filters-button"},
{area: "#display-area", button: "#display-button"},
{area: "#data-area", button: "#data-button"},
];
// Toggle a panel open or closed. If opening, all other visible panels are closed first.
// areaId is the jQuery selector for the panel's content area, e.g. "#filters-area".
function togglePanel(areaId) {
if (!$(areaId).is(":visible")) {
PANELS.forEach(p => {
if (p.area !== areaId && $(p.area).is(":visible")) {
$(p.area).hide();
$(p.button).button("toggle");
}
});
}
$(areaId).toggle();
}
// Close a panel and deactivate its toggle button.
function closePanel(areaId) {
const panel = PANELS.find(p => p.area === areaId);
if (panel) {
$(panel.button).button("toggle");
}
$(areaId).hide();
}
function toggleFiltersPanel() {
togglePanel("#filters-area");
}
function closeFiltersPanel() {
closePanel("#filters-area");
}
function toggleDisplayPanel() {
togglePanel("#display-area");
}
function closeDisplayPanel() {
closePanel("#display-area");
}
function toggleDataPanel() {
togglePanel("#data-area");
}
function closeDataPanel() {
closePanel("#data-area");
}
// Build a headers object containing any QRZ.com / HamQTH credentials the user has supplied,
// provided the corresponding "enabled" checkbox is ticked.
function getCredentialHeaders() {
const headers = {};
if ($("#qrz-enabled")[0] && $("#qrz-enabled")[0].checked) {
const qrzUsername = $("#qrz-username").val();
const qrzPassword = $("#qrz-password").val();
if (qrzUsername) headers["X-QRZ-Username"] = qrzUsername;
if (qrzPassword) headers["X-QRZ-Password"] = qrzPassword;
}
if ($("#hamqth-enabled")[0] && $("#hamqth-enabled")[0].checked) {
const hamqthUsername = $("#hamqth-username").val();
const hamqthPassword = $("#hamqth-password").val();
if (hamqthUsername) headers["X-HamQTH-Username"] = hamqthUsername;
if (hamqthPassword) headers["X-HamQTH-Password"] = hamqthPassword;
}
return headers;
}
// Startup
$(document).ready(function () {
usePreferredTheme();
listenForOSThemeChange();
});
+674
View File
@@ -0,0 +1,674 @@
// Cache for the full dxstats API response, so we can reload on the fly if the user changes the value of their continent
// in the select box
let dxStatsData = null;
// Kp forecast chart
let kpChart = null;
// Cache for ionosonde data from the API
let ionosondeData = null;
// Ionosonde foF2/MUF chart
let ionosondeChart = null;
// Load solar conditions
function loadSolarConditions() {
$.getJSON('/api/v2/solar', function (jsonData) {
// HF
const hfConditionClass = {'Good': 'bg-success-subtle', 'Fair': 'bg-warning-subtle', 'Poor': 'bg-danger-subtle'};
if (jsonData.hf_conditions) {
$('#hamqsl-section').show();
Object.entries(jsonData.hf_conditions).forEach(function ([key, condition]) {
const cell = $('#hf-conditions-' + key);
cell.text(condition);
cell.addClass(hfConditionClass[condition]);
});
}
// VHF
if (jsonData.vhf_conditions) {
Object.entries(jsonData.vhf_conditions).forEach(function ([key, condition]) {
const cell = $('#vhf-conditions-' + key);
cell.text(condition);
let vhfClass;
if (condition === 'Band Closed') {
vhfClass = 'bg-danger-subtle';
} else if (condition.includes('High')) {
vhfClass = 'bg-warning-subtle';
} else {
vhfClass = 'bg-success-subtle';
}
cell.addClass(vhfClass);
});
}
if (jsonData.aurora_latitude !== null && jsonData.aurora_latitude !== undefined) {
$('#vhf-conditions-aurora-lat').text(jsonData.aurora_latitude + '°');
}
// Solar Weather
const swFields = {
'sfi': 'sw-sfi',
'sunspots': 'sw-sunspots',
'band_conditions_desc': 'sw-solar-flux-desc',
'k_index': 'sw-k-index',
'a_index': 'sw-a-index',
'geomag_field': 'sw-geomag-field',
'geomag_storm_scale': 'sw-geomag-storm-scale',
'geomag_storm_desc': 'sw-geomag-storm-desc',
'geomag_noise': 'sw-geomag-noise',
'xray': 'sw-xray',
'radio_blackout_scale': 'sw-radio-blackout-scale',
'xray_desc': 'sw-xray-desc',
'proton_flux': 'sw-proton-flux',
'solar_storm_scale': 'sw-solar-storm-scale',
'proton_flux_desc': 'sw-proton-desc',
'electron_flux': 'sw-electron-flux',
'electron_flux_desc': 'sw-electron-desc',
};
Object.entries(swFields).forEach(function ([field, id]) {
const val = jsonData[field];
if (val !== null && val !== undefined) {
$('#' + id).text(val);
}
});
// Solar Weather - colouring
function applySwClass(valsId, descId, cls) {
$('#' + valsId).addClass(cls);
$('#' + descId).addClass(cls);
}
const sfi = jsonData.sfi;
if (sfi !== null && sfi !== undefined) {
applySwClass('sw-solar-flux-vals', 'sw-solar-flux-desc',
sfi > 120 ? 'bg-success-subtle' : sfi > 90 ? 'bg-warning-subtle' : 'bg-danger-subtle');
}
const kIndex = jsonData.k_index;
if (kIndex !== null && kIndex !== undefined) {
applySwClass('sw-geomag-vals', 'sw-geomag-desc',
kIndex < 5 ? 'bg-success-subtle' : kIndex < 6 ? 'bg-warning-subtle' : 'bg-danger-subtle');
}
const xRay = jsonData.xray;
if (xRay) {
const letter = xRay[0].toUpperCase();
const xRayClass = (letter === 'X') ? 'bg-danger-subtle'
: (letter === 'M') ? 'bg-warning-subtle'
: 'bg-success-subtle';
applySwClass('sw-xray-vals', 'sw-xray-desc', xRayClass);
}
const protonFlux = jsonData.proton_flux;
if (protonFlux !== null && protonFlux !== undefined) {
applySwClass('sw-proton-vals', 'sw-proton-desc',
protonFlux <= 100 ? 'bg-success-subtle' : protonFlux <= 10000 ? 'bg-warning-subtle' : 'bg-danger-subtle');
}
const electronFlux = jsonData.electron_flux;
if (electronFlux !== null && electronFlux !== undefined) {
applySwClass('sw-electron-vals', 'sw-electron-desc',
electronFlux <= 100 ? 'bg-success-subtle' : electronFlux <= 1000 ? 'bg-warning-subtle' : 'bg-danger-subtle');
}
// Ionosonde
if (jsonData.ionosonde_data && Object.keys(jsonData.ionosonde_data).length > 0) {
$('#ionosonde-section').show();
ionosondeData = jsonData.ionosonde_data;
populateIonosondeDropdown(ionosondeData);
renderIonosondeData();
}
// Forecast
if (jsonData.k_index_forecast) {
$('#noaa-section').show();
}
renderKIndexForecast(jsonData.k_index_forecast);
renderSolarStormForecast(jsonData.solar_storm_forecast);
renderBlackoutForecast(jsonData.blackout_forecast_r1r2, jsonData.blackout_forecast_r3_or_greater);
});
}
// Render the K-index forecast as a Chart.js bar chart, one bar per 3-hour UTC period
function renderKIndexForecast(data) {
if (!data) return;
const entries = Object.entries(data)
.map(([tsStr, kp]) => ({ts: parseFloat(tsStr), kp}))
.sort((a, b) => a.ts - b.ts);
if (entries.length === 0) return;
// Use a simple integer index axis: ticks at 0, 1, 2, ..., N (period boundaries) and bars
// centred at 0.5, 1.5, ..., N-0.5 (midpoints). This guarantees tick marks fall exactly on
// bar edges regardless of how Chart.js rounds large timestamp values.
// "axisMin = 0" is the left/top edge of bar 0; "axisMax = N" is the right/bottom edge of bar N-1.
const N = entries.length;
const periodSecs = 3 * 3600;
// Inherit colours from Bootstrap CSS variables so that dark mode inherently works. We want bar colours that are not
// quite as saturated as the Bootstrap success/warning/danger colours but not as desaturated as the "subtle"
// versions, so use tinycolor to apply some transparency.
const style = getComputedStyle(document.documentElement);
const withAlpha = hex => tinycolor(hex).setAlpha(0.8).toRgbString();
const colors = entries.map(e =>
e.kp < 4.5 ? withAlpha(style.getPropertyValue('--bs-success').trim())
: e.kp < 5.5 ? withAlpha(style.getPropertyValue('--bs-warning').trim())
: withAlpha(style.getPropertyValue('--bs-danger').trim())
);
const textColor = style.getPropertyValue('--bs-body-color').trim() || '#666';
const gridColor = style.getPropertyValue('--bs-border-color').trim() || 'rgba(128,128,128,0.3)';
if (kpChart) {
kpChart.destroy();
}
const isMobile = window.innerWidth < 768;
const kpAxisTicks = {
stepSize: 1,
color: textColor,
// Include geomagnetic storm levels (Gx) alongside the Kp index
callback: v => v > 4 ? `(G${v - 4}) ${v}` : String(v),
};
const kpAxis = {
min: 0,
max: 9,
title: {display: true, text: 'Kp', color: textColor},
ticks: kpAxisTicks,
grid: {color: gridColor},
};
// Linear scale using integer indices. Ticks at 0..N (period boundary indices);
// the callback converts each integer index back to a UTC time string.
// On mobile the time axis is vertical, so reverse it to keep time running top-to-bottom.
const timeAxis = {
type: 'linear',
min: 0,
max: N,
offset: false,
reverse: isMobile,
title: {display: true, text: 'Time (UTC)', color: textColor},
ticks: {
stepSize: 1,
color: textColor,
maxRotation: 45,
minRotation: 0,
callback(value) {
if (!Number.isInteger(value) || value < 0 || value > N) return null;
const ts = value < N ? entries[value].ts : entries[N - 1].ts + periodSecs;
const dt = new Date(ts * 1000);
const h = dt.getUTCHours(), m = dt.getUTCMinutes();
const timeStr = String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0');
if (h === 0 && m === 0) {
return [timeStr, dt.toLocaleDateString('en-GB', {day: '2-digit', month: 'short', timeZone: 'UTC'})];
}
return timeStr;
},
},
grid: {color: gridColor, offset: false},
};
// Draw a "now" line at the current time position
const nowLinePlugin = {
id: 'nowLine',
afterDraw(chart) {
const nowTs = Date.now() / 1000;
// Find which bar (if any) the current time falls in and compute a fractional index
const firstTs = entries[0].ts;
const lastTs = entries[N - 1].ts + periodSecs;
if (nowTs < firstTs || nowTs > lastTs) return;
const fracIndex = (nowTs - firstTs) / periodSecs;
const {ctx, chartArea} = chart;
const scale = isMobile ? chart.scales.y : chart.scales.x;
const pos = scale.getPixelForValue(fracIndex);
ctx.save();
ctx.strokeStyle = textColor;
ctx.lineWidth = 2;
ctx.setLineDash([5, 4]);
ctx.beginPath();
if (isMobile) {
ctx.moveTo(chartArea.left, pos);
ctx.lineTo(chartArea.right, pos);
} else {
ctx.moveTo(pos, chartArea.top);
ctx.lineTo(pos, chartArea.bottom);
}
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = textColor;
ctx.font = '11px sans-serif';
if (isMobile) {
ctx.textAlign = 'right';
ctx.textBaseline = 'bottom';
ctx.fillText('Now', chartArea.right, pos - 3);
} else {
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(' Now', pos, chartArea.top + 3);
}
ctx.restore();
}
};
// Bars centred at i+0.5 (midpoint between tick i and tick i+1) so each bar spans
// exactly from tick i to tick i+1 with barPercentage/categoryPercentage = 1.0.
const chartData = isMobile
? entries.map((e, i) => ({x: e.kp, y: i + 0.5}))
: entries.map((e, i) => ({x: i + 0.5, y: e.kp}));
kpChart = new Chart(document.getElementById('forecast-kp-chart'), {
type: 'bar',
data: {
datasets: [{
data: chartData,
backgroundColor: colors,
hoverBackgroundColor: colors,
borderWidth: 0,
barPercentage: 1.0,
categoryPercentage: 1.0,
}]
},
options: {
responsive: true,
// Swap axes on mobile, and change the aspect ratio
aspectRatio: isMobile ? 0.4 : 3,
indexAxis: isMobile ? 'y' : 'x',
plugins: {
legend: {
display: false
},
tooltip: {
enabled: false
}
},
scales: {
x: isMobile ? kpAxis : timeAxis,
y: isMobile ? timeAxis : kpAxis,
}
},
plugins: [nowLinePlugin],
});
}
// Render the solar storm forecast table
function renderSolarStormForecast(data) {
if (!data) return;
const entries = Object.entries(data)
.map(([tsStr, pct]) => ({ts: parseFloat(tsStr), pct}))
.sort((a, b) => a.ts - b.ts);
// Header
const headRow = $('#forecast-solar-storm-head').empty().append('<th></th>');
entries.forEach(({ts}) => {
const label = new Date(ts * 1000)
.toLocaleDateString('en-GB', {day: '2-digit', month: 'short', timeZone: 'UTC'});
headRow.append(`<th>${label}</th>`);
});
// Single data row: "S1 or greater" label + one cell per date
const tr = $('<tr>').append('<td>S1 or greater</td>');
entries.forEach(({pct}) => {
const td = $('<td>').text(pct + '%');
td.addClass(pct < 50 ? 'bg-success-subtle' : pct < 75 ? 'bg-warning-subtle' : 'bg-danger-subtle');
tr.append(td);
});
$('#forecast-solar-storm-tbody').empty().append(tr);
}
// Render the radio blackout forecast table
function renderBlackoutForecast(r1r2Data, r3Data) {
if (!r1r2Data && !r3Data) return;
const tsSet = new Set([
...Object.keys(r1r2Data || {}),
...Object.keys(r3Data || {})
]);
const entries = [...tsSet]
.map(tsStr => ({
ts: parseFloat(tsStr),
r1r2: r1r2Data ? r1r2Data[tsStr] : undefined,
r3: r3Data ? r3Data[tsStr] : undefined
}))
.sort((a, b) => a.ts - b.ts);
// Header
const headRow = $('#forecast-blackout-head').empty().append('<th></th>');
entries.forEach(({ts}) => {
const label = new Date(ts * 1000)
.toLocaleDateString('en-GB', {day: '2-digit', month: 'short', timeZone: 'UTC'});
headRow.append(`<th>${label}</th>`);
});
// Two data rows: R1-R2 and R3+
function makeRow(rowLabel, getValue) {
const tr = $('<tr>').append(`<td>${rowLabel}</td>`);
entries.forEach(entry => {
const pct = getValue(entry);
const td = $('<td>');
if (pct !== undefined) {
td.text(pct + '%');
td.addClass(pct < 50 ? 'bg-success-subtle' : pct < 75 ? 'bg-warning-subtle' : 'bg-danger-subtle');
}
tr.append(td);
});
return tr;
}
$('#forecast-blackout-tbody').empty()
.append(makeRow('R1-R2', e => e.r1r2))
.append(makeRow('R3 or greater', e => e.r3));
}
// Populate the ionosonde station dropdown and restore any saved selection
function populateIonosondeDropdown(data) {
const select = $('#ionosonde-station');
const savedUrsi = localStorage.getItem('#ionosonde-station:value');
const savedValue = savedUrsi ? JSON.parse(savedUrsi) : null;
select.empty();
// Sort by station name rather than URSI because station name is what's displayed, and any out-of-order names might
// confuse the user
Object.values(data).sort((a, b) => a.name.localeCompare(b.name)).forEach(function (station) {
select.append($('<option>', {value: station.ursi, text: station.name}));
});
// Select one by default if the user's localStorage has an existing selection for this
if (savedValue && select.find('option[value="' + savedValue + '"]').length) {
select.val(savedValue);
}
}
// Render the foF2/MUF data and line chart for the currently selected station
function renderIonosondeData() {
// First make sure that we have some data, that a station entry is selected in the drop-down box, and that the
// data contains an entry for that station. If not, this represents an odd state (over and above just "no data for
// this station", so bail out at this point. The user will have to reselect something from the list, or wait until
// the API is behaving itself again.
if (!ionosondeData) return;
const ursi = $('#ionosonde-station').val();
if (!ursi) return;
const station = ionosondeData[ursi];
if (!station) return;
// Set up some styles, matching the k-index chart. We use Bootstrap's "primary", "danger", and "success" colours
// not for any real reason but just to get a suitable blue, red, and green that match the other colours Spothole uses
const style = getComputedStyle(document.documentElement);
const fof2Color = style.getPropertyValue('--bs-primary').trim();
const mufColor = style.getPropertyValue('--bs-success').trim();
const lufColor = style.getPropertyValue('--bs-danger').trim();
const textColor = style.getPropertyValue('--bs-body-color').trim() || '#666';
const gridColor = style.getPropertyValue('--bs-border-color').trim() || 'rgba(128,128,128,0.3)';
// Utility function to convert the dict of timestamp-to-value into just a value array in timestamp key order
function toSeries(dict) {
if (!dict) return [];
return Object.entries(dict)
.map(([tsStr, val]) => ({ts: parseFloat(tsStr), val}))
.sort((a, b) => a.ts - b.ts);
}
const fof2Entries = toSeries(station.fof2);
const mufEntries = toSeries(station.muf);
const lufEntries = toSeries(station.luf);
const allTs = [...fof2Entries, ...mufEntries, ...lufEntries].map(e => e.ts);
if (allTs.length === 0) {
$('#ionosonde-no-data').show();
$('#ionosonde-data-rows').hide();
$('#ionosonde-band-state').hide();
$('#ionosonde-chart').hide();
if (ionosondeChart) {
ionosondeChart.destroy();
ionosondeChart = null;
}
return;
}
$('#ionosonde-no-data').hide();
$('#ionosonde-data-rows').show();
// Populate latest values summary (visible on all screen sizes)
const latestFof2 = fof2Entries.length ? fof2Entries[fof2Entries.length - 1].val : null;
const latestMuf = mufEntries.length ? mufEntries[mufEntries.length - 1].val : null;
const latestLuf = lufEntries.length ? lufEntries[lufEntries.length - 1].val : null;
const minTs = allTs.length ? Math.min(...allTs) : null;
const maxTs = allTs.length ? Math.max(...allTs) : null;
if (maxTs != null) {
const latestDate = moment.utc(maxTs * 1000);
$('#ionosonde-latest-time').text(latestDate.format('DD MMM YYYY HH:mm [UTC]') + ' (' + latestDate.fromNow() + ')');
}
$('#ionosonde-latest-luf').text(latestLuf !== null ? latestLuf.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-latest-fof2').text(latestFof2 !== null ? latestFof2.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-latest-muf').text(latestMuf !== null ? latestMuf.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-stale-warning').toggle(maxTs !== null && (Date.now() / 1000 - maxTs) > 12 * 3600);
// Populate band state tables. There are actually two tables to populate, which is pretty janky, but allows us to
// display horizontally on desktop but flip it around to become a vertical list on mobile.
const bandStateClass = {'Closed': 'bg-danger-subtle', 'Short': 'bg-primary-subtle', 'Long': 'bg-success-subtle'};
const bandStates = station.band_states;
if (bandStates && Object.keys(bandStates).length > 0) {
const headRow = $('#ionosonde-band-state-head').empty();
const dataRow = $('#ionosonde-band-state-row').empty();
const vBody = $('#ionosonde-band-state-body').empty();
Object.entries(bandStates).forEach(([band, state]) => {
const cls = bandStateClass[state] || '';
headRow.append($('<th>').addClass('text-center').text(band));
dataRow.append($('<td>').addClass('text-center ' + cls).text(state));
vBody.append($('<tr>').append($('<td>').addClass('fw-bold').text(band)).append($('<td>').addClass(cls).text(state)));
});
$('#ionosonde-band-state').show();
} else {
$('#ionosonde-band-state').hide();
}
if (ionosondeChart) {
ionosondeChart.destroy();
}
// Compute tick positions at 3-hour UTC boundaries so midnight always lands on a tick, which triggers the date being
// printed, and in general looks nicer than arbitrary ticks based on min & max timestamp
const tickStep = 3 * 3600;
const tickValues = [];
tickValues.push(minTs);
for (let t = Math.ceil(minTs / tickStep) * tickStep; t <= maxTs; t += tickStep) {
tickValues.push(t);
}
tickValues.push(maxTs);
// Build time axis
const timeAxis = {
type: 'linear',
min: minTs,
max: maxTs,
title: {display: true, text: 'Time (UTC)', color: textColor},
afterBuildTicks(axis) {
axis.ticks = tickValues.map(v => ({value: v}));
},
ticks: {
color: textColor,
maxRotation: 45,
minRotation: 0,
callback(value) {
// Use the same type of display as in the k-index chart, where the labels on the axis are just HH:mm
// unless that's 00:00, in which case add the short date as well.
const dt = new Date(value * 1000);
const h = dt.getUTCHours();
const m = dt.getUTCMinutes();
const timeStr = String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0');
if (h === 0 && m === 0) {
return [timeStr, dt.toLocaleDateString('en-GB', {day: '2-digit', month: 'short', timeZone: 'UTC'})];
}
return timeStr;
},
},
grid: {color: gridColor},
};
// Build frequency axis. This is pretty normal except there's no grid, because we draw extra horizontal lines for
// the amateur radio bands which function as grid lines for the frequency axis.
const freqAxis = {
min: 0,
title: {display: true, text: 'Frequency (MHz)', color: textColor},
ticks: {color: textColor},
grid: {display: false},
};
// List of ham bands for drawing horizontal lines
const AMATEUR_BANDS = [
{label: '160m', freq: 1.8},
{label: '80m', freq: 3.5},
{label: '60m', freq: 5.3515},
{label: '40m', freq: 7.0},
{label: '30m', freq: 10.1},
{label: '20m', freq: 14.0},
{label: '17m', freq: 18.068},
{label: '15m', freq: 21.0},
{label: '12m', freq: 24.89},
{label: '10m', freq: 28.0},
];
// Build the horizontal lines for each ham band, including a label on the right-hand side.
const bandLinesPlugin = {
id: 'bandLines',
beforeDatasetsDraw(chart) {
const {ctx, chartArea, scales} = chart;
if (!scales.y) return;
ctx.save();
ctx.strokeStyle = gridColor;
ctx.lineWidth = 1;
ctx.setLineDash([]);
// Add an extra horizontal line for 30MHz, which should correspond to the top of the chart and avoid having
// no top "border" gridline
const y30 = scales.y.getPixelForValue(30);
if (y30 >= chartArea.top && y30 <= chartArea.bottom) {
ctx.beginPath();
ctx.moveTo(chartArea.left, y30);
ctx.lineTo(chartArea.right, y30);
ctx.stroke();
}
ctx.font = '10px sans-serif';
ctx.fillStyle = textColor;
// Add the ham band "grid lines"
AMATEUR_BANDS.forEach(({label, freq}) => {
const y = scales.y.getPixelForValue(freq);
if (y < chartArea.top || y > chartArea.bottom) return;
ctx.beginPath();
ctx.moveTo(chartArea.left, y);
ctx.lineTo(chartArea.right, y);
ctx.stroke();
ctx.textAlign = 'right';
ctx.textBaseline = 'bottom';
ctx.fillText(label, chartArea.right - 4, y - 2);
});
ctx.restore();
}
};
// Create the chart itself
ionosondeChart = new Chart(document.getElementById('ionosonde-chart'), {
type: 'line',
data: {
datasets: [
{
label: 'LUF',
data: lufEntries.map(e => ({x: e.ts, y: e.val})),
borderColor: lufColor,
backgroundColor: 'transparent',
pointRadius: 0,
tension: 0.2,
},
{
label: 'foF2',
data: fof2Entries.map(e => ({x: e.ts, y: e.val})),
borderColor: fof2Color,
backgroundColor: 'transparent',
pointRadius: 0,
tension: 0.2,
},
{
label: 'MUF (3000 km)',
data: mufEntries.map(e => ({x: e.ts, y: e.val})),
borderColor: mufColor,
backgroundColor: 'transparent',
pointRadius: 0,
tension: 0.2,
}
]
},
options: {
responsive: true,
aspectRatio: 3,
plugins: {
legend: {display: true, labels: {color: textColor, usePointStyle: true, pointStyle: 'line'}},
tooltip: {enabled: false}
},
scales: {x: timeAxis, y: freqAxis},
},
plugins: [bandLinesPlugin],
});
// Chart canvas is normally hidden until we get here with some definitely good data. Now we have that so show it
$('#ionosonde-chart').show();
}
// Called when the ionosonde station select changes
function ionosondeStationChanged() {
saveSettings();
renderIonosondeData();
}
// Render the DX stats table for the currently selected DE continent
function renderDxStats() {
if (!dxStatsData) {
return;
}
const deContinent = $('#dxstats-de-continent').val();
const deData = dxStatsData[deContinent];
if (!deData) {
return;
}
const cells = [];
Object.entries(deData).forEach(function ([dxContinent, bands]) {
Object.entries(bands).forEach(function ([band, count]) {
const cell = $('#dxstats-' + dxContinent + '-' + band);
cell.text(count);
cells.push({cell, count});
});
});
const counts = cells.map(function (c) {
return c.count;
});
const min = Math.min(...counts);
const max = Math.max(...counts);
const range = max - min;
cells.forEach(function ({cell, count}) {
const t = range > 0 ? (count - min) / range : 0;
const cls = t === 0 ? 'bg-danger-subtle' : t < 0.05 ? 'bg-warning-subtle' : 'bg-success-subtle';
cell.removeClass('bg-danger-subtle bg-warning-subtle bg-success-subtle').addClass(cls);
});
}
// Called when the DE continent select changes
function dxStatsContientChanged() {
saveSettings();
renderDxStats();
}
// Fetch DX stats from the API and render
function loadDxStats() {
$.getJSON('/api/v2/dxstats', function (jsonData) {
dxStatsData = jsonData;
renderDxStats();
});
}
// Startup
$(document).ready(function () {
loadSettings();
loadSolarConditions();
loadDxStats();
});
+106
View File
@@ -0,0 +1,106 @@
//
// GEOGRAPHIC UTILITY FUNCTIONS
// Great Circle calculation, Maidenhead grid calcs, etc.
//
// Calculate great circle bearing between two lat/lon points.
function calcBearing(lat1, lon1, lat2, lon2) {
lat1 *= Math.PI / 180;
lon1 *= Math.PI / 180;
lat2 *= Math.PI / 180;
lon2 *= Math.PI / 180;
const lonDelta = lon2 - lon1;
const y = Math.sin(lonDelta) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lonDelta);
let bearing = Math.atan2(y, x);
bearing = bearing * (180 / Math.PI);
if (bearing < 0) {
bearing += 360;
}
return bearing;
}
// Convert a Maidenhead grid reference of arbitrary precision to the lat/long of the centre point of the square.
// Returns null if the grid format is invalid.
function latLonForGridCentre(grid) {
let [lat, lon, latCellSize, lonCellSize] = latLonForGridSWCornerPlusSize(grid);
if (lat != null && lon != null && latCellSize != null && lonCellSize != null) {
return [lat + latCellSize / 2.0, lon + lonCellSize / 2.0];
} else {
return null;
}
}
// Convert a Maidenhead grid reference of arbitrary precision to lat/long, including in the result the size of the
// lowest grid square. This is a utility method used by the main methods that return the centre, southwest, and
// northeast coordinates of a grid square.
// The return type is always an array of size 4. The elements in it are null if the grid format is invalid.
function latLonForGridSWCornerPlusSize(grid) {
// Make sure we are in upper case so our maths works. Case is arbitrary for Maidenhead references
grid = grid.toUpperCase();
// Return null if our Maidenhead string is invalid or too short
let len = grid.length;
if (len <= 0 || (len % 2) !== 0) {
return [null, null, null, null];
}
let lat = 0.0; // aggregated latitude
let lon = 0.0; // aggregated longitude
let latCellSize = 10; // Size in degrees latitude of the current cell. Starts at 20 and gets smaller as the calculation progresses
let lonCellSize = 20; // Size in degrees longitude of the current cell. Starts at 20 and gets smaller as the calculation progresses
let latCellNo; // grid latitude cell number this time
let lonCellNo; // grid longitude cell number this time
// Iterate through blocks (two-character sections)
for (let block = 0; block * 2 < len; block += 1) {
if (block % 2 === 0) {
// Letters in this block
lonCellNo = grid.charCodeAt(block * 2) - 'A'.charCodeAt(0);
latCellNo = grid.charCodeAt(block * 2 + 1) - 'A'.charCodeAt(0);
// Bail if the values aren't in range. Allowed values are A-R (0-17) for the first letter block, or
// A-X (0-23) thereafter.
let maxCellNo = (block === 0) ? 17 : 23;
if (latCellNo < 0 || latCellNo > maxCellNo || lonCellNo < 0 || lonCellNo > maxCellNo) {
return [null, null, null, null];
}
} else {
// Numbers in this block
lonCellNo = parseInt(grid.charAt(block * 2));
latCellNo = parseInt(grid.charAt(block * 2 + 1));
// Bail if the values aren't in range 0-9..
if (latCellNo < 0 || latCellNo > 9 || lonCellNo < 0 || lonCellNo > 9) {
return [null, null, null, null];
}
}
// Aggregate the angles
lat += latCellNo * latCellSize;
lon += lonCellNo * lonCellSize;
// Reduce the cell size for the next block, unless we are on the last cell.
if (block * 2 < len - 2) {
// Still have more work to do, so reduce the cell size
if (block % 2 === 0) {
// Just dealt with letters, next block will be numbers so cells will be 1/10 the current size
latCellSize = latCellSize / 10.0;
lonCellSize = lonCellSize / 10.0;
} else {
// Just dealt with numbers, next block will be letters so cells will be 1/24 the current size
latCellSize = latCellSize / 24.0;
lonCellSize = lonCellSize / 24.0;
}
}
}
// Offset back to (-180, -90) where the grid starts
lon -= 180.0;
lat -= 90.0;
// Return nulls on maths errors
if (isNaN(lat) || isNaN(lon) || isNaN(latCellSize) || isNaN(lonCellSize)) {
return [null, null, null, null];
}
return [lat, lon, latCellSize, lonCellSize];
}
+622
View File
@@ -0,0 +1,622 @@
// Colours
const MAIDENHEAD_GRID_COLOR_LIGHT = 'rgba(200, 140, 140, 1.0)';
const CQ_ZONES_COLOR_LIGHT = 'rgba(140, 200, 140, 1.0)';
const ITU_ZONES_COLOR_LIGHT = 'rgba(200, 200, 140, 1.0)';
const WAB_WAI_GRID_COLOR_LIGHT = 'rgba(140, 140, 200, 1.0)';
const MAIDENHEAD_GRID_COLOR_DARK = 'rgba(120, 60, 60, 1.0)';
const CQ_ZONES_COLOR_DARK = 'rgba(60, 120, 60, 1.0)';
const ITU_ZONES_COLOR_DARK = 'rgba(120, 120, 60, 1.0)';
const WAB_WAI_GRID_COLOR_DARK = 'rgba(60, 60, 120, 1.0)';
// SSE connection for live spot updates
let evtSource;
let restartSSEOnErrorTimeoutId;
// Map dx_call to a pair of marker & geodesic line, so we can de-duplicate spots as they arrive and only show
// one marker per dx_call. The key here is actually dx_call + SSID if the spot gives us an SSID; this is mostly for
// if APRS spots are enabled so we can ID a home and mobile station separately rather than our marker oscillating
// between the two as updates come in.
let spotMarkers = new Map();
// Map layers
let backgroundTileLayer;
let markersLayer;
let geodesicsLayer;
let oms;
let terminator;
let maidenheadGrid;
let cqZones;
let ituZones;
let wabwaiGrid;
// Tracks the currently-loaded basemap provider string to avoid unnecessary tile reloads
let loadedBasemap;
// Tracks whether this is the first display of markers after page load
let firstLoad = true;
// Load spots and populate the map.
function loadSpots() {
// Close any existing SSE connection before fetching fresh data
if (evtSource != null) {
evtSource.close();
}
// Including QRZ/HamQTH lookups to improve positions causes the load to be really slow, so on first load
// the user would be waiting ages without data and will think it's broken. We therefore load in several
// stages:
// 1) Load without any credentials
// 2) (If we have credentials) reload with them, replacing what's already there,
// 3) Subscribe to the SSE endpoint (with credentials if we have them) so that updates come with augmented
// data if they can.
$.ajax({url: '/api/v2/spots' + buildQueryString(), dataType: 'json', headers: getCredentialHeaders(), success: function (jsonData) {
// Store data
spots = jsonData;
// Update map
updateMap();
if ($("#showTerminator")[0].checked) {
terminator.setTime();
}
// Check if we have any credentials to use
if (getCredentialQueryString() !== "") {
// OK, we have credentials and have loaded once without them so the user has a basic map. Now reload
// with the credentials and replace what's on the map, so we can improve the data.
$.getJSON('/api/v1/spots' + buildQueryString(true), function (jsonData2) {
spots = jsonData2;
updateMap();
// Now start the ongoing SSE connection
startSSEConnection();
});
} else {
// We had no credentials with which to augment the data anyway, so just start the SSE connection
// now
startSSEConnection();
}
}});
}
// Start the SSE connection to receive new spots as they arrive
function startSSEConnection() {
if (evtSource != null) {
evtSource.close();
}
// SSE is going to fetch only a few spots at a time, so now we include QRZ/HamQTH credentials because the delay won't be significant.
evtSource = new EventSource('/api/v1/spots/stream' + buildQueryString(true));
evtSource.onmessage = function (event) {
const newSpot = JSON.parse(event.data);
const key = spotKey(newSpot);
// Remove existing marker/geodesic for this callsign if present
removeSpotFromMap(key);
spots = spots.filter(s => spotKey(s) !== key);
// Skip spots with no map coordinates
if (newSpot["dx_latitude"] == null || newSpot["dx_longitude"] == null) {
return;
}
// Add to data store and map
spots.unshift(newSpot);
addSpotToMap(newSpot);
};
evtSource.onerror = function () {
if (evtSource != null) {
evtSource.close();
}
clearTimeout(restartSSEOnErrorTimeoutId);
restartSSEOnErrorTimeoutId = setTimeout(startSSEConnection, 1000);
};
}
// Remove spots from the map that are older than the selected max age.
function expireOldSpots() {
const maxAgeSeconds = parseInt($("#max-spot-age option:selected").val());
const cutoff = (Date.now() / 1000) - maxAgeSeconds;
spots = spots.filter(function (s) {
if (s["time"] && s["time"] < cutoff) {
removeSpotFromMap(spotKey(s));
return false;
}
return true;
});
}
// Returns a unique key for a spot based on its callsign and SSID. This is in case the APRS spot source is enabled and
// we want to display all SSIDs for a given callsign, not just the latest one.
function spotKey(s) {
return s["dx_call"] + (s["dx_ssid"] ? "-" + s["dx_ssid"] : "");
}
// Add a single spot's marker and geodesic to the map and to spotMarkers
function addSpotToMap(s) {
const m = L.marker([s["dx_latitude"], s["dx_longitude"]], {icon: getIcon(s)});
m.bindPopup(getTooltipText(s));
markersLayer.addLayer(m);
oms.addMarker(m);
let geodesic = null;
if ($("#mapShowGeodesics")[0].checked && s["de_latitude"] != null && s["de_longitude"] != null) {
try {
geodesic = L.geodesic([[s["de_latitude"], s["de_longitude"]], m.getLatLng()], {
color: bandToColor(s['band']),
wrap: false,
steps: 5
});
geodesicsLayer.addLayer(geodesic);
} catch (e) {
// Not sure what causes these but better to continue than to crash out
}
}
spotMarkers.set(spotKey(s), {marker: m, geodesic: geodesic});
}
// Remove a spot's marker and geodesic from the map and from spotMarkers.
function removeSpotFromMap(key) {
const entry = spotMarkers.get(key);
if (entry) {
markersLayer.removeLayer(entry.marker);
oms.removeMarker(entry.marker);
if (entry.geodesic) {
geodesicsLayer.removeLayer(entry.geodesic);
}
spotMarkers.delete(key);
}
}
// Build a query string for the API, based on the filters that the user has selected.
function buildQueryString() {
let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&";
}
});
str = str + "max_age=" + $("#max-spot-age option:selected").val();
// Additional filters for the map view: No dupes, no QRT, only spots with good locations
str = str + "&dedupe=true&allow_qrt=false";
return str;
}
// Update the spots map
function updateMap() {
// Clear existing content
markersLayer.clearLayers();
geodesicsLayer.clearLayers();
oms.clearMarkers();
spotMarkers.clear();
// Make new markers for all spots
spots.forEach(function (s) {
if (s["dx_latitude"] == null || s["dx_longitude"] == null) {
return;
}
addSpotToMap(s);
});
// On first load, zoom to the extent of the markers
if (firstLoad) {
if (markersLayer.getLayers().length >= 2) {
const group = new L.featureGroup(markersLayer.getLayers());
map.fitBounds(group.getBounds().pad(0.1));
}
firstLoad = false;
}
}
// Get an icon for a spot, based on its band, using PSK Reporter colours, its program etc.
function getIcon(s) {
return L.ExtraMarkers.icon({
icon: sigToIcon(s["sig"], "fa-tower-cell"),
iconColor: bandToContrastColor(s["band"]),
markerColor: bandToColor(s["band"]),
shape: 'circle',
prefix: 'fa',
svg: true
});
}
// Tooltip text for the markers
function getTooltipText(s) {
// Format DX call
let dx_call = s["dx_call"];
if (dx_call == null) {
dx_call = "";
}
if (s["dx_ssid"] != null) {
dx_call = dx_call + "-" + s["dx_ssid"];
}
// Format DX flag
let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
if (dx_call == null) {
dx_flag = "";
}
if (s["dx_flag"] && s["dx_flag"] != null && s["dx_flag"] !== "") {
dx_flag = s["dx_flag"];
}
// Format the frequency
let freq_string = "Unknown";
if (s["freq"] != null) {
const mhz = Math.floor(s["freq"] / 1000000.0);
const khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0);
const hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0));
const hz_string = (hz > 0) ? hz.toFixed(0)[0] : "";
freq_string = `<span class='freq-mhz freq-mhz-pad'>${mhz.toFixed(0)}</span><span class='freq-khz'>${khz.toFixed(0).padStart(3, '0')}</span><span class='freq-hz hideonmobile'>${hz_string}</span>`
}
// Format comment
let commentText = "";
if (s["comment"] != null) {
commentText = escapeHtml(s["comment"]);
}
// Sig or fallback to source
let sigSourceText = s["source"];
if (s["sig"]) {
sigSourceText = s["sig"];
}
// Format sig_refs
let sig_refs = "";
if (s["sig_refs"] != null) {
const items = [];
for (let i = 0; i < s["sig_refs"].length; i++) {
if (s["sig_refs"][i]["url"] != null) {
items[i] = `<a href='${s["sig_refs"][i]["url"]}' title='${s["sig_refs"][i]["name"]}' target='_new' class='sig-ref-link'>${s["sig_refs"][i]["id"]}</a>`
} else {
items[i] = `${s["sig_refs"][i]["id"]}`
}
}
sig_refs = items.join(", ");
}
// DX
let ttt = `<span class='nowrap'><span class='icon-wrapper'>${dx_flag}</span> <a href='https://www.qrz.com/db/${dx_call}' target='_blank' class="dx-link">${dx_call}</a></span><br/>`;
// Frequency & band
ttt += `<span class='icon-wrapper'><i class='fa-solid fa-radio markerPopupIcon'></i></span>&nbsp;${freq_string}`;
if (s["band"] != null) {
ttt += ` (${s["band"]})`;
}
// Mode
if (s["mode"] != null) {
ttt += ` &nbsp;&nbsp; <i class='fa-solid fa-wave-square markerPopupIcon'></i>&nbsp;${s["mode"]}`;
}
ttt += "<br/>";
// Source / SIG / Ref
ttt += `<span class='nowrap'><span class='icon-wrapper'><i class='fa-solid ${sigToIcon(s["sig"], "fa-tower-cell")}'></i></span>&nbsp;${sigSourceText} ${sig_refs}</span><br/>`;
// Time
ttt += `<span class='icon-wrapper'><i class='fa-solid fa-clock markerPopupIcon'></i></span>&nbsp;${moment.unix(s["time"]).fromNow()}`;
// Comment
if (commentText.length > 0) {
ttt += `<br/><span class='icon-wrapper'><i class='fa-solid fa-comment markerPopupIcon'></i></span> ${commentText}`;
}
return ttt;
}
// Load server options. Once a successful callback is made from this, we then query spots and set up the timer to query
// spots repeatedly.
function loadOptions() {
$.getJSON('/api/v2/options', function (jsonData) {
// Store options
options = jsonData;
// First pass loading settings, so we can load the band colour scheme before the filters that need to use it
loadSettings();
setColorScheme($("#color-scheme option:selected").val());
setBandColorScheme($("#band-color-scheme option:selected").val());
// Add CSS for band toggle buttons
addBandToggleColourCSS(options["bands"]);
// Populate the filters panel
generateBandsMultiToggleFilterCard(options["bands"]);
generateSIGsMultiToggleFilterCard(options["sigs"]);
generateMultiToggleFilterCard("#dx-continent-options", "dx_continent", options["continents"]);
generateMultiToggleFilterCard("#de-continent-options", "de_continent", options["continents"]);
generateModesMultiToggleFilterCard(options["modes"]);
generateSourcesMultiToggleFilterCard(options["spot_sources"], spotProvidersEnabledByDefault);
// Load URL params. These may select things from the various filter & display options, so the function needs
// to be called after these are set up, but if the URL params ask for "embedded mode", this will suppress
// loading settings, so this needs to be called before that.
loadURLParams();
loadMapURLParams();
// Load settings from settings storage now all the controls are available
loadSettings();
// If no basemap has been explicitly saved and the UI is in dark mode, default to dark Mapnik
if (localStorage.getItem("#basemap:value") === null) {
if (document.documentElement.getAttribute("data-bs-theme") === "dark") {
$("#basemap").val("OpenStreetMap.Mapnik.Dark");
}
}
// Apply basemap and overlay settings now that controls have their saved values
setBasemap($("#basemap").val());
setBasemapOpacity(parseFloat($("#basemapOpacity").val()));
enableTerminator($("#showTerminator")[0].checked);
enableMaidenheadGrid($("#showMaidenheadGrid")[0].checked);
enableCQZones($("#showCQZones")[0].checked);
enableITUZones($("#showITUZones")[0].checked);
enableWABWAIGrid($("#showWABWAIGrid")[0].checked);
// Load spots and start SSE for live updates
loadSpots();
// Set up spot expiry checker
setInterval(expireOldSpots, 60 * 1000);
});
}
// Method called when any display property is changed to reload the map and persist the display settings.
function displayUpdated() {
updateMap();
setBasemap($("#basemap").val());
setBasemapOpacity(parseFloat($("#basemapOpacity").val()));
enableTerminator($("#showTerminator")[0].checked);
enableMaidenheadGrid($("#showMaidenheadGrid")[0].checked);
enableCQZones($("#showCQZones")[0].checked);
enableITUZones($("#showITUZones")[0].checked);
enableWABWAIGrid($("#showWABWAIGrid")[0].checked);
saveSettings();
}
// Set the basemap
function setBasemap(basemapname) {
// Only change if we have to, to avoid a flash of reloading content
if (loadedBasemap !== basemapname) {
loadedBasemap = basemapname;
if (typeof backgroundTileLayer !== 'undefined') {
map.removeLayer(backgroundTileLayer);
}
// OpenStreetMap.Mapnik.Dark is a synthetic variant that uses Mapnik tiles with a CSS filter applied
const providerName = basemapname === "OpenStreetMap.Mapnik.Dark" ? "OpenStreetMap.Mapnik" : basemapname;
backgroundTileLayer = L.tileLayer.provider(providerName, {
opacity: parseFloat($("#basemapOpacity").val()),
edgeBufferTiles: 1
});
backgroundTileLayer.addTo(map);
backgroundTileLayer.bringToBack();
if (basemapname === "OpenStreetMap.Mapnik.Dark") {
const container = backgroundTileLayer.getContainer();
if (container) {
container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)';
}
}
// Identify dark basemaps to ensure we use white text for unselected icons
// and change the background colour appropriately
const basemapIsDark = basemapname === "CartoDB.DarkMatter" || basemapname === "Esri.WorldImagery" || basemapname === "OpenStreetMap.Mapnik.Dark";
$("#map").css('background-color', basemapIsDark ? "black" : "white");
// Change the colour of the grid and zone overlays to match
if (basemapIsDark) {
maidenheadGrid.options.color = MAIDENHEAD_GRID_COLOR_DARK;
cqZones.options.color = CQ_ZONES_COLOR_DARK;
ituZones.options.color = ITU_ZONES_COLOR_DARK;
wabwaiGrid.options.color = WAB_WAI_GRID_COLOR_DARK;
} else {
maidenheadGrid.options.color = MAIDENHEAD_GRID_COLOR_LIGHT;
cqZones.options.color = CQ_ZONES_COLOR_LIGHT;
ituZones.options.color = ITU_ZONES_COLOR_LIGHT;
wabwaiGrid.options.color = WAB_WAI_GRID_COLOR_LIGHT;
}
// Force regenerate overlays in the new colours
map.removeLayer(maidenheadGrid);
map.removeLayer(cqZones);
map.removeLayer(ituZones);
map.removeLayer(wabwaiGrid);
enableMaidenheadGrid($("#showMaidenheadGrid")[0].checked);
enableCQZones($("#showCQZones")[0].checked);
enableITUZones($("#showITUZones")[0].checked);
enableWABWAIGrid($("#showWABWAIGrid")[0].checked);
}
}
// Set the basemap opacity
function setBasemapOpacity(opacity) {
if (typeof backgroundTileLayer !== 'undefined') {
backgroundTileLayer.setOpacity(opacity);
}
}
// Shows/hides the terminator/greyline overlay
function enableTerminator(show) {
if (show) {
terminator.setTime();
terminator.addTo(map);
} else {
map.removeLayer(terminator);
}
}
// Shows/hides the Maidenhead grid overlay
function enableMaidenheadGrid(show) {
if (show) {
maidenheadGrid.addTo(map);
backgroundTileLayer.bringToBack();
} else {
map.removeLayer(maidenheadGrid);
}
}
// Shows/hides the CQ zone overlay
function enableCQZones(show) {
if (show) {
cqZones.addTo(map);
backgroundTileLayer.bringToBack();
} else {
map.removeLayer(cqZones);
}
}
// Shows/hides the ITU zone overlay
function enableITUZones(show) {
if (show) {
ituZones.addTo(map);
backgroundTileLayer.bringToBack();
} else {
map.removeLayer(ituZones);
}
}
// Shows/hides the WAB/WAI grid overlay
function enableWABWAIGrid(show) {
if (show) {
wabwaiGrid.addTo(map);
backgroundTileLayer.bringToBack();
} else {
map.removeLayer(wabwaiGrid);
}
}
// Load map-specific URL parameters for center position and zoom level.
// These set Leaflet state directly rather than form controls, so they live here rather than in loadURLParams().
// If any parameter is applied, firstLoad is set to false so updateMap() does not override the position.
function loadMapURLParams() {
let params = new URLSearchParams(document.location.search);
let lat = parseFloat(params.get("map-center-lat"));
let lon = parseFloat(params.get("map-center-lon"));
let zoom = parseFloat(params.get("map-zoom"));
let hasLatLon = !isNaN(lat) && !isNaN(lon);
let hasZoom = !isNaN(zoom);
if (hasLatLon || hasZoom) {
if (hasLatLon && hasZoom) {
map.setView([lat, lon], zoom);
} else if (hasLatLon) {
map.setView([lat, lon], map.getZoom());
} else {
map.setZoom(zoom);
}
firstLoad = false;
}
}
// Set up the map
function setUpMap() {
// Create map
map = L.map('map', {
zoomControl: false,
minZoom: 2,
maxZoom: 12
});
// Add basemap
loadedBasemap = $("#basemap").val();
const initialProviderName = loadedBasemap === "OpenStreetMap.Mapnik.Dark" ? "OpenStreetMap.Mapnik" : loadedBasemap;
backgroundTileLayer = L.tileLayer.provider(initialProviderName, {
opacity: parseFloat($("#basemapOpacity").val()),
edgeBufferTiles: 1
});
backgroundTileLayer.addTo(map);
backgroundTileLayer.bringToBack();
if (loadedBasemap === "OpenStreetMap.Mapnik.Dark") {
const container = backgroundTileLayer.getContainer();
if (container) {
container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)';
}
}
// Add marker layer
markersLayer = new L.LayerGroup();
markersLayer.addTo(map);
// Set up spiderfy for overlapping markers
oms = new OverlappingMarkerSpiderfier(map, {keepSpiderfied: true});
oms.addListener('click', function (marker) {
marker.openPopup();
});
// Add geodesic layer
geodesicsLayer = new L.LayerGroup();
geodesicsLayer.addTo(map);
// Add terminator/greyline (toggleable)
terminator = L.terminator({
interactive: false
});
terminator.setStyle({fillColor: '#00000050'});
if ($("#showTerminator")[0].checked) {
terminator.addTo(map);
}
// Add Maidenhead grid (toggleable)
maidenheadGrid = L.maidenhead({
color: MAIDENHEAD_GRID_COLOR_LIGHT
});
if ($("#showMaidenheadGrid")[0].checked) {
maidenheadGrid.addTo(map);
backgroundTileLayer.bringToBack();
}
// Add CQ zone layer (toggleable)
cqZones = L.cqzones({
color: CQ_ZONES_COLOR_LIGHT
});
if ($("#showCQZones")[0].checked) {
cqZones.addTo(map);
backgroundTileLayer.bringToBack();
}
// Add ITU zone layer (toggleable)
ituZones = L.ituzones({
color: ITU_ZONES_COLOR_LIGHT
});
if ($("#showITUZones")[0].checked) {
ituZones.addTo(map);
backgroundTileLayer.bringToBack();
}
// Add WAB/WAI grid layer (toggleable)
wabwaiGrid = L.workedAllBritainIreland({
color: WAB_WAI_GRID_COLOR_LIGHT
});
if ($("#showWABWAIGrid")[0].checked) {
wabwaiGrid.addTo(map);
backgroundTileLayer.bringToBack();
}
// Display a default view. This will only last until the spots are first loaded, at which point the map will zoom
// to the extent of ths spots.
map.setView([30, 0], 3);
}
// Display the intro box, unless the user has already dismissed it once.
function displayIntroBox() {
if (localStorage.getItem("map-intro-box-dismissed") == null) {
$("#map-intro-box").show();
}
$("#map-intro-box-dismiss").click(function () {
localStorage.setItem("map-intro-box-dismissed", true);
});
}
// Startup
$(document).ready(function () {
// Close SSE connection cleanly when navigating away
window.addEventListener('beforeunload', function () {
if (evtSource != null) {
evtSource.close();
}
});
// Hide the extra things that need to be hidden on this page
$(".hideonmap").hide();
// Set up map
setUpMap();
// Call loadOptions(), this will then trigger loading spots and setting up timers.
loadOptions();
// Display intro box
displayIntroBox();
// Prevent mouse scroll and touch actions in the popup menus being passed through to the map
L.DomEvent.disableScrollPropagation(document.getElementById('settingsButtonRowMap'));
L.DomEvent.disableClickPropagation(document.getElementById('settingsButtonRowMap'));
});
+530
View File
@@ -0,0 +1,530 @@
// SSE event source
let evtSource;
let restartSSEOnErrorTimeoutId;
// Table row count, to alternate shading
let rowCount = 0;
// Set up a listener to close the SSE connection nicely when we navigate away from the page, to prevent console errors
// and keep things nice and tidy for the server.
window.addEventListener('beforeunload', function () {
if (evtSource != null) {
evtSource.close();
}
});
// Load spots and populate the table.
function loadSpots() {
// If we have an ongoing SSE connection, stop it so it doesn't interfere with our reload
if (evtSource != null) {
evtSource.close();
}
// Make the new query
$.ajax({url: '/api/v2/spots' + buildQueryString(), dataType: 'json', headers: getCredentialHeaders(), success: function (jsonData) {
// Store data
spots = jsonData;
// Update table
updateTable();
// Start SSE connection to fetch updates in the background, if we are in "run" mode
let run = $('#runButton:checked').val();
if (run) {
startSSEConnection();
}
}});
}
// Start an SSE connection (closing an existing one if it exists). This will then be used to add to the table on the
// fly.
function startSSEConnection() {
if (evtSource != null) {
evtSource.close();
}
evtSource = new EventSource('/api/v2/spots/stream' + buildQueryString());
evtSource.onmessage = function (event) {
// Get the new spot
const newSpot = JSON.parse(event.data);
// Awful fudge to ensure new incoming spots at the top of the list don't have timestamps that make them look
// like they belong further down the list. If the spot is older than the latest one we already have, bump its
// time up to match it. This isn't great but since we poll spot providers every 2 minutes anyway, it shouldn't
// be too far wrong.
if (spots.length > 0) {
newSpot["time"] = Math.max(newSpot["time"], Math.max(...spots.map(s => s["time"])))
}
// Add spot to internal data store
spots.unshift(newSpot);
// Work out if we need to remove an old spot
if (spots.length > $("#spots-to-fetch option:selected").val()) {
spots = spots.slice(0, -1);
// Drop oldest spot off the end of the table. This is two rows because of the mobile view extra rows
$("#table tbody tr").last().remove();
$("#table tbody tr").last().remove();
}
// If we had zero spots before (i.e. one now), the table will have a "No spots" row that we need to remove now
// that we have one.
if (spots.length === 1) {
$("#table tbody tr").last().remove();
}
// Add the new spot to table
addSpotToTopOfTable(newSpot, true);
// Ping if we need to
if ($("#pingOnNewSpots")[0].checked) {
new Audio("/audio/ping.mp3").play();
}
};
evtSource.onerror = function () {
if (evtSource != null) {
evtSource.close();
}
clearTimeout(restartSSEOnErrorTimeoutId)
restartSSEOnErrorTimeoutId = setTimeout(startSSEConnection, 1000);
};
}
// Build a query string for the API, based on the filters that the user has selected.
function buildQueryString() {
let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&";
}
});
str = str + "limit=" + $("#spots-to-fetch option:selected").val();
if ($("#search").val() !== "") {
str = str + "&text_includes=" + encodeURIComponent($("#search").val());
}
return str;
}
// Update the spots table
function updateTable() {
// Use local time instead of UTC?
const useLocalTime = $("#timeZone")[0].value === "local";
// Get user grid if valid, this will be null if it's not.
const userPos = latLonForGridCentre($("#userGrid").val());
// Table data toggles
const showTime = $("#tableShowTime")[0].checked;
const showDX = $("#tableShowDX")[0].checked;
const showFreq = $("#tableShowFreq")[0].checked;
const showMode = $("#tableShowMode")[0].checked;
const showComment = $("#tableShowComment")[0].checked;
const showBearing = $("#tableShowBearing")[0].checked && userPos != null;
const showType = $("#tableShowType")[0].checked;
const showRef = $("#tableShowRef")[0].checked;
const showDE = $("#tableShowDE")[0].checked;
const showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked;
// Populate table with headers
let table = $("#table");
table.find('thead tr').empty();
if (showTime) {
table.find('thead tr').append(`<th class="bg-primary-subtle">${useLocalTime ? "Local" : "UTC"}</th>`);
}
if (showDX) {
table.find('thead tr').append(`<th class="bg-primary-subtle">DX</th>`);
}
if (showFreq) {
table.find('thead tr').append(`<th class="bg-primary-subtle">Freq<span class='bg-primary-subtle hideonmobile'>uency</span></th>`);
}
if (showMode) {
table.find('thead tr').append(`<th class="bg-primary-subtle">Mode</th>`);
}
if (showComment) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Comment</th>`);
}
if (showBearing) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Bearing</th>`);
}
if (showType) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Type</th>`);
}
if (showRef) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>Ref.</th>`);
}
if (showDE) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'>DE</th>`);
}
if (showWorkedCheckbox) {
table.find('thead tr').append(`<th class='bg-primary-subtle hideonmobile'></th>`);
}
table.find('tbody').empty();
if (spots.length === 0) {
table.find('tbody').append('<tr class="bg-danger-subtle"><td colspan="100" style="text-align:center;">No spots match your filters.</td></tr>');
}
// We are regenerating the entire table not just adding a new row, so reset the row counter
rowCount = 0;
let spotsNewestFirst = spots.toReversed();
spotsNewestFirst.forEach(s => addSpotToTopOfTable(s, false));
}
// Add rows corresponding to a new spot to the top of the table
// highlightNew = false for an initial load, true for new SSE-loaded spots
function addSpotToTopOfTable(s, highlightNew) {
let rows = createNewTableRowsForSpot(s, highlightNew);
$("#table").find('tbody').prepend(rows[1]);
$("#table").find('tbody').prepend(rows[0]);
}
// Turn a spot into a set of table rows to represent it. This is actually two table rows because we need a second
// separate row for the mobile view.
// highlightNew = false for an initial load, true for new SSE-loaded spots
function createNewTableRowsForSpot(s, highlightNew) {
// Use local time instead of UTC?
const useLocalTime = $("#timeZone")[0].value === "local";
// Get user grid if valid, this will be null if it's not.
const userPos = latLonForGridCentre($("#userGrid").val());
// Table data toggles
const showTime = $("#tableShowTime")[0].checked;
const showDX = $("#tableShowDX")[0].checked;
const showFreq = $("#tableShowFreq")[0].checked;
const showMode = $("#tableShowMode")[0].checked;
const showComment = $("#tableShowComment")[0].checked;
const showBearing = $("#tableShowBearing")[0].checked && userPos != null;
const showType = $("#tableShowType")[0].checked;
const showRef = $("#tableShowRef")[0].checked;
const showDE = $("#tableShowDE")[0].checked;
const showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked;
// Create row
let $tr = $('<tr>');
// Apply striping to the table. We can't just use Bootstrap's table-striped class because we have all sorts of
// extra faff to deal with, like the mobile view having extra rows, and the On Now / Next 24h / Later banners
// which cause the table-striped colouring to go awry.
if (rowCount % 2 === 1) {
$tr.addClass("table-active");
}
// Show faded out if QRT or already worked
let alreadyWorkedThis = alreadyWorked(s["dx_call"], s["band"], s["mode"]);
if (s["qrt"] === true || alreadyWorkedThis) {
$tr.addClass("table-faded");
}
// If we are asked to highlight new rows (i.e. this row is being added "live" via the SSE client and not as a bulk
// reload of the whole table)
if (highlightNew) {
$tr.addClass("new");
}
// Format a UTC or local time for display
const time = moment.unix(s["time"]).utc();
if (useLocalTime) {
time.local();
}
const time_formatted = time.format("HH:mm");
// Format DX call
let dx_call = s["dx_call"];
if (dx_call == null) {
dx_call = "";
}
if (s["dx_ssid"] != null) {
dx_call = dx_call + "-" + s["dx_ssid"];
}
// Format dx country
let dx_country = s["dx_country"];
if (dx_country == null) {
dx_country = "Unknown or not a country";
}
// Format DX flag
let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
if (dx_call == null) {
dx_flag = "";
}
if (s["dx_dxcc_id"] && s["dx_dxcc_id"] != null && s["dx_dxcc_id"] !== 0) {
dx_flag = `<img src="static/img/flags/${s['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`;
}
// Format the frequency
let freq_string = "Unknown";
if (s["freq"] != null) {
const mhz = Math.floor(s["freq"] / 1000000.0);
const khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0);
const hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0));
const hz_string = (hz > 0) ? hz.toFixed(0)[0] : "";
freq_string = `<span class='freq-mhz freq-mhz-pad'>${mhz.toFixed(0)}</span><span class='freq-khz'>${khz.toFixed(0).padStart(3, '0')}</span><span class='freq-hz hideonmobile'>${hz_string}</span>`
}
// Format the mode
let mode_string = s["mode"];
if (s["mode"] == null) {
mode_string = "";
} else if (s["mode_source"] === "BANDPLAN") {
mode_string = mode_string + "<span class='mode-q hideonmobile'><i class='fa-solid fa-circle-question' title='The mode was not reported via the spotting service. This is a guess based on the frequency.'></i></span>";
}
// Format comment
let commentText = "";
if (s["comment"] != null) {
commentText = escapeHtml(s["comment"]);
}
// Format bearing text
let bearingText = "---<span class='bearing-q hideonmobile'><i class='fa-solid fa-circle-question' title='The position was not reported via the spotting service, and we could not determine one. A bearing to this DX is not available.'></i></span>";
if (userPos != null && s["dx_latitude"] != null && s["dx_longitude"] != null) {
const bearing = calcBearing(userPos[0], userPos[1], s["dx_latitude"], s["dx_longitude"]);
bearingText = bearing.toFixed(0).padStart(3, '0') + "°";
if (s["dx_location_good"] == null || s["dx_location_good"] === false) {
if (s["dx_location_source"] === "HOME QTH") {
bearingText = bearingText + "<span class='bearing-q hideonmobile'><i class='fa-solid fa-circle-question' title='The position was not reported via the spotting service. We had to fall back to a QRZ \"home\" location for a portable/mobile/alternative spot, so this bearing may not be accurate if the DX is close to you..'></i></span>";
} else {
bearingText = bearingText + "<span class='bearing-q hideonmobile'><i class='fa-solid fa-circle-question' title='The position was not reported via the spotting service. We had to fall back to just using the centre of a DXCC entity, so this bearing may not be accurate if the DX is close to you.'></i></span>";
}
}
}
// Format "type" (Sig or fallback to source)
let typeText = s["source"];
if (s["sig"]) {
typeText = s["sig"];
}
// Format sig_refs
let sig_refs = "";
if (s["sig_refs"] != null) {
const items = [];
for (let i = 0; i < s["sig_refs"].length; i++) {
if (s["sig_refs"][i]["url"] != null) {
items[i] = `<span style="white-space: nowrap;"><a href='${encodeURI(s["sig_refs"][i]["url"])}' title='${escapeHtml(s["sig_refs"][i]["name"])}' target='_new' class='sig-ref-link'>${escapeHtml(s["sig_refs"][i]["id"])}</a></span>`
} else {
items[i] = `<span style="white-space: nowrap;">${escapeHtml(s["sig_refs"][i]["id"])}</span>`
}
}
sig_refs = items.join(", ");
}
// Format de country
let de_country = s["de_country"];
if (de_country == null) {
de_country = "Unknown or not a country";
}
// Format DE flag
let de_flag = "<i class='fa-solid fa-circle-question'></i>";
if (s["de_dxcc_id"] && s["de_dxcc_id"] != null && s["de_dxcc_id"] !== 0) {
de_flag = `<img src="static/img/flags/${s['de_dxcc_id']}.png" class="flag" width="24" alt="${de_country}" title="${de_country}"/>`;
}
// Format de call
let de_call = s["de_call"];
if (de_call == null) {
de_call = "";
de_flag = "";
}
if (s["de_ssid"] != null) {
de_call = de_call + "-" + s["de_ssid"];
}
// Format band name
const bandFullName = s['band'] ? s['band'] + " band" : "Unknown band";
// Format "worked" checkbox
const workedCheckbox = `<input type="checkbox" ${alreadyWorkedThis ? "checked" : ""} onClick="setWorkedState('${s['dx_call']}', '${s['band']}', '${s['mode']}', ${alreadyWorkedThis ? "false" : "true"});" title="Check this box to record that you have worked this callsign on their current band and mode.">`;
// Populate the row
if (showTime) {
$tr.append(`<td class='nowrap'>${time_formatted}</td>`);
}
if (showDX) {
$tr.append(`<td class='nowrap'><span class='flag-wrapper' title='${dx_country}'>${dx_flag}</span><a class='dx-link' href='https://qrz.com/db/${s["dx_call"]}' target='_new' title='${s["dx_name"] != null ? s["dx_name"] : ""}'>${dx_call}</a></td>`);
}
if (showFreq) {
$tr.append(`<td class='nowrap'><span class='band-bullet' title='${bandFullName}' style='${(s["freq"] != null) ? "color: " + bandToColor(s["band"]) : "display: none;"}'>&#9632;</span>${freq_string}</td>`);
}
if (showMode) {
$tr.append(`<td class='nowrap'>${mode_string}</td>`);
}
if (showComment) {
$tr.append(`<td class='hideonmobile'>${commentText}</td>`);
}
if (showBearing) {
$tr.append(`<td class='nowrap hideonmobile'>${bearingText}</td>`);
}
if (showType) {
$tr.append(`<td class='nowrap hideonmobile'><span class='icon-wrapper'><i class='fa-solid ${sigToIcon(s["sig"], "fa-tower-cell")}'></i></span> ${typeText}</td>`);
}
if (showRef) {
$tr.append(`<td class='hideonmobile' style='max-width: 11em;'>${sig_refs}</td>`);
}
if (showDE) {
$tr.append(`<td class='nowrap hideonmobile'><span class='flag-wrapper' title='${de_country}'>${de_flag}</span>${de_call}</td>`);
}
if (showWorkedCheckbox) {
$tr.append(`<td class='nowrap hideonmobile'>${workedCheckbox}</td>`);
}
// Second row for mobile view only, containing type, ref & comment
const $tr2 = $("<tr class='hidenotonmobile'>");
// Apply styles as per the first row
if (rowCount % 2 === 1) {
$tr2.addClass("table-active");
}
if (s["qrt"] === true || alreadyWorkedThis) {
$tr2.addClass("table-faded");
}
if (highlightNew) {
$tr2.addClass("new");
}
const $td2 = $("<td colspan='100'>");
const $td2floatleft = $(`<div style="float: left;">`);
if (showType) {
$td2floatleft.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(s["sig"], "fa-tower-cell")}'></i></span> ${typeText} `);
}
if (showRef) {
$td2floatleft.append(`${sig_refs} `);
}
$td2.append($td2floatleft);
const $td2floatright = $(`<div style="float: right;">`);
if (showBearing) {
$td2floatright.append(`${bearingText} &nbsp;`);
}
if (showDE) {
$td2floatright.append(` de ${de_call} &nbsp;`);
}
if (showWorkedCheckbox) {
$td2floatright.append(` ${workedCheckbox} &nbsp;`);
}
$td2.append($td2floatright);
$td2.append(`</div><div style="clear: both;"></div>`);
if (showComment) {
$td2.append(`${commentText}`);
}
$tr2.append($td2);
rowCount++;
return [$tr, $tr2];
}
// Load server options. Once a successful callback is made from this, we then query spots and set up the timer to query
// spots repeatedly.
function loadOptions() {
$.getJSON('/api/v2/options', function (jsonData) {
// Store options
options = jsonData;
// First pass loading settings, so we can load the band colour scheme before the filters that need to use it
loadSettings();
setColorScheme($("#color-scheme option:selected").val());
setBandColorScheme($("#band-color-scheme option:selected").val());
// Add CSS for band toggle buttons
addBandToggleColourCSS(options["bands"]);
// Populate the filters panel
generateBandsMultiToggleFilterCard(options["bands"]);
generateSIGsMultiToggleFilterCard(options["sigs"]);
generateMultiToggleFilterCard("#dx-continent-options", "dx_continent", options["continents"]);
generateMultiToggleFilterCard("#de-continent-options", "de_continent", options["continents"]);
generateModesMultiToggleFilterCard(options["modes"]);
generateSourcesMultiToggleFilterCard(options["spot_sources"], spotProvidersEnabledByDefault);
// Load URL params. These may select things from the various filter & display options, so the function needs
// to be called after these are set up, but if the URL params ask for "embedded mode", this will suppress
// loading settings, so this needs to be called before that.
loadURLParams();
// Load settings from settings storage now all the controls are available
loadSettings();
// Extra setting - the toggle for the "bearing" column is disabled if the user has not entered a valid grid, and
// normally this logic is handled on user input to the grid field, but we might have just loaded a value direct
// into the field, so apply the same logic here.
$("#tableShowBearing").prop('disabled', !isUserGridValid());
if (!isUserGridValid()) {
$("#tableShowBearing").prop('checked', false);
}
// Load spots (this will also set up the SSE connection to update them too)
loadSpots();
});
}
// Work out if the user's entered grid is a valid Maidenhead grid
function isUserGridValid() {
const userGrid = $("#userGrid").val().toUpperCase();
return latLonForGridCentre(userGrid) != null;
}
// Method called when the user's grid input is changed.
function userGridUpdated() {
const userGridValid = isUserGridValid();
if (userGridValid) {
updateTable();
}
// Enable/disable bearing column depending on grid validity
$("#tableShowBearing").prop('disabled', !userGridValid);
if (!userGridValid) {
$("#tableShowBearing").prop('checked', false);
}
// Save settings even if not a valid grid, this allows the user to clear their grid and have it save.
saveSettings();
}
// Display the intro box, unless the user has already dismissed it once.
function displayIntroBox() {
if (localStorage.getItem("intro-box-dismissed") == null) {
$("#intro-box").show();
}
$("#intro-box-dismiss").click(function () {
localStorage.setItem("intro-box-dismissed", true);
});
}
// Mark a callsign-band-mode combination as worked (or unmark it). Persist this to localStorage.
function setWorkedState(callsign, band, mode, nowWorked) {
let combo = callsign + "-" + band + "-" + mode;
if (nowWorked && !worked.includes(combo)) {
worked.push(combo);
updateTable();
localStorage.setItem("worked", JSON.stringify(worked));
} else if (!nowWorked && worked.includes(combo)) {
worked.splice(worked.indexOf(combo), 1);
updateTable();
localStorage.setItem("worked", JSON.stringify(worked));
}
}
// Clear the list of worked calls
function clearWorked() {
worked = [];
updateTable();
localStorage.setItem("worked", JSON.stringify(worked));
}
// Startup
$(document).ready(function () {
// Call loadOptions(), this will then trigger loading spots and setting up timers.
loadOptions();
// Display intro box
displayIntroBox();
// Set up run/pause toggles
$("#runButton").change(function () {
// Need to start the SSE connection but also do a full re-query to catch up anything that we missed, so we
// might as well just call loadSpots again which will trigger it all
loadSpots();
});
$("#pauseButton").change(function () {
// If we are pausing and have an open SSE connection, stop it
if (evtSource != null) {
evtSource.close();
}
});
});
+131
View File
@@ -0,0 +1,131 @@
// Storage for the spot data that the server gives us.
let spots = [];
// List of people the user has worked. Each entry has the format callsign-band-mode. These can be added to the list by
// ticking the checkbox on a row of the table, and cleared from the Display menu. Where a row would be added to the
// table and the callsign-band-mode is in this list, it is shown struck through as already worked. This is persisted
// to localStorage.
let worked = []
// Dynamically add CSS code for the band checkboxes to show in the appropriate colour.
// Some band names contain decimal points which are not allowed in CSS classes, so we text-replace them to "p".
function addBandToggleColourCSS(band_options) {
const $style = $('<style>');
band_options.forEach(o => {
const domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, "");
$style.append(`#filter-button-label-band-${domSafeName} { padding-left: 0.3em; border-left: 5px solid ${bandToColor(o['name'])};}`);
});
$('html > head').append($style);
}
// Generate bands filter card. This one is a special case.
function generateBandsMultiToggleFilterCard(band_options) {
const $grid = $('<div class="row row-cols-3 row-cols-md-2 row-cols-lg-3 row-cols-xxl-4 g-1 mb-1">');
band_options.forEach(o => {
const domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, "");
$grid.append(`<div class="col"><div class="form-check"><input type="checkbox" class="form-check-input filter-button-band storeable-checkbox" id="filter-button-band-${domSafeName}" value="${o['name']}" autocomplete="off" onClick="filtersUpdated()" checked> <label class="form-check-label" id="filter-button-label-band-${domSafeName}" for="filter-button-band-${domSafeName}">${o['name']}</label></div></div>`);
});
$("#band-options").append($grid);
$("#band-options").append(`<div class="mt-1"><a href="#" onclick="toggleFilterButtons('band', true); return false;">All</a> &nbsp; <a href="#" onclick="toggleFilterButtons('band', false); return false;">None</a> &nbsp; <a href="#" onclick="setHamHFBandToggles(); return false;">Ham HF only</a></div>`);
}
// Set the band toggles so that only the amateur radio HF bands are selected. This includes 160m and 6m because that's
// widely expected by hams to be included. Special case of toggleFilterButtons().
function setHamHFBandToggles() {
const hamHFBands = ["160m", "80m", "60m", "40m", "30m", "20m", "17m", "15m", "12m", "10m", "6m"];
$(".filter-button-band").each(function () {
$(this).prop('checked', hamHFBands.includes($(this).val().replace("filter-button-band-", "")));
});
filtersUpdated();
}
// Generate SIGs filter card. This one is also a special case.
function generateSIGsMultiToggleFilterCard(sig_options) {
const $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">');
sig_options.forEach(o => {
const domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, "");
$grid.append(`<div class="col"><div class="form-check"><input type="checkbox" class="form-check-input filter-button-sig storeable-checkbox" id="filter-button-sig-${domSafeName}" value="${o['name']}" autocomplete="off" onClick="filtersUpdated()" checked><label class="form-check-label" id="filter-button-label-sig-${domSafeName}" for="filter-button-sig-${domSafeName}" title="${o['description']}"><i class="fa-solid ${sigToIcon(o['name'], 'fa-tower-cell')}"></i> ${o['name']}</label></div></div>`);
});
// Bonus "NO_SIG" / "General DX" option
$grid.append(`<div class="w-100"><div class="form-check"><input type="checkbox" class="form-check-input filter-button-sig storeable-checkbox" id="filter-button-sig-NO_SIG" value="NO_SIG" autocomplete="off" onClick="filtersUpdated()" checked><label class="form-check-label" id="filter-button-label-sig-NO_SIG" for="filter-button-sig-NO_SIG"><i class="fa-solid fa-tower-cell"></i> General DX</label></div></div>`);
$("#sig-options").append($grid);
$("#sig-options").append(`<div class="mt-1"><a href="#" onclick="toggleFilterButtons('sig', true); return false;">All</a> &nbsp; <a href="#" onclick="toggleFilterButtons('sig', false); return false;">None</a></div>`);
}
// Generate modes filter card. This one is also a special case.
function generateModesMultiToggleFilterCard(mode_options) {
const $grid = $('<div class="row row-cols-3 row-cols-md-2 row-cols-lg-3 g-1 mb-1">');
mode_options.forEach(o => {
const domSafeName = o.replace(/^[^A-Za-z0-9]+|[^\w]+/gi, "");
$grid.append(`<div class="col"><div class="form-check"><input type="checkbox" class="form-check-input filter-button-mode storeable-checkbox" id="filter-button-mode-${domSafeName}" value="${o}" autocomplete="off" onClick="filtersUpdated()" checked><label class="form-check-label" id="filter-button-label-mode-${domSafeName}" for="filter-button-mode-${domSafeName}">${o}</label></div></div>`);
});
$("#mode-options").append($grid);
$("#mode-options").append(`<div class="mt-1"><a href="#" onclick="toggleFilterButtons('mode', true); return false;">All</a> &nbsp; <a href="#" onclick="toggleFilterButtons('mode', false); return false;">None</a> &nbsp; <a href="#" onclick="setVoiceModeToggles(); return false;">Voice only</a> &nbsp; <a href="#" onclick="setDigiModeToggles(); return false;">Digimodes only</a></div>`);
}
// Set the mode toggles that relate to Analog Voice.
function setVoiceModeToggles() {
const modes = ["PHONE", "SSB", "LSB", "USB", "AM", "FM", "DV", "DMR", "DSTAR", "C4FM", "M17"];
$(".filter-button-mode").each(function () {
$(this).prop('checked', modes.includes($(this).val().replace("filter-button-mode-", "")));
});
filtersUpdated();
}
// Set the mode toggles that relate to Digimodes.
function setDigiModeToggles() {
const modes = ["DATA", "FT8", "FT4", "RTTY", "SSTV", "JS8", "HELL", "PSK", "OLIVIA", "PKT", "MSK144"];
$(".filter-button-mode").each(function () {
$(this).prop('checked', modes.includes($(this).val().replace("filter-button-mode-", "")));
});
filtersUpdated();
}
// Generate Sources filter card. This one is a minor special case as we create the checkboxes in the normal way, but
// set which ones are enabled by default based on config rather than having them all enabled by default. We also sanitise
// names here for HTML elements.
function generateSourcesMultiToggleFilterCard(source_options, sources_enabled_by_default) {
const $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">');
source_options.forEach(o => {
const enable = sources_enabled_by_default.includes(o);
const domSafeName = o.replace(/^[^A-Za-z0-9]+|[^\w]+/gi, "");
$grid.append(`<div class="col"><div class="form-check"><input type="checkbox" class="form-check-input filter-button-source storeable-checkbox" id="filter-button-source-${domSafeName}" value="${o}" autocomplete="off" onClick="filtersUpdated()" ${enable ? "checked" : ""}><label class="form-check-label" for="filter-button-source-${domSafeName}">${o}</label></div></div>`);
});
$("#source-options").append($grid);
$("#source-options").append(`<div class="mt-1"><a href="#" onclick="toggleFilterButtons('source', true); return false;">All</a> &nbsp; <a href="#" onclick="toggleFilterButtons('source', false); return false;">None</a></div>`);
}
// Method called when any filter is changed to reload the spots and persist the filter settings.
function filtersUpdated() {
loadSpots();
saveSettings();
}
// Function to update the band colour scheme in spots, bands and map pages
function setBandColorSchemeFromUI() {
setBandColorScheme($("#band-color-scheme option:selected").val());
saveSettings();
// Fudge a full reload because we need to update not just colours in the list/map/bands but also the filters
window.location.reload();
}
// Query if a callsign-band-mode combination as has already been worked
function alreadyWorked(callsign, band, mode) {
return worked.includes(callsign + "-" + band + "-" + mode);
}
// Reload spots on becoming visible. This forces a refresh when used as a PWA and the user switches back to the PWA
// after some time has passed with it in the background.
addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadSpots();
}
});
// Startup
$(document).ready(function () {
// Load worked list
const tmpWorked = JSON.parse(localStorage.getItem("worked"));
if (tmpWorked) {
worked = tmpWorked;
}
});
+51
View File
@@ -0,0 +1,51 @@
// Load server status
function loadStatus() {
$.getJSON('/api/v2/status', function (jsonData) {
$("#software-version").text(jsonData["software-version"]);
$("#server-owner-callsign").text(jsonData["server-owner-callsign"]);
$("#up-since").text(moment().subtract(jsonData["uptime"], 'seconds').fromNow());
$("#memory-use").text(jsonData["mem_use_mb"] + " MB");
$("#total-spots").text(jsonData["num_spots"]);
$("#total-alerts").text(jsonData["num_alerts"]);
$("#web-server-status").text(jsonData["webserver"]["status"]);
$("#web-server-last-api").text(moment.unix(jsonData["webserver"]["last_api_access"]).utc().fromNow());
$("#web-server-last-page").text(moment.unix(jsonData["webserver"]["last_page_access"]).utc().fromNow());
$("#cleanup-status").text(jsonData["cleanup"]["status"]);
$("#cleanup-last-ran").text(moment.unix(jsonData["cleanup"]["last_ran"]).utc().fromNow());
jsonData["spot_providers"].forEach(p => {
$("#spot-providers-status-container").append(`
<div class="row row-cols-1 row-cols-md-4 g-4 mb-2">
<div class="col"><strong>${p["name"]}</strong></div>
<div class="col">Status: ${p["status"]}</div>
<div class="col">Last updated: ${(p["enabled"] && p["last_updated"] > 0) ? moment.unix(p["last_updated"]).utc().fromNow() : "N/A"}</div>
<div class="col">Latest spot: ${(p["enabled"] && p["last_spot"] > 0) ? moment.unix(p["last_spot"]).utc().fromNow() : "N/A"}</div>
</div>`);
});
jsonData["alert_providers"].forEach(p => {
$("#alert-providers-status-container").append(`
<div class="row row-cols-1 row-cols-md-4 g-4 mb-2">
<div class="col"><strong>${p["name"]}</strong></div>
<div class="col">Status: ${p["status"]}</div>
<div class="col">Last updated: ${(p["enabled"] && p["last_updated"] > 0) ? moment.unix(p["last_updated"]).utc().fromNow() : "N/A"}</div>
</div>`);
});
jsonData["solar_condition_providers"].forEach(p => {
$("#condition-providers-status-container").append(`
<div class="row row-cols-1 row-cols-md-4 g-4 mb-2">
<div class="col"><strong>${p["name"]}</strong></div>
<div class="col">Status: ${p["status"]}</div>
<div class="col">Last updated: ${(p["enabled"] && p["last_updated"] > 0) ? moment.unix(p["last_updated"]).utc().fromNow() : "N/A"}</div>
</div>`);
});
});
}
// Startup
$(document).ready(function () {
loadStatus();
});
+439
View File
@@ -0,0 +1,439 @@
//
// USER INTERFACE FUNCTIONS (AMATEUR RADIO)
// Functions providing colour schemes for ham radio bands, SIG icons etc.
//
const BAND_COLOR_SCHEMES = {
"PSK Reporter": {
"2200m": "#ff4500",
"600m": "#1e90ff",
"160m": "#7cfc00",
"80m": "#e550e5",
"60m": "#00008b",
"40m": "#5959ff",
"30m": "#62d962",
"20m": "#f2c40c",
"17m": "#f2f261",
"15m": "#cca166",
"12m": "#b22222",
"11m": "#00ff00",
"10m": "#ff69b4",
"6m": "#FF0000",
"5m": "#e0e0e0",
"4m": "#cc0044",
"2m": "#FF1493",
"1.25m": "#CCFF00",
"70cm": "#999900",
"23cm": "#5AB8C7",
"13cm": "#FF7F50",
"5.8GHz": "#cc0099",
"10GHz": "#696969",
"24GHz": "#f3edc6",
"47GHz": "#ffe786",
"76GHz": "#baf9d8"
},
"PSK Reporter (Adjusted)": {
"2200m": "#ff4500",
"600m": "#1e90ff",
"160m": "#7cfc00",
"80m": "#b33fb3",
"60m": "#00008b",
"40m": "#5959ff",
"30m": "#62d962",
"20m": "#f2c40c",
"17m": "#f2f261",
"15m": "#cca166",
"12m": "#b22222",
"11m": "#00ff00",
"10m": "#ff7eb4",
"6m": "#FF0000",
"5m": "#e0e0e0",
"4m": "#cc0044",
"2m": "#FF1493",
"1.25m": "#CCFF00",
"70cm": "#999900",
"23cm": "#5AB8C7",
"13cm": "#FF7F50",
"5.8GHz": "#cc0099",
"10GHz": "#696969",
"24GHz": "#f3edc6",
"47GHz": "#ffe786",
"76GHz": "#baf9d8"
},
"RBN": {
"2200m": "#000000",
"600m": "#aaaaaa",
"160m": "#ffe000",
"80m": "#093F00",
"60m": "#777777",
"40m": "#ffa500",
"30m": "#ff0000",
"20m": "#800080",
"17m": "#0000ff",
"15m": "#444444",
"12m": "#00ffff",
"11m": "#000000",
"10m": "#ff00ff",
"6m": "#ffc0cb",
"5m": "#000000",
"4m": "#a276ff",
"2m": "#92FF7F",
"1.25m": "#000000",
"70cm": "#000000",
"23cm": "#000000",
"13cm": "#000000",
"5.8GHz": "#000000",
"10GHz": "#000000",
"24GHz": "#000000",
"47GHz": "#000000",
"76GHz": "#000000"
},
"Ham Rainbow": {
"2200m": "#8e4f37",
"600m": "#8e4f37",
"160m": "#8e3737",
"80m": "#da2f93",
"60m": "#792fda",
"40m": "#2f4bda",
"30m": "#2fdad2",
"20m": "#68da2f",
"17m": "#dad52f",
"15m": "#da832f",
"12m": "#da5c2f",
"11m": "#8e8e8e",
"10m": "#da2f2f",
"6m": "#8e377a",
"5m": "#8e8e8e",
"4m": "#42378e",
"2m": "#37748e",
"1.25m": "#8e8e8e",
"70cm": "#378e65",
"23cm": "#8e8e37",
"13cm": "#8e6037",
"5.8GHz": "#8e6037",
"10GHz": "#8e6037",
"24GHz": "#8e6037",
"47GHz": "#8e6037",
"76GHz": "#8e6037"
},
"Ham Rainbow (Reverse)": {
"2200m": "#42378e",
"600m": "#42378e",
"160m": "#8e377a",
"80m": "#da2f2f",
"60m": "#da5c2f",
"40m": "#da832f",
"30m": "#dad52f",
"20m": "#68da2f",
"17m": "#2fdad2",
"15m": "#2f4bda",
"12m": "#792fda",
"11m": "#8e8e8e",
"10m": "#da2f93",
"6m": "#8e3737",
"5m": "#8e8e8e",
"4m": "#8e4f37",
"2m": "#8e6037",
"1.25m": "#8e8e8e",
"70cm": "#8e8e37",
"23cm": "#378e65",
"13cm": "#37748e",
"5.8GHz": "#37748e",
"10GHz": "#37748e",
"24GHz": "#37748e",
"47GHz": "#37748e",
"76GHz": "#37748e",
},
"Kate Morley": {
"2200m": "#817",
"600m": "#817",
"160m": "#817",
"80m": "#a35",
"60m": "#c66",
"40m": "#e94",
"30m": "#ed0",
"20m": "#9d5",
"17m": "#4d8",
"15m": "#2cb",
"12m": "#0bc",
"11m": "#09c",
"10m": "#09c",
"6m": "#36b",
"5m": "#36b",
"4m": "#36b",
"2m": "#36b",
"1.25m": "#36b",
"70cm": "#639",
"23cm": "#639",
"13cm": "#639",
"5.8GHz": "#639",
"10GHz": "#639",
"24GHz": "#639",
"47GHz": "#639",
"76GHz": "#639",
},
"ColorBrewer": {
"2200m": "#54278f",
"600m": "#756bb1",
"160m": "#9e9ac8",
"80m": "#cbc9e2",
"60m": "#08519c",
"40m": "#3182bd",
"30m": "#6baed6",
"20m": "#bdd7e7",
"17m": "#006d2c",
"15m": "#31a354",
"12m": "#74c476",
"11m": "#bae4b3",
"10m": "#a63603",
"6m": "#e6550d",
"5m": "#fd8d3c",
"4m": "#fdbe85",
"2m": "#a50f15",
"1.25m": "#de2d26",
"70cm": "#fb6a4a",
"23cm": "#fcae91",
"13cm": "#636363",
"5.8GHz": "#636363",
"10GHz": "#969696",
"24GHz": "#969696",
"47GHz": "#cccccc",
"76GHz": "#cccccc",
},
"IWantHue": {
"2200m": "#409271",
"600m": "#b03ce1",
"160m": "#50c640",
"80m": "#d545b7",
"60m": "#99b936",
"40m": "#7260db",
"30m": "#60af57",
"20m": "#d54788",
"17m": "#58c79f",
"15m": "#e2462a",
"12m": "#49b1d3",
"11m": "#df872f",
"10m": "#506bb0",
"6m": "#c6a639",
"5m": "#9554a3",
"4m": "#36783c",
"2m": "#da405b",
"1.25m": "#657527",
"70cm": "#8c97e2",
"23cm": "#b44f2f",
"13cm": "#d386c8",
"5.8GHz": "#aaac66",
"10GHz": "#9d4760",
"24GHz": "#90672c",
"47GHz": "#e08086",
"76GHz": "#dc9769",
},
"IWantHue (Color Blind)": {
"2200m": "#bf9e3d",
"600m": "#9d2fec",
"160m": "#79df39",
"80m": "#d445db",
"60m": "#5dd175",
"40m": "#814dd8",
"30m": "#d7ce2f",
"20m": "#657af1",
"17m": "#8cc34a",
"15m": "#d635aa",
"12m": "#6cbd80",
"11m": "#b860c1",
"10m": "#e48721",
"6m": "#686ccc",
"5m": "#d44e2b",
"4m": "#51b3db",
"2m": "#d74058",
"1.25m": "#56c5ad",
"70cm": "#d0478d",
"23cm": "#708940",
"13cm": "#c380c2",
"5.8GHz": "#cab775",
"10GHz": "#7a7fc2",
"24GHz": "#b87148",
"47GHz": "#bd678c",
"76GHz": "#c3666b",
},
"Mokole": {
"2200m": "#8b4513",
"600m": "#006400",
"160m": "#808000",
"80m": "#483d8b",
"60m": "#5f9ea0",
"40m": "#000080",
"30m": "#9acd32",
"20m": "#8b008b",
"17m": "#ff0000",
"15m": "#ff8c00",
"12m": "#ffd700",
"11m": "#7fff00",
"10m": "#8a2be2",
"6m": "#00ff7f",
"5m": "#dc143c",
"4m": "#00bfff",
"2m": "#0000ff",
"1.25m": "#d8bfd8",
"70cm": "#ff00ff",
"23cm": "#1e90ff",
"13cm": "#db7093",
"5.8GHz": "#f0e68c",
"10GHz": "#ff1493",
"24GHz": "#ffa07a",
"47GHz": "#ee82ee",
"76GHz": "#7fffd4",
}
};
let bandColorScheme = "PSK Reporter (Adjusted)";
// Set the band colour scheme. Returns true if successful, false if the requested scheme was not known
function setBandColorScheme(scheme) {
let ret = BAND_COLOR_SCHEMES[scheme]
if (ret) {
bandColorScheme = scheme;
}
return ret;
}
// Get the list of known bands
function getKnownBands() {
return Array.from(Object.keys(BAND_COLOR_SCHEMES[bandColorScheme]));
}
// Get the list of available band colour schemes
function getAvailableBandColorSchemes() {
return Array.from(Object.keys(BAND_COLOR_SCHEMES));
}
// Band name to colour (in the current colour scheme). If the band is unknown, black will be returned.
function bandToColor(band) {
let col = (band != null) ? BAND_COLOR_SCHEMES[bandColorScheme][band] : null;
if (col) {
return col;
} else {
return "#000000";
}
}
// Band name to contrast colour (in the current colour scheme). This is either black or white, contrasting as well as
// possible with the band colour. If the band is unknown, white will be returned.
function bandToContrastColor(band) {
const rgb = hexToRGB(bandToColor(band));
const lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
return (lum > 128) ? "#000000" : "#ffffff";
}
const MODE_TYPE_COLOR_SCHEMES = {
"CW": "red",
"PHONE": "green",
"DATA": "blue"
}
// Mode type (CW, PHONE, DATA) to colour. If the mode type is unknown, black will be returned.
function modeTypeToColor(modeType) {
let col = (modeType != null) ? MODE_TYPE_COLOR_SCHEMES[modeType.toUpperCase()] : null;
if (col) {
return col;
} else {
return "#000000";
}
}
const SIG_ICONS = {
"POTA": "fa-tree",
"SOTA": "fa-mountain-sun",
"WWFF": "fa-seedling",
"GMA": "fa-person-hiking",
"WWBOTA": "fa-radiation",
"HEMA": "fa-mound",
"IOTA": "fa-book-atlas",
"MOTA": "fa-fan",
"ARLHS": "fa-house-flood-water",
"ILLW": "fa-house-flood-water",
"SIOTA": "fa-wheat-awn",
"WCA": "fa-chess-rook",
"ZLOTA": "fa-kiwi-bird",
"WOTA": "fa-w",
"BOTA": "fa-umbrella-beach",
"KRMNPA": "fa-earth-oceania",
"LLOTA": "fa-water",
"Towers": "fa-tower-observation",
"WAB": "fa-table-cells-large",
"WAI": "fa-table-cells-large",
"DME": "fa-building",
"Tiles": "fa-square",
"Toilets": "fa-toilet"
}
const SIG_NAMES = {
"POTA": "Parks on the Air",
"SOTA": "Summits on the Air",
"WWFF": "Worldwide Flora & Fauna",
"GMA": "Global Mountain Activity",
"WWBOTA": "Bunkers on the Air",
"HEMA": "Humps Excluding Marilyns Award",
"IOTA": "Islands on the Air",
"MOTA": "Mills on the Air",
"ARLHS": "Amateur Radio Lighthouse Society",
"ILLW": "International Lighthouse Lightship Weekend",
"SIOTA": "Silos on the Air",
"WCA": "World Castles Award",
"ZLOTA": "New Zealand on the Air",
"WOTA": "Wainwrights on the Air",
"BOTA": "Beaches on the Air",
"KRMNPA": "Keith Roget Memorial National Parks Award",
"LLOTA": "Lagos y Lagunas on the Air",
"WWTOTA": "Towers on the Air",
"WAB": "Worked All Britain",
"WAI": "Worked All Ireland",
"Tiles": "Tiles on the Air",
"TOTA": "Toilets on the Air"
}
// Get the Font Awesome icon for a given SIG. If the SIG is unknown, the provided default symbol will be returned
function sigToIcon(sig, defaultIcon) {
let col = (sig != null) ? SIG_ICONS[sig] : null;
if (col) {
return col;
} else {
let col = (sig != null) ? SIG_ICONS[sig.toUpperCase()] : null;
if (col) {
return col;
} else {
return defaultIcon;
}
}
}
// Get the full name for a given SIG abbreviation. If the SIG is unknown, an empty string will be returned.
function sigToName(sig) {
let col = (sig != null) ? SIG_NAMES[sig] : null;
if (col) {
return col;
} else {
let col = (sig != null) ? SIG_NAMES[sig.toUpperCase()] : null;
if (col) {
return col;
} else {
return "";
}
}
}
// Get the list of known SIGs
function getKnownSIGs() {
return Array.from(Object.keys(SIG_ICONS));
}
// Format a Maidenhead grid with alternating alphabetic blocks in lower case
function formatGrid(grid) {
grid = grid.toUpperCase();
if (grid.length >= 6) {
grid = grid.substring(0, 4) + grid.substring(4, 6).toLowerCase() + grid.substring(6);
}
if (grid.length >= 12) {
grid = grid.substring(0, 10) + grid.substring(10, 12).toLowerCase() + grid.substring(14);
}
return grid;
}
+40
View File
@@ -0,0 +1,40 @@
//
// GENERAL UTILITY FUNCTIONS
// OBject, string manipulation etc.
//
// Utility function to escape HTML characters from a string.
function escapeHtml(str) {
if (typeof str !== 'string') {
return '';
}
const escapeCharacter = (match) => {
switch (match) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
case '\'':
return '&#039;';
case '`':
return '&#096;';
default:
return match;
}
};
return str.replace(/[&<>"'`]/g, escapeCharacter);
}
// Converts an HTML hex colour to an array of [R, G, B] where each is 0-255.
function hexToRGB(hex) {
return hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
, (m, r, g, b) => '#' + r + r + g + g + b + b)
.substring(1).match(/.{2}/g)
.map(x => parseInt(x, 16));
}