mirror of
https://git.ianrenton.com/ian/spothole.git
synced 2025-10-27 16:59:25 +00:00
402 lines
18 KiB
JavaScript
402 lines
18 KiB
JavaScript
// How often to query the server?
|
|
const REFRESH_INTERVAL_SEC = 60;
|
|
|
|
// Storage for the spot data that the server gives us.
|
|
var spots = []
|
|
// Storage for the options that the server gives us. This will define our filters.
|
|
var options = {};
|
|
// Last time we updated the spots list on display.
|
|
var lastUpdateTime;
|
|
|
|
// Load spots and populate the table.
|
|
function loadSpots() {
|
|
$.getJSON('/api/spots' + buildQueryString(), function(jsonData) {
|
|
// Store last updated time
|
|
lastUpdateTime = moment.utc();
|
|
updateRefreshDisplay();
|
|
// Store data
|
|
spots = jsonData;
|
|
// Update table
|
|
updateTable();
|
|
});
|
|
}
|
|
|
|
// Build a query string for the API, based on the filters that the user has selected.
|
|
function buildQueryString() {
|
|
var str = "?";
|
|
["dx_continent", "de_continent", "mode_type", "source", "band"].forEach(fn => {
|
|
if (!allFilterOptionsSelected(fn)) {
|
|
str = str + getQueryStringFor(fn) + "&";
|
|
}
|
|
});
|
|
str = str + "limit=50";
|
|
return str;
|
|
}
|
|
|
|
// 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) {
|
|
var filter = $(".filter-button-" + parameter).filter(function() {
|
|
return !this.checked;
|
|
}).get();
|
|
return filter.length == 0;
|
|
}
|
|
|
|
// Update the spots table
|
|
function updateTable() {
|
|
// Populate table with headers
|
|
let table = $('<table class="table table-striped-custom table-hover">').append('<thead><tr class="table-primary"></tr></thead><tbody></tbody>');
|
|
table.find('thead tr').append(`<th>UTC</th>`);
|
|
table.find('thead tr').append(`<th>DX</th>`);
|
|
table.find('thead tr').append(`<th>Freq<span class='hideonmobile'>uency</span></th>`);
|
|
table.find('thead tr').append(`<th>Mode</th>`);
|
|
table.find('thead tr').append(`<th class='hideonmobile'>Comment</th>`);
|
|
table.find('thead tr').append(`<th class='hideonmobile'>Source</th>`);
|
|
table.find('thead tr').append(`<th class='hideonmobile'>Ref.</th>`);
|
|
table.find('thead tr').append(`<th class='hideonmobile'>DE</th>`);
|
|
|
|
if (spots.length == 0) {
|
|
table.find('tbody').append('<tr class="table-danger"><td colspan="100" style="text-align:center;">No spots match your filters.</td></tr>');
|
|
}
|
|
|
|
spots.forEach(s => {
|
|
// Create row
|
|
let $tr = $('<tr>');
|
|
|
|
// Show faded out if QRT
|
|
if (s["qrt"] == true) {
|
|
$tr.addClass("table-faded");
|
|
}
|
|
|
|
// Format a UTC time for display
|
|
var time = moment.utc(s["time"], moment.ISO_8601);
|
|
var time_formatted = time.format("HH:mm")
|
|
|
|
// Format dx country
|
|
var dx_country = s["dx_country"]
|
|
if (dx_country == null) {
|
|
dx_country = "Unknown or not a country"
|
|
}
|
|
|
|
// Format the frequency
|
|
var mhz = Math.floor(s["freq"] / 1000000.0);
|
|
var khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0);
|
|
var hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0));
|
|
var hz_string = (hz > 0) ? hz.toFixed(0)[0] : "";
|
|
var freq_string = `<span class='freq-mhz'>${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
|
|
mode_string = s["mode"];
|
|
if (s["mode"] == null) {
|
|
mode_string = "???"
|
|
}
|
|
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
|
|
var commentText = "";
|
|
if (s["comment"] != null) {
|
|
commentText = escapeHtml(s["comment"]);
|
|
}
|
|
|
|
// Sig or fallback to source
|
|
var sigSourceText = s["source"];
|
|
if (s["sig"]) {
|
|
sigSourceText = s["sig"];
|
|
}
|
|
|
|
// Format sig_refs
|
|
var sig_refs = ""
|
|
if (s["sig_refs"]) {
|
|
sig_refs = s["sig_refs"].join(", ")
|
|
}
|
|
|
|
// Format DE flag
|
|
var de_flag = "<i class='fa-solid fa-circle-question'></i>";
|
|
if (s["de_flag"] && s["de_flag"] != "") {
|
|
de_flag = s["de_flag"];
|
|
}
|
|
|
|
// Format de country
|
|
var de_country = s["de_country"]
|
|
if (de_country == null) {
|
|
de_country = "Unknown or not a country"
|
|
}
|
|
|
|
// CSS doesn't like classes with decimal points in, so we need to replace that in the same way as when we originally
|
|
// queried the options endpoint and set our CSS.
|
|
var cssFormattedBandName = s['band'] ? s['band'].replace('.', 'p') : "unknown";
|
|
var bandFullName = s['band'] ? s['band'] + " band": "Unknown band";
|
|
|
|
// Populate the row
|
|
$tr.append(`<td class='nowrap'>${time_formatted}</td>`);
|
|
$tr.append(`<td class='nowrap'><span class='flag-wrapper hideonmobile' title='${dx_country}'>${s["dx_flag"]}</span><a class='dx-link' href='https://qrz.com/db/${s["dx_call"]}' target='_new'>${s["dx_call"]}</a></td>`);
|
|
$tr.append(`<td class='nowrap'><span class='band-bullet band-bullet-${cssFormattedBandName}' title='${bandFullName}'>■</span>${freq_string}</td>`);
|
|
$tr.append(`<td class='nowrap'>${mode_string}</td>`);
|
|
$tr.append(`<td class='hideonmobile'>${commentText}</td>`);
|
|
$tr.append(`<td class='nowrap hideonmobile'><span class='icon-wrapper'><i class='fa-solid fa-${s["icon"]}'></i></span> ${s["source"]}</td>`);
|
|
$tr.append(`<td class='nowrap hideonmobile'>${sig_refs}</td>`);
|
|
$tr.append(`<td class='nowrap hideonmobile'><span class='flag-wrapper' title='${de_country}'>${de_flag}</span>${s["de_call"]}</td>`);
|
|
table.find('tbody').append($tr);
|
|
|
|
// Second row for mobile view only, containing source, ref & comment
|
|
$tr2 = $("<tr class='hidenotonmobile'>");
|
|
if (s["qrt"] == true) {
|
|
$tr2.addClass("table-faded");
|
|
}
|
|
$tr2.append(`<td colspan="100"><span class='icon-wrapper'><i class='fa-solid fa-${s["icon"]}'></i></span> ${sig_refs} ${commentText}</td>`);
|
|
table.find('tbody').append($tr2);
|
|
});
|
|
|
|
// Update DOM
|
|
$('#table-container').html(table);
|
|
}
|
|
|
|
// Load server status
|
|
function loadStatus() {
|
|
$.getJSON('/api/status', function(jsonData) {
|
|
$("#status-container").empty();
|
|
$("#status-container").append(generateStatusCard("Server Information", [
|
|
`Software Version: ${jsonData["software-version"]}`,
|
|
`Server Owner Callsign: ${jsonData["server-owner-callsign"]}`,
|
|
`Server Uptime: ${jsonData["uptime"]}`,
|
|
`Memory Use: ${jsonData["mem_use_mb"]} MB`,
|
|
`Total Spots: ${jsonData["num_spots"]}`
|
|
]));
|
|
$("#status-container").append(generateStatusCard("Web Server", [
|
|
`Status: ${jsonData["webserver"]["status"]}`,
|
|
`Last API Access: ${moment.utc(jsonData["webserver"]["last_api_access"], moment.ISO_8601).format("HH:mm")}`,
|
|
`Last Page Access: ${moment.utc(jsonData["webserver"]["last_page_access"], moment.ISO_8601).format("HH:mm")}`
|
|
]));
|
|
$("#status-container").append(generateStatusCard("Cleanup Service", [
|
|
`Status: ${jsonData["cleanup"]["status"]}`,
|
|
`Last Ran: ${moment.utc(jsonData["cleanup"]["last_ran"], moment.ISO_8601).format("HH:mm")}`
|
|
]));
|
|
jsonData["providers"].forEach(p => {
|
|
$("#status-container").append(generateStatusCard("Provider: " + p["name"], [
|
|
`Status: ${p["status"]}`,
|
|
`Last Updated: ${p["enabled"] ? moment.utc(p["last_updated"], moment.ISO_8601).format("HH:mm") : "N/A"}`,
|
|
`Latest Spot: ${p["enabled"] ? moment.utc(p["last_spot"], moment.ISO_8601).format("HH:mm YYYY-MM-DD") : "N/A"}`
|
|
]));
|
|
});
|
|
});
|
|
}
|
|
|
|
// Generate a status card
|
|
function generateStatusCard(title, textLines) {
|
|
let $col = $("<div class='col'>")
|
|
let $card = $("<div class='card'>");
|
|
let $card_body = $("<div class='card-body'>");
|
|
$card_body.append(`<h5 class='card-title'>${title}</h5>`);
|
|
$card_body.append(`<p class='card-text'>${textLines.join("<br/>")}</p>`);
|
|
$card.append($card_body);
|
|
$col.append($card);
|
|
return $col;
|
|
}
|
|
|
|
// 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/options', function(jsonData) {
|
|
// Store options
|
|
options = jsonData;
|
|
|
|
// Add CSS for band bullets and band toggle buttons
|
|
addBandColourCSS(options["bands"]);
|
|
|
|
// Populate the filters panel
|
|
$("#filters-container-1").append(generateBandsFilterCard("Bands", "band", options["bands"]));
|
|
$("#filters-container-2").append(generateFilterCard("DX Continent", "dx_continent", options["continents"]));
|
|
$("#filters-container-2").append(generateFilterCard("DE Continent", "de_continent", options["continents"]));
|
|
$("#filters-container-2").append(generateFilterCard("Modes", "mode_type", options["mode_types"]));
|
|
$("#filters-container-2").append(generateFilterCard("Sources", "source", options["sources"]));
|
|
|
|
// Load filter settings from settings storage
|
|
loadSettings();
|
|
|
|
// Load spots and set up the timer
|
|
loadSpots();
|
|
setInterval(loadSpots, REFRESH_INTERVAL_SEC * 1000)
|
|
});
|
|
}
|
|
|
|
// Dynamically add CSS code for the band bullets and band toggle buttons to be 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 addBandColourCSS(band_options) {
|
|
var $style = $('<style>');
|
|
band_options.forEach(o => {
|
|
// CSS doesn't like IDs with decimal points in, so we need to replace that
|
|
var cssFormattedBandName = o['name'] ? o['name'].replace('.', 'p') : "unknown";
|
|
$style.append(`.band-bullet-${cssFormattedBandName} { color: ${o['color']}; }`);
|
|
$style.append(`#filter-button-label-band-${cssFormattedBandName} { border-color: ${o['color']}; color: var(--bs-primary);}`);
|
|
$style.append(`.btn-check:checked + #filter-button-label-band-${cssFormattedBandName} { background-color: ${o['color']}; color: ${o['contrast_color']};}`);
|
|
});
|
|
$('html > head').append($style);
|
|
}
|
|
|
|
// Generate filter card
|
|
function generateFilterCard(displayName, filterQuery, options) {
|
|
let $col = $("<div class='col'>")
|
|
let $card = $("<div class='card'>");
|
|
let $card_body = $("<div class='card-body'>");
|
|
$card_body.append(`<h5 class='card-title'>${displayName}</h5>`);
|
|
$p = $("<p class='card-text filter-card-text'>");
|
|
// Create a button for each option
|
|
options.forEach(o => {
|
|
$p.append(`<input type="checkbox" class="btn-check filter-button-${filterQuery} storeable-checkbox" name="options" id="filter-button-${filterQuery}-${o}" value="${o}" autocomplete="off" onClick="filtersUpdated()" checked><label class="btn btn-outline-primary" for="filter-button-${filterQuery}-${o}">${o}</label> `);
|
|
});
|
|
// Create All/None buttons
|
|
$p.append(` <span style="display: inline-block"><button id="filter-button-${filterQuery}-all" type="button" class="btn btn-outline-secondary" onclick="toggleFilterButtons('${filterQuery}', true);">All</button> <button id="filter-button-${filterQuery}-none" type="button" class="btn btn-outline-secondary" onclick="toggleFilterButtons('${filterQuery}', false);">None</button></span>`);
|
|
// Compile HTML elements to return
|
|
$card_body.append($p);
|
|
$card.append($card_body);
|
|
$col.append($card);
|
|
return $col;
|
|
}
|
|
|
|
// Generate bands filter card. This one is a special case.
|
|
function generateBandsFilterCard(displayName, filterQuery, band_options) {
|
|
let $col = $("<div class='col'>")
|
|
let $card = $("<div class='card'>");
|
|
let $card_body = $("<div class='card-body'>");
|
|
$card_body.append(`<h5 class='card-title'>${displayName}</h5>`);
|
|
$p = $("<p class='card-text filter-card-text'>");
|
|
// Create a button for each option
|
|
band_options.forEach(o => {
|
|
// CSS doesn't like IDs with decimal points in, so we need to replace that in the same way as when we originally
|
|
// queried the options endpoint and set our CSS.
|
|
var cssFormattedBandName = o['name'] ? o['name'].replace('.', 'p') : "unknown";
|
|
$p.append(`<input type="checkbox" class="btn-check filter-button-${filterQuery} storeable-checkbox" name="options" id="filter-button-${filterQuery}-${cssFormattedBandName}" value="${o['name']}" autocomplete="off" onClick="filtersUpdated()" checked><label class="btn btn-outline" id="filter-button-label-${filterQuery}-${cssFormattedBandName}" for="filter-button-${filterQuery}-${cssFormattedBandName}">${o['name']}</label> `);
|
|
});
|
|
// Create All/None buttons
|
|
$p.append(` <span style="display: inline-block"><button id="filter-button-${filterQuery}-all" type="button" class="btn btn-outline-secondary" onclick="toggleFilterButtons('${filterQuery}', true);">All</button> <button id="filter-button-${filterQuery}-none" type="button" class="btn btn-outline-secondary" onclick="toggleFilterButtons('${filterQuery}', false);">None</button></span>`);
|
|
// Compile HTML elements to return
|
|
$card_body.append($p);
|
|
$card.append($card_body);
|
|
$col.append($card);
|
|
return $col;
|
|
}
|
|
|
|
// Method called when "All" or "None" is clicked
|
|
function toggleFilterButtons(filterQuery, state) {
|
|
$(".filter-button-" + filterQuery).each(function() {
|
|
$(this).prop('checked', state);
|
|
});
|
|
filtersUpdated();
|
|
}
|
|
|
|
// Method called when any filter is changed to reload the spots and persist the filter settings.
|
|
function filtersUpdated() {
|
|
loadSpots();
|
|
saveSettings();
|
|
}
|
|
|
|
// Update the refresh timing display
|
|
function updateRefreshDisplay() {
|
|
if (lastUpdateTime != null) {
|
|
let count = REFRESH_INTERVAL_SEC;
|
|
let secSinceUpdate = moment.duration(moment().diff(lastUpdateTime)).asSeconds();
|
|
updatingString = "Updating..."
|
|
if (secSinceUpdate < REFRESH_INTERVAL_SEC) {
|
|
count = REFRESH_INTERVAL_SEC - secSinceUpdate;
|
|
updatingString = "Updating in " + count.toFixed(0) + " seconds...";
|
|
}
|
|
$("#timing-container").text("Last updated at " + lastUpdateTime.format('HH:mm') + " UTC. " + updatingString);
|
|
}
|
|
}
|
|
|
|
// Utility function to escape HTML characters from a string.
|
|
function escapeHtml(str) {
|
|
if (typeof str !== 'string') {
|
|
return '';
|
|
}
|
|
|
|
const escapeCharacter = (match) => {
|
|
switch (match) {
|
|
case '&': return '&';
|
|
case '<': return '<';
|
|
case '>': return '>';
|
|
case '"': return '"';
|
|
case '\'': return ''';
|
|
case '`': return '`';
|
|
default: return match;
|
|
}
|
|
};
|
|
|
|
return str.replace(/[&<>"'`]/g, escapeCharacter);
|
|
}
|
|
|
|
// Save settings to local storage
|
|
function saveSettings() {
|
|
// 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.
|
|
return $(".storeable-checkbox").each(function() {
|
|
localStorage.setItem($(this)[0].id + ":checked", $(this)[0].checked);
|
|
});
|
|
}
|
|
|
|
// Load settings from local storage and set up the filter selectors
|
|
function loadSettings() {
|
|
// Find all local storage entries and push their data to the corresponding UI element
|
|
Object.keys(localStorage).forEach(function(key) {
|
|
// Split the key back into an element ID and a property
|
|
var split = key.split(":");
|
|
$("#" + split[0]).prop(split[1], JSON.parse(localStorage.getItem(key)));
|
|
});
|
|
}
|
|
|
|
// Set up UI element event listeners, after the document is ready
|
|
function setUpEventListeners() {
|
|
$("#status-button").click(function() {
|
|
// If we are going to display status, load the data for the status panel, and hide the filters panel
|
|
if (!$("#status-area").is(":visible")) {
|
|
loadStatus();
|
|
if ($("#filters-area").is(":visible")) {
|
|
$("#filters-area").hide();
|
|
$("#filters-button").button("toggle");
|
|
}
|
|
}
|
|
$("#status-area").toggle();
|
|
});
|
|
$("#close-status-button").click(function() {
|
|
$("#status-button").button("toggle");
|
|
$("#status-area").hide();
|
|
});
|
|
$("#filters-button").click(function() {
|
|
// If we are going to display filters, hide the filters panel
|
|
if (!$("#filters-area").is(":visible") && $("#status-area").is(":visible")) {
|
|
$("#status-area").hide();
|
|
$("#status-button").button("toggle");
|
|
}
|
|
$("#filters-area").toggle();
|
|
});
|
|
$("#close-filters-button").click(function() {
|
|
$("#filters-button").button("toggle");
|
|
$("#filters-area").hide();
|
|
});
|
|
}
|
|
|
|
// Startup
|
|
$(document).ready(function() {
|
|
// Call loadOptions(), this will then trigger loading spots and setting up timers.
|
|
loadOptions();
|
|
// Update the refresh timing display every second
|
|
setInterval(updateRefreshDisplay, 1000);
|
|
// Set up event listeners
|
|
setUpEventListeners();
|
|
}); |