Files
spothole/webassets/js/alerts.js
2025-10-06 21:11:59 +01:00

300 lines
12 KiB
JavaScript

// How often to query the server?
const REFRESH_INTERVAL_SEC = 60 * 30;
// Storage for the alert data that the server gives us.
var alerts = []
// Storage for the options that the server gives us. This will define our filters.
var options = {};
// Last time we updated the alerts list on display.
var lastUpdateTime;
// Load alerts and populate the table.
function loadAlerts() {
$.getJSON('/api/alerts' + buildQueryString(), 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() {
var str = "?";
["dx_continent", "source"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&";
}
});
str = str + "limit=" + $("#alerts-to-fetch option:selected").val();
str = str + "&max_duration=604800";
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 alerts 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>Start UTC</th>`);
table.find('thead tr').append(`<th>End UTC</th>`);
table.find('thead tr').append(`<th>DX</th>`);
table.find('thead tr').append(`<th>Freq<span class='hideonmobile'>uencie</span>s & Modes</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>`);
// 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.
onNow = alerts.filter(a => (a["end_time"] != null && moment.unix(a["end_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore())
|| (a["end_time"] == null && moment.unix(a["start_time"]).utc().add(1, 'hours').isSameOrAfter() && moment.unix(a["start_time"]).utc().isBefore()));
next24h = alerts.filter(a => moment.unix(a["start_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().subtract(24, 'hours').isBefore());
later = alerts.filter(a => moment.unix(a["start_time"]).utc().subtract(24, 'hours').isSameOrAfter());
if (onNow.length > 0) {
table.find('tbody').append('<tr class="table-primary"><td colspan="100" style="text-align:center;">On Now</td></tr>');
addAlertRowsToTable(table.find('tbody'), onNow);
}
if (next24h.length > 0) {
table.find('tbody').append('<tr class="table-primary"><td colspan="100" style="text-align:center;">Starting within 24 hours</td></tr>');
addAlertRowsToTable(table.find('tbody'), next24h);
}
if (later.length > 0) {
table.find('tbody').append('<tr class="table-primary"><td colspan="100" 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="table-danger"><td colspan="100" style="text-align:center;">No alerts match your filters.</td></tr>');
}
// Update DOM
$('#table-container').html(table);
}
// Add a row to tbody for each alert in the provided list
function addAlertRowsToTable(tbody, alerts) {
alerts.forEach(a => {
// Create row
let $tr = $('<tr>');
// Format UTC times for display
var start_time = moment.unix(a["start_time"]).utc();
var start_time_formatted = start_time.format("YYYY-MM-DD HH:mm");
var end_time = moment.unix(a["end_time"]).utc();
var end_time_formatted = (end_time != null) ? end_time.format("YYYY-MM-DD HH:mm") : "Not specified";
// Format dx country
var dx_country = a["dx_country"]
if (dx_country == null) {
dx_country = "Unknown or not a country"
}
// Format freqs & modes
var freqsModesText = "";
if (a["freqs_modes"] != null) {
freqsModesText = escapeHtml(a["freqs_modes"]);
}
// Format comment
var commentText = "";
if (a["comment"] != null) {
commentText = escapeHtml(a["comment"]);
}
// Sig or fallback to source
var sigSourceText = a["source"];
if (a["sig"]) {
sigSourceText = a["sig"];
}
// Format sig_refs
var sig_refs = ""
if (a["sig_refs"]) {
sig_refs = a["sig_refs"].join(", ")
}
// Populate the row
$tr.append(`<td class='nowrap'>${start_time_formatted}</td>`);
$tr.append(`<td class='nowrap'>${end_time_formatted}</td>`);
$tr.append(`<td class='nowrap'><span class='flag-wrapper hideonmobile' title='${dx_country}'>${a["dx_flag"]}</span><a class='dx-link' href='https://qrz.com/db/${a["dx_call"]}' target='_new'>${a["dx_call"]}</a></td>`);
$tr.append(`<td class='hideonmobile'>${freqsModesText}</td>`);
$tr.append(`<td class='hideonmobile'>${commentText}</td>`);
$tr.append(`<td class='nowrap hideonmobile'><span class='icon-wrapper'><i class='fa-solid fa-${a["icon"]}'></i></span> ${sigSourceText}</td>`);
$tr.append(`<td class='hideonmobile'>${sig_refs}</td>`);
tbody.append($tr);
// Second row for mobile view only, containing source, ref, freqs/modes & comment
$tr2 = $("<tr class='hidenotonmobile'>");
$tr2.append(`<td colspan="100"><span class='icon-wrapper'><i class='fa-solid fa-${a["icon"]}'></i></span> ${sig_refs} ${freqsModesText}<br/>${commentText}</td>`);
tbody.append($tr2);
});
}
// Load server options. Once a successful callback is made from this, we then query alerts.
function loadOptions() {
$.getJSON('/api/options', function(jsonData) {
// Store options
options = jsonData;
// Populate the filters panel
$("#settings-container").append(generateFilterCard("DX Continent", "dx_continent", options["continents"]));
$("#settings-container").append(generateFilterCard("Sources", "source", options["spot_sources"]));
// Load settings from settings storage
loadSettings();
// Load alerts and set up the timer
loadAlerts();
setInterval(loadAlerts, REFRESH_INTERVAL_SEC * 1000);
});
}
// 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>&nbsp;<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 alerts and persist the filter settings.
function filtersUpdated() {
loadAlerts();
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;
if (count <= 60) {
var number = count.toFixed(0);
updatingString = "Updating in " + number + " second" + (number != "1" ? "s" : "") + ".";
} else {
var number = Math.round(count / 60.0).toFixed(0);
updatingString = "Updating in " + number + " minute" + (number != "1" ? "s" : "") + ".";
}
}
$("#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 '&amp;';
case '<': return '&lt;';
case '>': return '&gt;';
case '"': return '&quot;';
case '\'': return '&#039;';
case '`': return '&#096;';
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.
$(".storeable-checkbox").each(function() {
localStorage.setItem($(this)[0].id + ":checked", $(this)[0].checked);
});
$(".storeable-select").each(function() {
localStorage.setItem($(this)[0].id + ":value", $(this)[0].value);
});
}
// 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() {
$("#settings-button").click(function() {
$("#settings-area").toggle();
});
$("#close-settings-button").click(function() {
$("#settings-button").button("toggle");
$("#settings-area").hide();
});
$("#alerts-to-fetch").click(function() {
filtersUpdated();
});
}
// 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);
// Set up event listeners
setUpEventListeners();
});