14 Commits
Author SHA1 Message Date
Ian Renton 05ac652cee Fix some IDE warnings 2026-06-19 19:31:56 +01:00
Ian Renton 725eb619b4 Internalise third-party dependencies 2026-06-18 20:07:42 +01:00
Ian Renton 8fc3cfa56d Fix some IDE warnings 2026-06-17 18:08:02 +01:00
Ian Renton e5b2afd765 Skip JS integrity checks since jsdelivr docs say they may re-minify sources as necessary, potentially resulting in different checksums 2026-06-17 18:02:21 +01:00
Ian Renton b725c34f7c General refactor to remove stuff being passed around the Tornado handlers when it doesn't need to be. Conditions provider presence is how handled on the JS side without needing special booleans sent to every page handler. 2026-06-09 11:06:48 +01:00
Ian Renton cd30fc765b Add an API-only mode that hides the server's web UI. Closes #111 2026-06-09 10:38:16 +01:00
Ian Renton cd40cd985d Fix keys showing as "property1" and "property2" in ionosonde_data when OpenAPI spec is rendered in HTML 2026-06-09 08:56:52 +01:00
Ian Renton 7c8b4c6bf8 Workaround to fetch ionosonde data from KC2G since the GIRO data source often seems to be down. 2026-06-06 10:29:18 +01:00
Ian Renton a1c7cc6386 Use QRZ's full formatted name (includes nickname) if available; if not try to extract the nickname along with first and surnames. Closes #110. 2026-06-06 09:04:48 +01:00
Ian Renton 72360758ac Close SSE connection nicely on navigating away from the page 2026-06-05 18:52:32 +01:00
Ian Renton 6938a8cc0a SSE server reliability improvements 2026-06-05 16:17:29 +01:00
Ian Renton f6622bb942 SSE server reliability improvements 2026-06-05 16:15:10 +01:00
Ian Renton 74caae342b SSE server reliability improvements 2026-06-05 16:11:25 +01:00
Ian Renton a2dff07c0e SSE server reliability improvements 2026-06-05 16:06:33 +01:00
77 changed files with 5626 additions and 678 deletions
+39
View File
@@ -1,6 +1,45 @@
<component name="InspectionProjectProfileManager"> <component name="InspectionProjectProfileManager">
<profile version="1.0"> <profile version="1.0">
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="Annotator" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="BadExpressionStatementJS" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="CssOverwrittenProperties" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="CssUnresolvedCustomProperty" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="CssUnusedSymbol" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="GrazieInspection" enabled="false" level="GRAMMAR_ERROR" enabled_by_default="false" />
<inspection_tool class="GrazieStyle" enabled="false" level="STYLE_SUGGESTION" enabled_by_default="false" />
<inspection_tool class="HtmlUnknownAttribute" enabled="false" level="WARNING" enabled_by_default="false">
<option name="myValues">
<value>
<list size="0" />
</value>
</option>
<option name="myCustomValuesEnabled" value="true" />
</inspection_tool>
<inspection_tool class="HtmlUnknownTag" enabled="false" level="WARNING" enabled_by_default="false">
<option name="myValues">
<value>
<list size="6">
<item index="0" class="java.lang.String" itemvalue="nobr" />
<item index="1" class="java.lang.String" itemvalue="noembed" />
<item index="2" class="java.lang.String" itemvalue="comment" />
<item index="3" class="java.lang.String" itemvalue="noscript" />
<item index="4" class="java.lang.String" itemvalue="embed" />
<item index="5" class="java.lang.String" itemvalue="script" />
</list>
</value>
</option>
<option name="myCustomValuesEnabled" value="true" />
</inspection_tool>
<inspection_tool class="HtmlUnknownTarget" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="HttpUrlsUsage" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="JSDeprecatedSymbols" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="JSIgnoredPromiseFromCall" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="JSJQueryEfficiency" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="JSUnnecessarySemicolon" enabled="false" level="WARNING" enabled_by_default="false" />
<inspection_tool class="JSUnresolvedReference" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="LanguageDetectionInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="OutdatedRequirementInspection" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false"> <inspection_tool class="SpellCheckingInspection" enabled="false" level="TYPO" enabled_by_default="false">
<option name="processCode" value="true" /> <option name="processCode" value="true" />
<option name="processLiterals" value="true" /> <option name="processLiterals" value="true" />
-6
View File
@@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptLibraryMappings">
<file url="file://$PROJECT_DIR$" libraries="{redoc.standalone}" />
</component>
</project>
+2
View File
@@ -3,8 +3,10 @@
<component name="NewModuleRootManager"> <component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$"> <content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv" /> <excludeFolder url="file://$MODULE_DIR$/.venv" />
<excludeFolder url="file://$MODULE_DIR$/webassets/vendor" />
</content> </content>
<orderEntry type="jdk" jdkName="Python 3.13 virtualenv at ~/code/spothole/.venv" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3.13 virtualenv at ~/code/spothole/.venv" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="redoc.standalone" level="application" />
</component> </component>
</module> </module>
+49 -17
View File
@@ -22,9 +22,11 @@ You can access the public version's web interface at [https://spothole.app](http
This is a Progressive Web App, so you can also "install" it to your Android or iOS device by accessing it in Chrome or Safari respectively, and following the menu-driven process for installing PWAs. This is a Progressive Web App, so you can also "install" it to your Android or iOS device by accessing it in Chrome or Safari respectively, and following the menu-driven process for installing PWAs.
You are more than welcome to use the data and the API that Spothole provides to power your own software. There are many ways to do this; see below.
## Embedding Spothole in another website ## Embedding Spothole in another website
You can embed Spothole in another website, e.g. for use as part of a ham radio custom dashboard. You can embed Spothole's web interface in another website, e.g. for use as part of a ham radio custom dashboard.
URL parameters can be used to trigger an "embedded" mode which hides the headers, footers and settings. In this mode, you provide configuration for the various filter and display options via additional URL parameters. Any settings that the user has set for Spothole are ignored. This is so that the embedding site can select, for example, their choice of dark mode or SIG filters, which will not impact how Spothole appears when the user accesses it directly. Effectively, it becomes separate to their normal Spothole settings. URL parameters can be used to trigger an "embedded" mode which hides the headers, footers and settings. In this mode, you provide configuration for the various filter and display options via additional URL parameters. Any settings that the user has set for Spothole are ignored. This is so that the embedding site can select, for example, their choice of dark mode or SIG filters, which will not impact how Spothole appears when the user accesses it directly. Effectively, it becomes separate to their normal Spothole settings.
@@ -90,11 +92,9 @@ Then edit `config.yml` in your text editor of choice to set up the software as y
By default, all outdoor programme providers are enabled, as is one cluster node and the NG3K DXpedition data. The RBN spot providers are turned off by default due to the volume of traffic from CW/RTTY/FT8 skimmers, and the APRS and Packet spot providers are off by default on the assumption that Spothole users want a spot with a human at the other end of it, but all can be easily re-enabled. By default, all outdoor programme providers are enabled, as is one cluster node and the NG3K DXpedition data. The RBN spot providers are turned off by default due to the volume of traffic from CW/RTTY/FT8 skimmers, and the APRS and Packet spot providers are off by default on the assumption that Spothole users want a spot with a human at the other end of it, but all can be easily re-enabled.
`config.yml` has some entries for QRZ.com username & password, and Clublog API keys. If provided, these allow Spothole to retrieve more information about DX spots, such as the country their callsign corresponds to. The software will work just fine without them, but you may find a few country flags etc. are less accurate or missing. Other parameters you will want to update include the base URL to your instance, and whether you want to serve a full web-based DX cluster interface or just the API endpoints for client software to use.
Clublog API keys are free, but you'll need to get your own by submitting a helpdesk ticket and explaining what you'll use it for. The admin team are happy with the rate of requests made by my Spothole server, so unless you change the source code of yours to radically increase the rate of querying Clublog, I'm sure they will be fine with your server too. `config.yml` has an entry for a Clublog API key. If provided, this will allow Spothole to retrieve some more information about DX spots. The software will work just fine without it, but you may find a few country flags etc. are less accurate or missing. Clublog API keys are free, but you'll need to get your own by submitting a helpdesk ticket and explaining what you'll use it for. The admin team are happy with the rate of requests made by my Spothole server, so unless you change the source code of yours to radically increase the rate of querying Clublog, I'm sure they will be fine with your server too.
Free QRZ.com accounts offer only limited access to the site's data via their API. You'll have to sign up for one of their "XML Data Subscriber" plans to gain access to the full data, but if you're on a free account then the software will get what information it can.
Once you're happy with the content of `config.yml`, you can proceed to running the software. Once you're happy with the content of `config.yml`, you can proceed to running the software.
@@ -246,10 +246,6 @@ To set up nginx as a reverse proxy that sits in front of Spothole, first ensure
Create a file at `/etc/nginx/sites-available/` called `spothole`. Give it the following contents, replacing `spothole.app` with the domain name on which you want to run Spothole. If you changed the port on which Spothole runs, update that on the "proxy_pass" line too. Create a file at `/etc/nginx/sites-available/` called `spothole`. Give it the following contents, replacing `spothole.app` with the domain name on which you want to run Spothole. If you changed the port on which Spothole runs, update that on the "proxy_pass" line too.
```nginx ```nginx
map $request_uri $xssorigin {
~^/api *;
}
server { server {
server_name spothole.app; server_name spothole.app;
@@ -258,21 +254,55 @@ server {
alias /var/www/html/.well-known/; alias /var/www/html/.well-known/;
} }
# SSE endpoints
location ~ ^/api/v1/(spots|alerts)/stream {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:8080;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 24h;
proxy_connect_timeout 10s;
proxy_send_timeout 24h;
proxy_set_header X-Accel-Buffering no;
proxy_hide_header Access-Control-Allow-Origin;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-store always;
add_header Content-Type text/event-stream always;
}
# Other API endpoints
location /api/ {
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://127.0.0.1:8080;
proxy_buffering on;
proxy_cache off;
proxy_read_timeout 30s;
proxy_connect_timeout 10s;
proxy_hide_header Access-Control-Allow-Origin;
add_header Access-Control-Allow-Origin * always;
add_header Cache-Control no-store always;
}
# Static assets
location / { location / {
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Connection ""; proxy_set_header Connection "";
proxy_pass http://127.0.0.1:8080; proxy_pass http://127.0.0.1:8080;
proxy_hide_header Access-Control-Allow-Origin; proxy_buffering on;
add_header Access-Control-Allow-Origin $xssorigin; proxy_read_timeout 30s;
proxy_connect_timeout 10s;
add_header Cache-Control "public, max-age=3600, must-revalidate" always;
} }
} }
``` ```
One further change you might want to make to the file above is the `add_header Access-Control-Allow-Origin` statement. This is what's used on One further change you might want to make to the file above is the `add_header Access-Control-Allow-Origin` statements. These are what's used on
my own Spothole server to make sure that other third-party web-based software can get the data from my instance, and applies to any endpoint underneath `/api`. If you want my own Spothole server to make sure that other third-party web-based software can get the data from my instance, and applies to any endpoint underneath `/api`. If you want
*your* Spothole instance to be set up the same way, so that others can write software in JavaScript that can access it, *your* Spothole instance to be set up the same way, so that others can write software in JavaScript that can access it,
leave this intact. But if you want your Spothole instance to only be usable by scripts running on the web server you write, leave this intact. But if you want your Spothole instance to only be usable by scripts running on the web server you write,
you can remove this line. (Note that this doesn't stop other people writing *non-web-based* software that accesses your you can remove these lines. (Note that this doesn't stop other people writing *non-web-based* software that accesses your
Spothole API&mdash;the enforcement of cross-origin headers only happens within the user's browser. If you need to lock your Spothole API&mdash;the enforcement of cross-origin headers only happens within the user's browser. If you need to lock your
instance down so that no-one else can access it with *any* software, that's an aspect of nginx or firewall config that you will need instance down so that no-one else can access it with *any* software, that's an aspect of nginx or firewall config that you will need
to find help with elsewhere.) to find help with elsewhere.)
@@ -318,9 +348,9 @@ To navigate your way around the source code, this list may help.
* `/webassets` - Root for static files served by the web server * `/webassets` - Root for static files served by the web server
* `/webassets/apidocs` - Contains the OpenAPI spec (`openapi.yml`) * `/webassets/apidocs` - Contains the OpenAPI spec (`openapi.yml`)
* `/webassets/css` - CSS files used by the web front-end * `/webassets/css` - CSS files used by the web front-end
* `/webassets/fa` - a copy of the FontAwesome library
* `/webassets/img` - image files used by the web front-end * `/webassets/img` - image files used by the web front-end
* `/webassets/js` - JavaScript used by the web front-end * `/webassets/js` - JavaScript used by the web front-end
* `/webassets/vendor` - Third-party libraries (CSS, JS, fonts and images)
*Miscellaneous* *Miscellaneous*
@@ -353,11 +383,13 @@ As well as being my work, I have also gratefully received feature patches from S
The project contains GeoJSON files for CQ and ITU zones, in the `/datafiles/` directory. These are MIT-licenced and, to my knowledge, created by HA8TKS for his CQ and ITU zone layers for Leaflet. The project contains GeoJSON files for CQ and ITU zones, in the `/datafiles/` directory. These are MIT-licenced and, to my knowledge, created by HA8TKS for his CQ and ITU zone layers for Leaflet.
The project contains a self-hosted copy of Font Awesome's free library, in the `/webassets/fa/` directory. This is subject to Font Awesome's licence and is not covered by the overall licence declared in the `LICENSE` file. This approach was taken in preference to using their hosted kits due to the popularity of this project exceeding the page view limit for their free hosted offering.
The project contains a set of flag icons generated using the "Noto Color Emoji" font on a Debian system, in the `/webassets/img/flags/` directory. The project contains a set of flag icons generated using the "Noto Color Emoji" font on a Debian system, in the `/webassets/img/flags/` directory.
The software uses a number of Python libraries as listed in `requirements.txt`, and a number of JavaScript libraries such as jQuery, Leaflet and Bootstrap. This project would not have been possible without these libraries, so many thanks to their developers. The software uses a number of Python libraries as listed in `requirements.txt`, and a number of JavaScript libraries. This project would not have been possible without these libraries, so many thanks to their developers.
### Third Party Libraries
A number of third-party libraries are self-hosted in the `/webassets/vendor/` directory. These files are subject to their own licences and are not covered by the overall licence declared in the `LICENSE` file.
Particular thanks go to country-files.com for providing country lookup data for amateur radio, to K0SWE for [this JSON-formatted DXCC data](https://github.com/k0swe/dxcc-json/), and to the developers of `pyhamtools` for making it easy to use country-files.com data as well as QRZ.com and Clublog lookup. Particular thanks go to country-files.com for providing country lookup data for amateur radio, to K0SWE for [this JSON-formatted DXCC data](https://github.com/k0swe/dxcc-json/), and to the developers of `pyhamtools` for making it easy to use country-files.com data as well as QRZ.com and Clublog lookup.
+1 -1
View File
@@ -12,7 +12,7 @@ class ParksNPeaks(HTTPAlertProvider):
"""Alert provider for Parks n Peaks""" """Alert provider for Parks n Peaks"""
POLL_INTERVAL_SEC = 1800 POLL_INTERVAL_SEC = 1800
ALERTS_URL = "http://parksnpeaks.org/api/ALERTS/" ALERTS_URL = "https://parksnpeaks.org/api/ALERTS/"
def __init__(self, provider_config): def __init__(self, provider_config):
super().__init__(provider_config, self.ALERTS_URL, self.POLL_INTERVAL_SEC) super().__init__(provider_config, self.ALERTS_URL, self.POLL_INTERVAL_SEC)
+12 -3
View File
@@ -6,6 +6,14 @@
# this as "N0CALL" and it shouldn't do any harm, as we're not sending anything to the various networks, only receiving. # this as "N0CALL" and it shouldn't do any harm, as we're not sending anything to the various networks, only receiving.
server-owner-callsign: "N0CALL" server-owner-callsign: "N0CALL"
# Port to open the local web server on
web-server-port: 8080
# Run in API-only mode? When enabled, the web UI is not served, only the API endpoints and the OpenAPI documentation
# page. If you are running your own Spothole instance purely to serve client software, and not wanting visitors to
# discover a full web-based cluster UI, enable this flag.
api-only-mode: false
# The base URL at which the software runs. # The base URL at which the software runs.
base-url: "http://localhost:8080" base-url: "http://localhost:8080"
@@ -187,9 +195,10 @@ solar-condition-providers:
class: "GIROIonosonde" class: "GIROIonosonde"
name: "GIRO Ionosonde Data" name: "GIRO Ionosonde Data"
enabled: true enabled: true
-
# Port to open the local web server on class: "KC2GProp"
web-server-port: 8080 name: "KC2G Propagation Data"
enabled: true
# Maximum time to keep spots and alerts in the system before deleting them. By default, one hour for spots and one week # Maximum time to keep spots and alerts in the system before deleting them. By default, one hour for spots and one week
# for alerts. # for alerts.
+1
View File
@@ -21,6 +21,7 @@ SERVER_OWNER_CALLSIGN = config["server-owner-callsign"]
WEB_SERVER_PORT = config["web-server-port"] WEB_SERVER_PORT = config["web-server-port"]
ALLOW_SPOTTING = config["allow-spotting"] ALLOW_SPOTTING = config["allow-spotting"]
WEB_UI_OPTIONS = config["web-ui-options"] WEB_UI_OPTIONS = config["web-ui-options"]
API_ONLY_MODE = config.get("api-only-mode", False)
# For ease of config, each spot provider owns its own config about whether it should be enabled by default in the web UI # For ease of config, each spot provider owns its own config about whether it should be enabled by default in the web UI
# but for consistency we provide this to the front-end in web-ui-options because it has no impact outside of the web UI. # but for consistency we provide this to the front-end in web-ui-options because it has no impact outside of the web UI.
+3 -4
View File
@@ -3,12 +3,11 @@ from data.band import Band
from data.sig import SIG from data.sig import SIG
# General software # General software
SOFTWARE_NAME = "Spothole by M0TRT" SOFTWARE_VERSION = "1.4-pre"
SOFTWARE_VERSION = "1.3"
# HTTP headers used for spot providers that use HTTP # HTTP headers used for spot providers that use HTTP
HTTP_HEADERS = {"User-Agent": SOFTWARE_NAME + ", v" + SOFTWARE_VERSION + " (operated by " + SERVER_OWNER_CALLSIGN + ")"} HTTP_HEADERS = {"User-Agent": "Spothole v" + SOFTWARE_VERSION + " (operated by " + SERVER_OWNER_CALLSIGN + ")"}
HAMQTH_PRG = (SOFTWARE_NAME + " v" + SOFTWARE_VERSION + " operated by " + SERVER_OWNER_CALLSIGN).replace(" ", "_") HAMQTH_PRG = ("Spothole v" + SOFTWARE_VERSION + " operated by " + SERVER_OWNER_CALLSIGN).replace(" ", "_")
# Special Interest Groups # Special Interest Groups
SIGS = [ SIGS = [
+4 -1
View File
@@ -18,7 +18,6 @@ from core.cache_utils import SEMI_STATIC_URL_DATA_CACHE
from core.config import config from core.config import config
from core.constants import BANDS, UNKNOWN_BAND, CW_MODES, PHONE_MODES, DATA_MODES, ALL_MODES, \ from core.constants import BANDS, UNKNOWN_BAND, CW_MODES, PHONE_MODES, DATA_MODES, ALL_MODES, \
HTTP_HEADERS, HAMQTH_PRG, MODE_ALIASES HTTP_HEADERS, HAMQTH_PRG, MODE_ALIASES
from data.lookup_credentials import LookupCredentials
# QRZ XML field names differ from pyhamtools' normalised names; map them here. # QRZ XML field names differ from pyhamtools' normalised names; map them here.
_QRZ_FIELD_MAP = { _QRZ_FIELD_MAP = {
@@ -363,8 +362,12 @@ class LookupHelper:
"""Infer an operator name from a callsign (requires QRZ.com/HamQTH)""" """Infer an operator name from a callsign (requires QRZ.com/HamQTH)"""
data = self._get_qrz_data_for_callsign(call, credentials) data = self._get_qrz_data_for_callsign(call, credentials)
if data and "name_fmt" in data:
return data["name_fmt"]
if data and "fname" in data: if data and "fname" in data:
name = data["fname"] name = data["fname"]
if "nick" in data:
name = name + " \"" + data["nick"] + "\""
if "name" in data: if "name" in data:
name = name + " " + data["name"] name = name + " " + data["name"]
return name return name
+2 -2
View File
@@ -161,8 +161,8 @@ class SolarConditions:
blackout_forecast_r1r2: dict = None blackout_forecast_r1r2: dict = None
# NOAA Radio Blackout (R3 or greater) probability forecast, keyed by UNIX timestamp of start of day UTC # NOAA Radio Blackout (R3 or greater) probability forecast, keyed by UNIX timestamp of start of day UTC
blackout_forecast_r3_or_greater: dict = None blackout_forecast_r3_or_greater: dict = None
# Ionosonde measurements from LGDC, dict keyed by URSI code, values are dicts with keys: ursi, name, fof2, muf, luf, # Ionosonde measurements, dict keyed by URSI code, values are dicts with keys: ursi, name, fof2, muf, luf,
# band_states # band_states. Populated by GIROIonosonde or KC2GProp providers.
ionosonde_data: dict = None ionosonde_data: dict = None
# Derived values (populated by infer_descriptions()) # Derived values (populated by infer_descriptions())
-1
View File
@@ -14,7 +14,6 @@ from core.constants import MODE_ALIASES
from core.geo_utils import lat_lon_to_cq_zone, lat_lon_to_itu_zone from core.geo_utils import lat_lon_to_cq_zone, lat_lon_to_itu_zone
from core.lookup_helper import lookup_helper, infer_band_from_freq, infer_mode_from_comment, \ from core.lookup_helper import lookup_helper, infer_band_from_freq, infer_mode_from_comment, \
infer_mode_from_frequency, infer_mode_type_from_mode infer_mode_from_frequency, infer_mode_type_from_mode
from data.lookup_credentials import LookupCredentials
from core.sig_utils import populate_sig_ref_info, ANY_SIG_REGEX, get_ref_regex_for_sig from core.sig_utils import populate_sig_ref_info, ANY_SIG_REGEX, get_ref_regex_for_sig
from data.sig_ref import SIGRef from data.sig_ref import SIGRef
+12 -3
View File
@@ -98,8 +98,12 @@ class APIAlertsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
self._heartbeat = tornado.ioloop.PeriodicCallback(self._callback, SSE_HANDLER_QUEUE_CHECK_INTERVAL) self._heartbeat = tornado.ioloop.PeriodicCallback(self._callback, SSE_HANDLER_QUEUE_CHECK_INTERVAL)
self._heartbeat.start() self._heartbeat.start()
# Flush headers immediately so nginx doesn't time out waiting for a response
self.write_message("keepalive", "")
except Exception as e: except Exception as e:
logging.warning("Exception when serving SSE socket", e) logging.warning("Exception when serving SSE socket: %s", e, exc_info=True)
self.close()
def close(self): def close(self):
"""When the user closes the socket, empty our queue and remove it from the list so the server no longer fills it""" """When the user closes the socket, empty our queue and remove it from the list so the server no longer fills it"""
@@ -122,6 +126,7 @@ class APIAlertsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
try: try:
if self._alert_queue: if self._alert_queue:
if not self._alert_queue.empty():
while not self._alert_queue.empty(): while not self._alert_queue.empty():
alert = self._alert_queue.get() alert = self._alert_queue.get()
# If the new alert matches our param filters, send it to the client. If not, ignore it. # If the new alert matches our param filters, send it to the client. If not, ignore it.
@@ -131,11 +136,15 @@ class APIAlertsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
alert.infer_missing(self._credentials) alert.infer_missing(self._credentials)
self.write_message(msg=json.dumps(alert, default=serialize_everything)) self.write_message(msg=json.dumps(alert, default=serialize_everything))
else:
# Send a keepalive comment if the queue was empty
self.write_message("keepalive", "")
if self._alert_queue not in self._sse_alert_queues: if self._alert_queue not in self._sse_alert_queues:
logging.error("Web server cleared up a queue of an active connection!") logging.error("Web server cleared up a queue of an active connection!")
self.close() self.close()
except: except Exception as e:
logging.warning("Exception in SSE callback, connection will be closed.") logging.warning("Exception in SSE callback, connection will be closed: %s", e, exc_info=True)
self.close() self.close()
-2
View File
@@ -1,11 +1,9 @@
import json
from datetime import datetime from datetime import datetime
import pytz import pytz
import tornado import tornado
from core.prometheus_metrics_handler import api_requests_counter from core.prometheus_metrics_handler import api_requests_counter
from core.utils import serialize_everything
class APISolarConditionsHandler(tornado.web.RequestHandler): class APISolarConditionsHandler(tornado.web.RequestHandler):
+12 -3
View File
@@ -100,8 +100,12 @@ class APISpotsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
self._heartbeat = tornado.ioloop.PeriodicCallback(self._callback, SSE_HANDLER_QUEUE_CHECK_INTERVAL) self._heartbeat = tornado.ioloop.PeriodicCallback(self._callback, SSE_HANDLER_QUEUE_CHECK_INTERVAL)
self._heartbeat.start() self._heartbeat.start()
# Flush headers immediately so nginx doesn't time out waiting for a response
self.write_message("keepalive", "")
except Exception as e: except Exception as e:
logging.warning("Exception when serving SSE socket", e) logging.warning("Exception when serving SSE socket: %s", e, exc_info=True)
self.close()
def close(self): def close(self):
"""When the user closes the socket, empty our queue and remove it from the list so the server no longer fills it""" """When the user closes the socket, empty our queue and remove it from the list so the server no longer fills it"""
@@ -124,6 +128,7 @@ class APISpotsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
try: try:
if self._spot_queue: if self._spot_queue:
if not self._spot_queue.empty():
while not self._spot_queue.empty(): while not self._spot_queue.empty():
spot = self._spot_queue.get() spot = self._spot_queue.get()
# If the new spot matches our param filters, send it to the client. If not, ignore it. # If the new spot matches our param filters, send it to the client. If not, ignore it.
@@ -133,11 +138,15 @@ class APISpotsStreamHandler(tornado_eventsource.handler.EventSourceHandler):
spot.infer_missing(self._credentials) spot.infer_missing(self._credentials)
self.write_message(msg=json.dumps(spot, default=serialize_everything)) self.write_message(msg=json.dumps(spot, default=serialize_everything))
else:
# Send a keepalive comment if the queue was empty
self.write_message("keepalive", "")
if self._spot_queue not in self._sse_spot_queues: if self._spot_queue not in self._sse_spot_queues:
logging.error("Web server cleared up a queue of an active connection!") logging.error("Web server cleared up a queue of an active connection!")
self.close() self.close()
except: except Exception as e:
logging.warning("Exception in SSE callback, connection will be closed.") logging.warning("Exception in SSE callback, connection will be closed: %s", e, exc_info=True)
self.close() self.close()
+5 -9
View File
@@ -3,7 +3,7 @@ from datetime import datetime
import pytz import pytz
import tornado import tornado
from core.config import ALLOW_SPOTTING, WEB_UI_OPTIONS, BASE_URL from core.config import ALLOW_SPOTTING, WEB_UI_OPTIONS, BASE_URL, SERVER_OWNER_CALLSIGN
from core.constants import SOFTWARE_VERSION from core.constants import SOFTWARE_VERSION
from core.prometheus_metrics_handler import page_requests_counter from core.prometheus_metrics_handler import page_requests_counter
@@ -11,12 +11,9 @@ from core.prometheus_metrics_handler import page_requests_counter
class PageTemplateHandler(tornado.web.RequestHandler): class PageTemplateHandler(tornado.web.RequestHandler):
"""Handler for all HTML pages generated from templates""" """Handler for all HTML pages generated from templates"""
def initialize(self, template_name, web_server_metrics, has_hamqsl=False, has_noaa_forecast=False, has_giro_ionosonde=False): def initialize(self, template_name, web_server_metrics):
self._template_name = template_name self._template_name = template_name
self._web_server_metrics = web_server_metrics self._web_server_metrics = web_server_metrics
self._has_hamqsl = has_hamqsl
self._has_noaa_forecast = has_noaa_forecast
self._has_giro_ionosonde = has_giro_ionosonde
def get(self): def get(self):
# Metrics # Metrics
@@ -26,7 +23,6 @@ class PageTemplateHandler(tornado.web.RequestHandler):
page_requests_counter.inc() page_requests_counter.inc()
# Load named template, and provide variables used in templates # Load named template, and provide variables used in templates
self.render(self._template_name + ".html", software_version=SOFTWARE_VERSION, allow_spotting=ALLOW_SPOTTING, self.render(self._template_name + ".html", software_version=SOFTWARE_VERSION,
web_ui_options=WEB_UI_OPTIONS, baseurl=BASE_URL, current_path=self.request.path, server_owner_callsign=SERVER_OWNER_CALLSIGN, allow_spotting=ALLOW_SPOTTING,
has_hamqsl=self._has_hamqsl, has_noaa_forecast=self._has_noaa_forecast, web_ui_options=WEB_UI_OPTIONS, baseurl=BASE_URL, current_path=self.request.path)
has_giro_ionosonde=self._has_giro_ionosonde)
+52 -42
View File
@@ -5,10 +5,11 @@ import os
import tornado import tornado
from tornado.web import StaticFileHandler from tornado.web import StaticFileHandler
from core.config import ALLOW_SPOTTING, WEB_SERVER_PORT, API_ONLY_MODE
from core.utils import empty_queue from core.utils import empty_queue
from server.handlers.api.addspot import APISpotHandler from server.handlers.api.addspot import APISpotHandler
from server.handlers.api.dxstats import APIDxStatsHandler
from server.handlers.api.alerts import APIAlertsHandler, APIAlertsStreamHandler from server.handlers.api.alerts import APIAlertsHandler, APIAlertsStreamHandler
from server.handlers.api.dxstats import APIDxStatsHandler
from server.handlers.api.lookups import APILookupCallHandler, APILookupSIGRefHandler, APILookupGridHandler from server.handlers.api.lookups import APILookupCallHandler, APILookupSIGRefHandler, APILookupGridHandler
from server.handlers.api.options import APIOptionsHandler from server.handlers.api.options import APIOptionsHandler
from server.handlers.api.solar_conditions import APISolarConditionsHandler from server.handlers.api.solar_conditions import APISolarConditionsHandler
@@ -21,7 +22,7 @@ from server.handlers.pagetemplate import PageTemplateHandler
class WebServer: class WebServer:
"""Provides the public-facing web server.""" """Provides the public-facing web server."""
def __init__(self, spots, alerts, solar_conditions, status_data, solar_condition_providers, port): def __init__(self, spots, alerts, solar_conditions, status_data):
"""Constructor""" """Constructor"""
self._spots = spots self._spots = spots
@@ -30,8 +31,8 @@ class WebServer:
self._sse_spot_queues = [] self._sse_spot_queues = []
self._sse_alert_queues = [] self._sse_alert_queues = []
self._status_data = status_data self._status_data = status_data
self._solar_condition_providers = solar_condition_providers self._port = WEB_SERVER_PORT
self._port = port self._api_only_mode = API_ONLY_MODE
self._shutdown_event = asyncio.Event() self._shutdown_event = asyncio.Event()
self.web_server_metrics = { self.web_server_metrics = {
"last_page_access_time": None, "last_page_access_time": None,
@@ -54,51 +55,60 @@ class WebServer:
async def _start_inner(self): async def _start_inner(self):
"""Start method (async). Sets up the Tornado application.""" """Start method (async). Sets up the Tornado application."""
provider_classes = [type(p).__name__ for p in self._solar_condition_providers if p.enabled] # Prepare a list of common arguments that are passed in to every API & page handler. This is just a basic thing
has_hamqsl = "HamQSL" in provider_classes # to avoid copy-pasting the same thing to every route declaration below.
has_noaa_forecast = "NOAA3dayForecast" in provider_classes handler_opts = {"web_server_metrics": self.web_server_metrics}
has_giro_ionosonde = "GIROIonosonde" in provider_classes
page_opts = {"web_server_metrics": self.web_server_metrics, "has_hamqsl": has_hamqsl,
"has_noaa_forecast": has_noaa_forecast, "has_giro_ionosonde": has_giro_ionosonde}
app = tornado.web.Application([ # API endpoints are always enabled
# Routes for API calls api_routes = [
(r"/api/v1/spots", APISpotsHandler, {"spots": self._spots, "web_server_metrics": self.web_server_metrics}), (r"/api/v1/spots", APISpotsHandler, {"spots": self._spots, **handler_opts}),
(r"/api/v1/alerts", APIAlertsHandler, (r"/api/v1/alerts", APIAlertsHandler, {"alerts": self._alerts, **handler_opts}),
{"alerts": self._alerts, "web_server_metrics": self.web_server_metrics}),
(r"/api/v1/spots/stream", APISpotsStreamHandler, (r"/api/v1/spots/stream", APISpotsStreamHandler,
{"sse_spot_queues": self._sse_spot_queues, "web_server_metrics": self.web_server_metrics}), {"sse_spot_queues": self._sse_spot_queues, **handler_opts}),
(r"/api/v1/alerts/stream", APIAlertsStreamHandler, (r"/api/v1/alerts/stream", APIAlertsStreamHandler,
{"sse_alert_queues": self._sse_alert_queues, "web_server_metrics": self.web_server_metrics}), {"sse_alert_queues": self._sse_alert_queues, **handler_opts}),
(r"/api/v1/solar", APISolarConditionsHandler, (r"/api/v1/solar", APISolarConditionsHandler, {"solar_conditions": self._solar_conditions, **handler_opts}),
{"solar_conditions": self._solar_conditions, "web_server_metrics": self.web_server_metrics}), (r"/api/v1/dxstats", APIDxStatsHandler, {"spots": self._spots, **handler_opts}),
(r"/api/v1/dxstats", APIDxStatsHandler, {"spots": self._spots, "web_server_metrics": self.web_server_metrics}), (r"/api/v1/options", APIOptionsHandler, {"status_data": self._status_data, **handler_opts}),
(r"/api/v1/options", APIOptionsHandler, (r"/api/v1/status", APIStatusHandler, {"status_data": self._status_data, **handler_opts}),
{"status_data": self._status_data, "web_server_metrics": self.web_server_metrics}), (r"/api/v1/lookup/call", APILookupCallHandler, {**handler_opts}),
(r"/api/v1/status", APIStatusHandler, (r"/api/v1/lookup/sigref", APILookupSIGRefHandler, {**handler_opts}),
{"status_data": self._status_data, "web_server_metrics": self.web_server_metrics}), (r"/api/v1/lookup/grid", APILookupGridHandler, {**handler_opts}),
(r"/api/v1/lookup/call", APILookupCallHandler, {"web_server_metrics": self.web_server_metrics}), (r"/api/v1/spot", APISpotHandler, {"spots": self._spots, **handler_opts}),
(r"/api/v1/lookup/sigref", APILookupSIGRefHandler, {"web_server_metrics": self.web_server_metrics}), ]
(r"/api/v1/lookup/grid", APILookupGridHandler, {"web_server_metrics": self.web_server_metrics}),
(r"/api/v1/spot", APISpotHandler, {"spots": self._spots, "web_server_metrics": self.web_server_metrics}), # If in API-only mode, serve a basic homepage; in normal mode, serve the usual UI routes
# Routes for templated pages if self._api_only_mode:
(r"/", PageTemplateHandler, {"template_name": "spots", **page_opts}), logging.info("API-only mode is enabled. Web UI will not be served.")
(r"/map", PageTemplateHandler, {"template_name": "map", **page_opts}), ui_routes = [
(r"/bands", PageTemplateHandler, {"template_name": "bands", **page_opts}), (r"/", PageTemplateHandler, {"template_name": "api_only_home", **handler_opts})
(r"/alerts", PageTemplateHandler, {"template_name": "alerts", **page_opts}), ]
(r"/add-spot", PageTemplateHandler, {"template_name": "add_spot", **page_opts}), else:
(r"/conditions", PageTemplateHandler, {"template_name": "conditions", **page_opts}), ui_routes = [
(r"/status", PageTemplateHandler, {"template_name": "status", **page_opts}), (r"/", PageTemplateHandler, {"template_name": "spots", **handler_opts}),
(r"/about", PageTemplateHandler, {"template_name": "about", **page_opts}), (r"/map", PageTemplateHandler, {"template_name": "map", **handler_opts}),
(r"/apidocs", PageTemplateHandler, {"template_name": "apidocs", **page_opts}), (r"/bands", PageTemplateHandler, {"template_name": "bands", **handler_opts}),
# Route for Prometheus metrics (r"/alerts", PageTemplateHandler, {"template_name": "alerts", **handler_opts}),
(r"/conditions", PageTemplateHandler, {"template_name": "conditions", **handler_opts}),
(r"/status", PageTemplateHandler, {"template_name": "status", **handler_opts}),
(r"/about", PageTemplateHandler, {"template_name": "about", **handler_opts})
]
# Only allow the Add Spot page if spotting is allowed
if ALLOW_SPOTTING:
ui_routes += [(r"/add-spot", PageTemplateHandler, {"template_name": "add_spot", **handler_opts})]
# API docs, Prometheus metrics, and finally static assets are always available regardless of API-only mode.
misc_routes = [
(r"/apidocs", PageTemplateHandler, {"template_name": "apidocs", **handler_opts}),
(r"/metrics", PrometheusMetricsHandler), (r"/metrics", PrometheusMetricsHandler),
# Default route to serve from "webassets" (r"/(.*)", StaticFileHandler, {"path": os.path.join(os.path.dirname(__file__), "../webassets")})
(r"/(.*)", StaticFileHandler, {"path": os.path.join(os.path.dirname(__file__), "../webassets")}), ]
],
app = tornado.web.Application(api_routes + ui_routes + misc_routes,
template_path=os.path.join(os.path.dirname(__file__), "../templates"), template_path=os.path.join(os.path.dirname(__file__), "../templates"),
debug=False) debug=False)
app.listen(self._port) app.listen(self._port)
logging.info("Web server running on port " + str(WEB_SERVER_PORT))
await self._shutdown_event.wait() await self._shutdown_event.wait()
def notify_new_spot(self, spot): def notify_new_spot(self, spot):
+43 -52
View File
@@ -6,19 +6,21 @@ from threading import Thread, Event
import pytz import pytz
import requests import requests
from core.constants import HTTP_HEADERS, BANDS from core.constants import HTTP_HEADERS
from solarconditionsproviders.ionosonde_utils import compute_band_states
from solarconditionsproviders.solar_conditions_provider import SolarConditionsProvider from solarconditionsproviders.solar_conditions_provider import SolarConditionsProvider
POLL_INTERVAL = 3600 # 1 hour POLL_INTERVAL = 3600 # 1 hour
STATIONS_INDEX = "datafiles/didbase-stations.csv" STATIONS_INDEX = "datafiles/didbase-stations.csv"
LGDC_URL = "https://lgdc.uml.edu/common/DIDBGetValues" LGDC_URL = "https://lgdc.uml.edu/common/DIDBGetValues"
HISTORY_HOURS = 24 HISTORY_HOURS = 24
HF_BANDS = [b for b in BANDS if b.is_ham_hf]
class GIROIonosonde(SolarConditionsProvider): class GIROIonosonde(SolarConditionsProvider):
"""Solar conditions provider using ionosonde data from the GIRO Data Center. """Solar conditions provider using ionosonde data from the GIRO Data Center.
Queries foF2, MUF, and LUF measurements for all stations in datafiles/didbase-stations.csv.""" Queries foF2, MUF, and LUF measurements for all stations in datafiles/didbase-stations.csv.
Can run alongside KC2GProp: GIRO supplements KC2G's foF2/MUF data with LUF readings, and
stations from each source that the other does not cover are preserved."""
def __init__(self, provider_config): def __init__(self, provider_config):
super().__init__(provider_config) super().__init__(provider_config)
@@ -27,8 +29,6 @@ class GIROIonosonde(SolarConditionsProvider):
self._stop_event = Event() self._stop_event = Event()
def _load_stations(self): def _load_stations(self):
"""Load the CSV file containing the list of URSIs and Station Names for currently active ionosondes."""
stations = [] stations = []
with open(STATIONS_INDEX, newline='') as f: with open(STATIONS_INDEX, newline='') as f:
for row in csv.reader(f): for row in csv.reader(f):
@@ -37,15 +37,19 @@ class GIROIonosonde(SolarConditionsProvider):
return stations return stations
def setup(self, solar_conditions, solar_conditions_cache): def setup(self, solar_conditions, solar_conditions_cache):
"""Prepopulate the ionosonde_data map with known URSI and station names, so that the API exposes this structure """Pre-populate ionosonde_data with known station names for stations not already present,
even before we actually have any data in it.""" so the station dropdown is available before the first poll. Does not overwrite existing
entries so KC2G cache data is preserved."""
super().setup(solar_conditions, solar_conditions_cache) super().setup(solar_conditions, solar_conditions_cache)
self.update_data({"ionosonde_data": { existing = solar_conditions.ionosonde_data or {}
s["ursi"]: {"ursi": s["ursi"], "name": s["name"], "fof2": None, "muf": None, "luf": None, new_entries = {
"band_states": None} s["ursi"]: {"ursi": s["ursi"], "name": s["name"], "fof2": None, "muf": None,
for s in self._stations "luf": None, "band_states": None}
}}) for s in self._stations if s["ursi"] not in existing
}
if new_entries:
self.update_data({"ionosonde_data": {**existing, **new_entries}})
def start(self): def start(self):
logging.info(f"Set up query of GIRO ionosonde data API every {POLL_INTERVAL} seconds.") logging.info(f"Set up query of GIRO ionosonde data API every {POLL_INTERVAL} seconds.")
@@ -63,9 +67,13 @@ class GIROIonosonde(SolarConditionsProvider):
def _poll(self): def _poll(self):
try: try:
logging.debug(f"Polling GIRO ionosonde data...") logging.debug("Polling GIRO ionosonde data...")
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
from_time = now - timedelta(hours=HISTORY_HOURS) from_time = now - timedelta(hours=HISTORY_HOURS)
cutoff_ts = from_time.timestamp()
# Start from the existing ionosonde_data so stations provided by other providers
# (e.g. KC2GProp) are preserved for stations GIRO does not cover.
ionosonde_data = dict(self._solar_conditions.ionosonde_data or {}) ionosonde_data = dict(self._solar_conditions.ionosonde_data or {})
updated_count = 0 updated_count = 0
@@ -76,10 +84,27 @@ class GIROIonosonde(SolarConditionsProvider):
name = station["name"] name = station["name"]
try: try:
fof2, muf, luf = self._fetch_station_data(ursi, from_time, now) fof2, muf, luf = self._fetch_station_data(ursi, from_time, now)
if fof2 and muf: if not fof2 or not muf:
band_states = self._compute_band_statess(fof2, muf, luf or {}) continue
ionosonde_data[ursi] = {"ursi": ursi, "name": name, "fof2": fof2, "muf": muf,
"luf": luf or None, "band_states": band_states} # Merge GIRO's readings into any existing data for this station.
existing = ionosonde_data.get(ursi, {})
merged_fof2 = {**{float(t): v for t, v in (existing.get("fof2") or {}).items()}, **fof2}
merged_muf = {**{float(t): v for t, v in (existing.get("muf") or {}).items()}, **muf}
merged_luf = dict(luf) if luf else {}
merged_fof2 = {t: v for t, v in merged_fof2.items() if t >= cutoff_ts}
merged_muf = {t: v for t, v in merged_muf.items() if t >= cutoff_ts}
merged_luf = {t: v for t, v in merged_luf.items() if t >= cutoff_ts}
band_states = compute_band_states(merged_fof2, merged_muf, merged_luf)
ionosonde_data[ursi] = {
"ursi": ursi, "name": name,
"fof2": merged_fof2 or None,
"muf": merged_muf or None,
"luf": merged_luf or None,
"band_states": band_states,
}
updated_count += 1 updated_count += 1
except Exception: except Exception:
logging.warning(f"Could not fetch ionosonde data for {ursi} ({name})") logging.warning(f"Could not fetch ionosonde data for {ursi} ({name})")
@@ -91,7 +116,7 @@ class GIROIonosonde(SolarConditionsProvider):
except Exception: except Exception:
self.status = "Error" self.status = "Error"
logging.exception(f"Exception in GIRO Ionosonde data provider") logging.exception("Exception in GIRO Ionosonde data provider")
self._stop_event.wait(timeout=1) self._stop_event.wait(timeout=1)
def _fetch_station_data(self, ursi, from_time, to_time): def _fetch_station_data(self, ursi, from_time, to_time):
@@ -105,40 +130,6 @@ class GIROIonosonde(SolarConditionsProvider):
return None, None, None return None, None, None
return self._parse_all(response.text) return self._parse_all(response.text)
@staticmethod
def _latest(d):
"""Return the value with the highest timestamp key, or None if the dict is empty."""
return d[max(d.keys())] if d else None
@staticmethod
def _compute_band_statess(fof2_dict, muf_dict, luf_dict):
"""Compute HF band states from the latest foF2, MUF and LUF values.
States:
Closed if band frequency is below LUF (if known) or above MUF
Short if band frequency is >= LUF and < foF2 (good for NVIS)
Long if band frequency is >= foF2 and < MUF (good for DX)
"""
# We have a list of timestamped data for each value, but for this we only want the latest value
fof2 = GIROIonosonde._latest(fof2_dict)
muf = GIROIonosonde._latest(muf_dict)
luf = GIROIonosonde._latest(luf_dict)
if fof2 is None or muf is None:
return {}
band_states = {}
# Iterate over all ham HF bands, we don't care about the others at this point
for band in HF_BANDS:
freq = band.start_freq / 1000000
if freq > muf or (luf is not None and freq < luf):
band_states[band.name] = "Closed"
elif freq < fof2:
band_states[band.name] = "Short"
else:
band_states[band.name] = "Long"
return band_states
@staticmethod @staticmethod
def _parse_all(text): def _parse_all(text):
"""Parse web server response and return (fof2_dict, muf_dict, luf_dict) keyed by UNIX timestamp.""" """Parse web server response and return (fof2_dict, muf_dict, luf_dict) keyed by UNIX timestamp."""
@@ -0,0 +1,33 @@
from core.constants import BANDS
HF_BANDS = [b for b in BANDS if b.is_ham_hf]
def _latest(d):
return d[max(d.keys())] if d else None
def compute_band_states(fof2_dict, muf_dict, luf_dict):
"""Compute HF band states from the latest foF2, MUF and LUF values.
States:
Closed if band frequency is above MUF or below LUF (if known)
Short if band frequency is >= LUF and < foF2 (good for NVIS)
Long if band frequency is >= foF2 and < MUF (good for DX)
"""
fof2 = _latest(fof2_dict)
muf = _latest(muf_dict)
luf = _latest(luf_dict) if luf_dict else None
if fof2 is None or muf is None:
return {}
band_states = {}
for band in HF_BANDS:
freq = band.start_freq / 1_000_000
if freq > muf or (luf is not None and freq < luf):
band_states[band.name] = "Closed"
elif freq < fof2:
band_states[band.name] = "Short"
else:
band_states[band.name] = "Long"
return band_states
+121
View File
@@ -0,0 +1,121 @@
import logging
from datetime import datetime, timezone, timedelta
from threading import Thread, Event
import pytz
import requests
from core.constants import HTTP_HEADERS
from solarconditionsproviders.ionosonde_utils import compute_band_states
from solarconditionsproviders.solar_conditions_provider import SolarConditionsProvider
POLL_INTERVAL = 900 # 15 minutes
KC2G_URL = "https://prop.kc2g.com/api/stations.json"
HISTORY_HOURS = 24
class KC2GProp(SolarConditionsProvider):
"""Solar conditions provider using ionosonde data from prop.kc2g.com. The API returns only the latest reading per
station, so this provider polls every 15 minutes and accumulates a 24-hour time series by merging each new reading
into the persisted ionosonde_data, producing the same data structure as GIROIonosonde.
Can run alongside GIROIonosonde: KC2G provides foF2/MUF with good reliability, while GIRO supplements with LUF
readings. Stations from each source that the other does not cover are preserved."""
def __init__(self, provider_config):
super().__init__(provider_config)
self._thread = None
self._stop_event = Event()
def start(self):
logging.info(f"Set up query of KC2G ionosonde data API every {POLL_INTERVAL} seconds.")
self._thread = Thread(target=self._run, daemon=True)
self._thread.start()
def stop(self):
self._stop_event.set()
def _run(self):
while True:
self._poll()
if self._stop_event.wait(timeout=POLL_INTERVAL):
break
def _poll(self):
try:
logging.debug("Polling KC2G ionosonde data...")
response = requests.get(KC2G_URL, headers=HTTP_HEADERS, timeout=(5, 30))
if response.status_code != 200:
logging.warning(f"KC2G ionosonde API returned HTTP {response.status_code}")
return
now = datetime.now(timezone.utc)
cutoff_ts = (now - timedelta(hours=HISTORY_HOURS)).timestamp()
# Start from existing ionosonde_data so the accumulated time series survives across polls and restarts and
# stations provided only by GIROIonosonde are not discarded
ionosonde_data = dict(self._solar_conditions.ionosonde_data or {})
updated_count = 0
for reading in response.json():
station = reading.get("station", {})
ursi = station.get("code")
name = station.get("name")
if not ursi or not name:
continue
time_str = reading.get("time")
if not time_str:
continue
try:
ts = datetime.fromisoformat(time_str)
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
ts_float = ts.timestamp()
except ValueError:
continue
# Skip readings outside our history window (some stations have months-old data)
if ts_float < cutoff_ts:
continue
fof2_val = reading.get("fof2")
muf_val = reading.get("mufd")
if fof2_val is None and muf_val is None:
continue
# Merge this reading into the existing time series for the station.
existing = ionosonde_data.get(ursi, {})
fof2_dict = dict(existing.get("fof2") or {})
muf_dict = dict(existing.get("muf") or {})
# LUF is not available from KC2G; carry forward whatever GIRO has written.
luf_dict = {float(t): v for t, v in (existing.get("luf") or {}).items()}
fof2_dict[ts_float] = fof2_val
muf_dict[ts_float] = muf_val
# Trim all series to the 24-hour window.
fof2_dict = {t: v for t, v in fof2_dict.items() if t >= cutoff_ts}
muf_dict = {t: v for t, v in muf_dict.items() if t >= cutoff_ts}
luf_dict = {t: v for t, v in luf_dict.items() if t >= cutoff_ts}
band_states = compute_band_states(fof2_dict, muf_dict, luf_dict)
ionosonde_data[ursi] = {
"ursi": ursi,
"name": name,
"fof2": fof2_dict or None,
"muf": muf_dict or None,
"luf": luf_dict or None,
"band_states": band_states,
}
updated_count += 1
self.update_data({"ionosonde_data": ionosonde_data})
self.status = "OK"
self.last_update_time = datetime.now(pytz.UTC)
logging.debug(f"Updated KC2G ionosonde data for {updated_count} stations.")
except Exception:
self.status = "Error"
logging.exception("Exception in KC2G ionosonde data provider")
self._stop_event.wait(timeout=1)
+4 -5
View File
@@ -9,8 +9,8 @@ from diskcache import Cache
from core.cleanup import CleanupTimer from core.cleanup import CleanupTimer
from data.solar_conditions import SolarConditions from data.solar_conditions import SolarConditions
from core.config import config, WEB_SERVER_PORT, SERVER_OWNER_CALLSIGN from core.config import config, SERVER_OWNER_CALLSIGN
from core.constants import SOFTWARE_NAME, SOFTWARE_VERSION from core.constants import SOFTWARE_VERSION
from core.lookup_helper import lookup_helper from core.lookup_helper import lookup_helper
from core.status_reporter import StatusReporter from core.status_reporter import StatusReporter
from server.webserver import WebServer from server.webserver import WebServer
@@ -90,7 +90,7 @@ if __name__ == '__main__':
logging.info("Starting...") logging.info("Starting...")
logging.info( logging.info(
"This is " + SOFTWARE_NAME + " version " + SOFTWARE_VERSION + ". This instance is run by " + SERVER_OWNER_CALLSIGN + ".") "This is Spothole version " + SOFTWARE_VERSION + ". This instance is run by " + SERVER_OWNER_CALLSIGN + ".")
# Shut down gracefully on SIGINT # Shut down gracefully on SIGINT
signal.signal(signal.SIGINT, shutdown) signal.signal(signal.SIGINT, shutdown)
@@ -99,8 +99,7 @@ if __name__ == '__main__':
lookup_helper.start() lookup_helper.start()
# Set up web server # Set up web server
web_server = WebServer(spots=spots, alerts=alerts, solar_conditions=solar_conditions, status_data=status_data, web_server = WebServer(spots=spots, alerts=alerts, solar_conditions=solar_conditions, status_data=status_data)
solar_condition_providers=solar_condition_providers, port=WEB_SERVER_PORT)
# Fetch, set up and start spot providers # Fetch, set up and start spot providers
for entry in config["spot-providers"]: for entry in config["spot-providers"]:
+1 -2
View File
@@ -27,7 +27,7 @@
<h4 class="mt-4">What data sources are supported?</h4> <h4 class="mt-4">What data sources are supported?</h4>
<p>Spothole can retrieve spots from: <a href="https://www.dxcluster.info/telnet/">Telnet-based DX clusters</a>, the <a href="https://www.reversebeacon.net/">Reverse Beacon Network (RBN)</a>, the <a href="https://www.aprs-is.net/">APRS Internet Service (APRS-IS)</a>, <a href="https://pota.app">POTA</a>, <a href="https://www.sota.org.uk/">SOTA</a>, <a href="https://wwff.co/">WWFF</a>, <a href="https://www.cqgma.org/">GMA</a>, <a href="https://wwbota.net/">WWBOTA</a>, <a href="http://www.hema.org.uk/">HEMA</a>, <a href="https://www.parksnpeaks.org/">Parks 'n' Peaks</a>, <a href="https://ontheair.nz">ZLOTA</a>, <a href="https://www.wota.org.uk/">WOTA</a>, <a href="https://llota.app">LLOTA</a>, <a href="https://wwtota.com">WWTOTA</a>, <a href="https://tilesontheair.com/">Tiles on the Air</a>, the <a href="https://ukpacketradio.network/">UK Packet Repeater Network</a>, and any site based on the <a href="https://github.com/nischu/xOTA">xOTA software by nischu</a>.</p> <p>Spothole can retrieve spots from: <a href="https://www.dxcluster.info/telnet/">Telnet-based DX clusters</a>, the <a href="https://www.reversebeacon.net/">Reverse Beacon Network (RBN)</a>, the <a href="https://www.aprs-is.net/">APRS Internet Service (APRS-IS)</a>, <a href="https://pota.app">POTA</a>, <a href="https://www.sota.org.uk/">SOTA</a>, <a href="https://wwff.co/">WWFF</a>, <a href="https://www.cqgma.org/">GMA</a>, <a href="https://wwbota.net/">WWBOTA</a>, <a href="http://www.hema.org.uk/">HEMA</a>, <a href="https://www.parksnpeaks.org/">Parks 'n' Peaks</a>, <a href="https://ontheair.nz">ZLOTA</a>, <a href="https://www.wota.org.uk/">WOTA</a>, <a href="https://llota.app">LLOTA</a>, <a href="https://wwtota.com">WWTOTA</a>, <a href="https://tilesontheair.com/">Tiles on the Air</a>, the <a href="https://ukpacketradio.network/">UK Packet Repeater Network</a>, and any site based on the <a href="https://github.com/nischu/xOTA">xOTA software by nischu</a>.</p>
<p>Spothole can retrieve alerts from: <a href="https://www.ng3k.com/">NG3K</a>, <a href="https://pota.app">POTA</a>, <a href="https://www.sota.org.uk/">SOTA</a>, <a href="https://wwff.co/">WWFF</a>, <a href="https://www.parksnpeaks.org/">Parks 'n' Peaks</a>, <a href="https://www.wota.org.uk/">WOTA</a> and <a href="https://www.beachesontheair.com/">BOTA</a>.</p> <p>Spothole can retrieve alerts from: <a href="https://www.ng3k.com/">NG3K</a>, <a href="https://pota.app">POTA</a>, <a href="https://www.sota.org.uk/">SOTA</a>, <a href="https://wwff.co/">WWFF</a>, <a href="https://www.parksnpeaks.org/">Parks 'n' Peaks</a>, <a href="https://www.wota.org.uk/">WOTA</a> and <a href="https://www.beachesontheair.com/">BOTA</a>.</p>
<p>Spothole can retrieve solar and propagation condition data from <a href="https://www.hamqsl.com">HamQSL</a>, the <a href="https://www.swpc.noaa.gov/">NOAA Space Weather Prediction Center</a> and the <a href="https://giro.uml.edu/">Lowell GIRO Data Center</a>.</p> <p>Spothole can retrieve solar and propagation condition data from <a href="https://www.hamqsl.com">HamQSL</a>, the <a href="https://www.swpc.noaa.gov/">NOAA Space Weather Prediction Center</a>, the <a href="https://giro.uml.edu/">Lowell GIRO Data Center</a> and <a href="https://prop.kc2g.com/">prop.kc2g.com</a> by KC2G.</p>
<p>Spothole can also perform lookups for callsign data on behalf of the user from <a href="https://qrz.com">QRZ.com</a> and <a href="https://hamqth.com">HamQTH</a>.</p> <p>Spothole can also perform lookups for callsign data on behalf of the user from <a href="https://qrz.com">QRZ.com</a> and <a href="https://hamqth.com">HamQTH</a>.</p>
<p>Note that the server owner has not necessarily enabled all these data sources. In particular it is common to disable RBN, to avoid the server being swamped with FT8 traffic, and to disable APRS-IS and UK Packet Net so that the server only displays stations where there is likely to be an operator physically present for a QSO.</p> <p>Note that the server owner has not necessarily enabled all these data sources. In particular it is common to disable RBN, to avoid the server being swamped with FT8 traffic, and to disable APRS-IS and UK Packet Net so that the server only displays stations where there is likely to be an operator physically present for a QSO.</p>
<p>Between the various data sources, the following Special Interest Groups (SIGs) are supported: Parks on the Air (POTA), Summits on the Air (SOTA), Worldwide Flora & Fauna (WWFF), Global Mountain Activity (GMA), Worldwide Bunkers on the Air (WWBOTA), HuMPs Excluding Marilyns Award (HEMA), Islands on the Air (IOTA), Mills on the Air (MOTA), the Amateur Radio Lighthouse Socirty (ARLHS), International Lighthouse Lightship Weekend (ILLW), Silos on the Air (SIOTA), World Castles Award (WCA), New Zealand on the Air (ZLOTA), Keith Roget Memorial National Parks Award (KRMNPA), Wainwrights on the Air (WOTA), Beaches on the Air (BOTA), Lagos y Lagunas On the Air (LLOTA), Towers on the Air (WWTOTA), Tiles on the Air, Worked All Britain (WAB), Worked All Ireland (WAI), and Toilets on the Air (TOTA).</p> <p>Between the various data sources, the following Special Interest Groups (SIGs) are supported: Parks on the Air (POTA), Summits on the Air (SOTA), Worldwide Flora & Fauna (WWFF), Global Mountain Activity (GMA), Worldwide Bunkers on the Air (WWBOTA), HuMPs Excluding Marilyns Award (HEMA), Islands on the Air (IOTA), Mills on the Air (MOTA), the Amateur Radio Lighthouse Socirty (ARLHS), International Lighthouse Lightship Weekend (ILLW), Silos on the Air (SIOTA), World Castles Award (WCA), New Zealand on the Air (ZLOTA), Keith Roget Memorial National Parks Award (KRMNPA), Wainwrights on the Air (WOTA), Beaches on the Air (BOTA), Lagos y Lagunas On the Air (LLOTA), Towers on the Air (WWTOTA), Tiles on the Air, Worked All Britain (WAB), Worked All Ireland (WAI), and Toilets on the Air (TOTA).</p>
@@ -69,7 +69,6 @@
<p>This software is dedicated to the memory of Tom G1PJB, SK, a friend and colleague who sadly passed away around the time I started writing it in Autumn 2025. I was looking forward to showing it to you when it was done.</p> <p>This software is dedicated to the memory of Tom G1PJB, SK, a friend and colleague who sadly passed away around the time I started writing it in Autumn 2025. I was looking forward to showing it to you when it was done.</p>
</div> </div>
<script src="/js/common.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-about").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-about").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+1 -2
View File
@@ -69,8 +69,7 @@
</div> </div>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/add-spot.js?v=1781893916"></script>
<script src="/js/add-spot.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-add-spot").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-add-spot").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+1 -2
View File
@@ -70,8 +70,7 @@
</div> </div>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/alerts.js?v=1781893916"></script>
<script src="/js/alerts.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-alerts").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-alerts").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+22
View File
@@ -0,0 +1,22 @@
{% extends "skeleton.html" %}
{% block head_extra %}
<link href="/vendor/css/bootstrap-5.3.8.min.css" rel="stylesheet">
{% end %}
{% block body %}
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="text-center mb-4">
<img src="/img/logo.png" width="192" height="60" alt="Spothole">
</div>
<div class="card">
<div class="card-body">
<p class="card-text">This server is running <strong>Spothole v{{software_version}}</strong>, and is operated by <strong>{{server_owner_callsign}}</strong>.</p>
<p class="card-text">The web UI is not available on this instance because the server is running in API-only mode, intended for use by client software rather than visitors to the website. See the <a href="/apidocs">API documentation</a> for details of how client software can interact with the server.</p>
<p class="card-text">Please see the <a href="https://git.ianrenton.com/ian/spothole#readme">README</a> for details of what Spothole is and how you can run it for yourself.</p>
</div>
</div>
</div>
</div>
</div>
{% end %}
+2 -3
View File
@@ -76,9 +76,8 @@
<script> <script>
let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %}; let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %};
</script> </script>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/spotsbandsandmap.js?v=1781893916"></script>
<script src="/js/spotsbandsandmap.js?v=1780424170"></script> <script src="/js/bands.js?v=1781893916"></script>
<script src="/js/bands.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-bands").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-bands").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+12 -22
View File
@@ -1,27 +1,19 @@
{% extends "skeleton.html" %} {% extends "skeleton.html" %}
{% block head_extra %} {% block head_extra %}
<link rel="stylesheet" href="/css/style.css?v=1780424170" type="text/css"> <link rel="stylesheet" href="/css/style.css?v=1781893916" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" <link href="/vendor/css/bootstrap-5.3.8.min.css" rel="stylesheet">
integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous"> <link href="/vendor/css/fontawesome-6.7.2.min.css" rel="stylesheet">
<link href="/fa/css/fontawesome.min.css" rel="stylesheet" /> <link href="/vendor/css/solid-6.7.2.min.css" rel="stylesheet">
<link href="/fa/css/solid.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js" <script src="/vendor/js/jquery-3.7.1.min.js"></script>
integrity="sha384-1H217gwSVyLSIfaLxHbE7dRb3v4mYCKbpQvzx0cegeju1MVsGrX5xXxAvs/HgeFs" <script src="/vendor/js/moment-2.29.4.min.js"></script>
crossorigin="anonymous"></script> <script src="/vendor/js/bootstrap-5.3.8.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js" <script src="/vendor/js/tinycolor2-1.6.0.min.js"></script>
integrity="sha384-N1xdnJwBzqfCpEDxEeSQzv4NPVPViBQq2NLbzth3YA1pLvR9mtf+TV5g6O+KLkPY"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"
integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/tinycolor2@1.6.0/cjs/tinycolor.min.js"
integrity="sha384-L1eE4eD41kpBIWe2I0eHy+GnEUC4RIpcvibVW2JCminuPlTl+2Bc528iPdVMg5Dn"
crossorigin="anonymous"></script>
<script src="https://misc.ianrenton.com/jsutils/utils.js?v=1780424170"></script> <script src="/js/utils.js?v=1781893916"></script>
<script src="https://misc.ianrenton.com/jsutils/ui-ham.js?v=1780424170"></script> <script src="/js/ui-ham.js?v=1781893916"></script>
<script src="https://misc.ianrenton.com/jsutils/geo.js?v=1780424170"></script> <script src="/js/geo.js?v=1781893916"></script>
<script src="/js/common.js?v=1781893916"></script>
{% end %} {% end %}
{% block body %} {% block body %}
<div class="container"> <div class="container">
@@ -42,9 +34,7 @@
{% if allow_spotting %} {% if allow_spotting %}
<li class="nav-item ms-4"><a href="/add-spot" class="nav-link" id="nav-link-add-spot"><i class="fa-solid fa-comment"></i> Add&nbsp;Spot</a></li> <li class="nav-item ms-4"><a href="/add-spot" class="nav-link" id="nav-link-add-spot"><i class="fa-solid fa-comment"></i> Add&nbsp;Spot</a></li>
{% end %} {% end %}
{% if has_hamqsl or has_noaa_forecast %}
<li class="nav-item ms-4"><a href="/conditions" class="nav-link" id="nav-link-conditions"><i class="fa-solid fa-sun"></i> Conditions</a></li> <li class="nav-item ms-4"><a href="/conditions" class="nav-link" id="nav-link-conditions"><i class="fa-solid fa-sun"></i> Conditions</a></li>
{% end %}
<li class="nav-item ms-4"><a href="/status" class="nav-link" id="nav-link-status"><i class="fa-solid fa-chart-simple"></i> Status</a></li> <li class="nav-item ms-4"><a href="/status" class="nav-link" id="nav-link-status"><i class="fa-solid fa-chart-simple"></i> Status</a></li>
<li class="nav-item ms-4"><a href="/about" class="nav-link" id="nav-link-about"><i class="fa-solid fa-circle-info"></i> About</a></li> <li class="nav-item ms-4"><a href="/about" class="nav-link" id="nav-link-about"><i class="fa-solid fa-circle-info"></i> About</a></li>
<li class="nav-item ms-4"><a href="/apidocs" class="nav-link" id="nav-link-api"><i class="fa-solid fa-gear"></i> API</a></li> <li class="nav-item ms-4"><a href="/apidocs" class="nav-link" id="nav-link-api"><i class="fa-solid fa-gear"></i> API</a></li>
+34 -22
View File
@@ -1,8 +1,8 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
{% if has_hamqsl %} <div id="hamqsl-section" style="display:none">
<div class="card mt-5"> <div class="card mt-5">
<div class="card-header"> <div class="card-header">
Propagation Conditions Propagation Conditions
</div> </div>
@@ -82,9 +82,9 @@
</div> </div>
<div class="form-text mt-3">Data from <a href="https://hamqsl.com">HamQSL.com</a>.</div> <div class="form-text mt-3">Data from <a href="https://hamqsl.com">HamQSL.com</a>.</div>
</div> </div>
</div> </div>
<div class="card mt-5"> <div class="card mt-5">
<div class="card-header"> <div class="card-header">
Solar Weather Solar Weather
</div> </div>
@@ -126,16 +126,17 @@
</div> </div>
<div class="row border-bottom align-items-start me-0"> <div class="row border-bottom align-items-start me-0">
<div class="col-12 col-md-2 fw-bold py-2">Electron Flux</div> <div class="col-12 col-md-2 fw-bold py-2">Electron Flux</div>
<div id="sw-electron-vals" class="col-12 col-md-3 py-2"><strong id="sw-electron-flux"></strong> efu</div> <div id="sw-electron-vals" class="col-12 col-md-3 py-2"><strong id="sw-electron-flux"></strong> efu
</div>
<div id="sw-electron-desc" class="col-12 col-md-7 py-2"></div> <div id="sw-electron-desc" class="col-12 col-md-7 py-2"></div>
</div> </div>
<div class="form-text mt-3">Data from <a href="https://hamqsl.com">HamQSL.com</a>.</div> <div class="form-text mt-3">Data from <a href="https://hamqsl.com">HamQSL.com</a>.</div>
</div> </div>
</div>
</div> </div>
{% end %}
{% if has_noaa_forecast %} <div id="noaa-section" style="display:none">
<div class="card mt-5"> <div class="card mt-5">
<div class="card-header"> <div class="card-header">
Solar Weather Forecast Solar Weather Forecast
</div> </div>
@@ -170,11 +171,11 @@
Center</a>. Center</a>.
</div> </div>
</div> </div>
</div>
</div> </div>
{% end %}
{% if has_giro_ionosonde %} <div id="ionosonde-section" style="display:none">
<div class="card mt-5"> <div class="card mt-5">
<div class="card-header"> <div class="card-header">
Ionosonde Data Ionosonde Data
</div> </div>
@@ -186,33 +187,45 @@
</select> </select>
</div> </div>
<div id="ionosonde-latest" class="mb-3"> <div id="ionosonde-latest" class="mb-3">
<div id="ionosonde-no-data" class="alert alert-warning mt-2 mb-0 py-2 js-hidden">No data available for this station.</div> <div id="ionosonde-no-data" class="alert alert-warning mt-2 mb-0 py-2 js-hidden">No data available for
this station.
</div>
<div id="ionosonde-data-rows" class="js-hidden"> <div id="ionosonde-data-rows" class="js-hidden">
<div class="row align-items-center me-0"> <div class="row align-items-center me-0">
<div class="col-12 py-2 text-muted">Latest values as of <span id="ionosonde-latest-time"></span></div> <div class="col-12 py-2 text-muted">Latest values as of <span id="ionosonde-latest-time"></span>
</div>
</div> </div>
<div class="row align-items-center me-0"> <div class="row align-items-center me-0">
<div class="col-12 col-md-4 py-2">LUF: <strong id="ionosonde-latest-luf"></strong></div> <div class="col-12 col-md-4 py-2">LUF: <strong id="ionosonde-latest-luf"></strong></div>
<div class="col-12 col-md-4 py-2">foF2: <strong id="ionosonde-latest-fof2"></strong></div> <div class="col-12 col-md-4 py-2">foF2: <strong id="ionosonde-latest-fof2"></strong></div>
<div class="col-12 col-md-4 py-2">MUF (3000 km): <strong id="ionosonde-latest-muf"></strong></div> <div class="col-12 col-md-4 py-2">MUF (3000 km): <strong id="ionosonde-latest-muf"></strong>
</div>
</div>
<div id="ionosonde-stale-warning" class="alert alert-warning mt-2 mb-0 py-2 js-hidden">Data is more
than 12 hours old!
</div> </div>
<div id="ionosonde-stale-warning" class="alert alert-warning mt-2 mb-0 py-2 js-hidden">Data is more than 12 hours old!</div>
</div> </div>
</div> </div>
<div id="ionosonde-band-state" class="mb-3 js-hidden"> <div id="ionosonde-band-state" class="mb-3 js-hidden">
<table class="table table-sm table-bordered mb-0 d-none d-md-table table-fixed-on-desktop"> <table class="table table-sm table-bordered mb-0 d-none d-md-table table-fixed-on-desktop">
<thead><tr id="ionosonde-band-state-head"></tr></thead> <thead>
<tbody><tr id="ionosonde-band-state-row"></tr></tbody> <tr id="ionosonde-band-state-head"></tr>
</thead>
<tbody>
<tr id="ionosonde-band-state-row"></tr>
</tbody>
</table> </table>
<table class="table table-sm table-bordered mb-0 d-md-none"> <table class="table table-sm table-bordered mb-0 d-md-none">
<tbody id="ionosonde-band-state-body"></tbody> <tbody id="ionosonde-band-state-body"></tbody>
</table> </table>
</div> </div>
<canvas id="ionosonde-chart" class="mt-3 mb-3 hideonmobile"></canvas> <canvas id="ionosonde-chart" class="mt-3 mb-3 hideonmobile"></canvas>
<div class="form-text mt-2">Data from the <a href="https://lgdc.uml.edu/">Lowell GIRO Data Center</a>.</div> <div class="form-text mt-2">Data from the <a href="https://lgdc.uml.edu/">Lowell GIRO Data Center</a> and/or
<a href="https://prop.kc2g.com/">KC2G</a>.
</div>
</div>
</div> </div>
</div> </div>
{% end %}
<div class="card mt-5"> <div class="card mt-5">
<div class="card-header"> <div class="card-header">
@@ -270,9 +283,8 @@
</div> </div>
</div> </div>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.9/dist/chart.umd.min.js"></script> <script src="/vendor/js/chart-4.4.9.umd.min.js"></script>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/conditions.js?v=1781893916"></script>
<script src="/js/conditions.js?v=1780424170"></script>
<script>$(document).ready(function () { <script>$(document).ready(function () {
$("#nav-link-conditions").addClass("active"); $("#nav-link-conditions").addClass("active");
}); <!-- highlight active page in nav --></script> }); <!-- highlight active page in nav --></script>
+16 -17
View File
@@ -76,27 +76,26 @@
</div> </div>
</div> </div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.css"> <link rel="stylesheet" href="/vendor/css/leaflet-1.9.4.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-extra-markers@1.2.2/dist/css/leaflet.extra-markers.min.css"> <link rel="stylesheet" href="/vendor/css/leaflet-extra-markers-1.2.2.min.css">
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.min.js"></script> <script src="/vendor/js/leaflet-1.9.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/overlapping-marker-spiderfier-leaflet/dist/oms.min.js"></script> <script src="/vendor/js/oms-leaflet-0.2.7.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-providers@2.0.0/leaflet-providers.min.js"></script> <script src="/vendor/js/leaflet-providers-2.0.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-extra-markers@1.2.2/src/assets/js/leaflet.extra-markers.min.js" type="module"></script> <script src="/vendor/js/leaflet-extra-markers-1.2.2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet.geodesic"></script> <script src="/vendor/js/leaflet-geodesic-2.7.2.umd.min.js"></script>
<script src="https://unpkg.com/leaflet.vectorgrid@latest/dist/Leaflet.VectorGrid.js"></script> <script src="/vendor/js/leaflet-vectorgrid-1.3.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/text-image/dist/text-image.js"></script> <script src="/vendor/js/text-image-0.7.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@joergdietrich/leaflet.terminator@1.1.0/L.Terminator.min.js"></script> <script src="/vendor/js/leaflet-terminator-1.1.0.min.js"></script>
<script src="https://ianrenton.github.io/Leaflet.Maidenhead/src/L.Maidenhead.js"></script> <script src="/vendor/js/leaflet-maidenhead.js"></script>
<script src="https://ha8tks.github.io/Leaflet.ITUzones/src/L.ITUzones.js"></script> <script src="/vendor/js/leaflet-ituzones.js"></script>
<script src="https://ha8tks.github.io/Leaflet.CQzones/src/L.CQzones.js"></script> <script src="/vendor/js/leaflet-cqzones.js"></script>
<script src="https://misc.ianrenton.com/Leaflet.WorkedAllBritainIreland/L.WorkedAllBritainIreland.js"></script> <script src="/vendor/js/leaflet-workedallbritainireland.js"></script>
<script> <script>
let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %}; let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %};
</script> </script>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/spotsbandsandmap.js?v=1781893916"></script>
<script src="/js/spotsbandsandmap.js?v=1780424170"></script> <script src="/js/map.js?v=1781893916"></script>
<script src="/js/map.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-map").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-map").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+2 -3
View File
@@ -104,9 +104,8 @@
<script> <script>
let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %}; let spotProvidersEnabledByDefault = {% raw json_encode(web_ui_options["spot-providers-enabled-by-default"]) %};
</script> </script>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/spotsbandsandmap.js?v=1781893916"></script>
<script src="/js/spotsbandsandmap.js?v=1780424170"></script> <script src="/js/spots.js?v=1781893916"></script>
<script src="/js/spots.js?v=1780424170"></script>
<script>$(document).ready(function() { $("#nav-link-spots").addClass("active"); }); <!-- highlight active page in nav --></script> <script>$(document).ready(function() { $("#nav-link-spots").addClass("active"); }); <!-- highlight active page in nav --></script>
{% end %} {% end %}
+1 -2
View File
@@ -59,8 +59,7 @@
</div> </div>
</div> </div>
<script src="/js/common.js?v=1780424170"></script> <script src="/js/status.js?v=1781893916"></script>
<script src="/js/status.js?v=1780424170"></script>
<script> <script>
$(document).ready(function() { $("#nav-link-status").addClass("active"); }); <!-- highlight active page in nav --> $(document).ready(function() { $("#nav-link-status").addClass("active"); }); <!-- highlight active page in nav -->
</script> </script>
+28
View File
@@ -11,6 +11,8 @@ info:
Please note that the data coming out of Spothole is only as good as the data going in. People mis-hear and make typos when spotting callsigns all the time, and there are plenty of areas where Spothole's location data may be inaccurate. If you are doing something where accuracy is important, such as contesting, you should not rely on Spothole's data to fill in any gaps in your log. Please note that the data coming out of Spothole is only as good as the data going in. People mis-hear and make typos when spotting callsigns all the time, and there are plenty of areas where Spothole's location data may be inaccurate. If you are doing something where accuracy is important, such as contesting, you should not rely on Spothole's data to fill in any gaps in your log.
Spothole's source code is located at https://git.ianrenton.com/ian/spothole and the README there provides setup instructions if you would like to run your own copy. A demonstration server of Spothole is located at https://spothole.app.
## Changelog ## Changelog
### 1.3 ### 1.3
@@ -1377,6 +1379,32 @@ components:
included, but not all of them may contain data. included, but not all of them may contain data.
additionalProperties: additionalProperties:
$ref: '#/components/schemas/IonosondeStation' $ref: '#/components/schemas/IonosondeStation'
example:
DB049:
ursi: DB049
name: Dourbes
fof2:
"1747267201.0": 7.45
"1747267501.0": 7.50
muf:
"1747267201.0": 21.66
"1747267501.0": 21.80
luf:
"1747267201.0": 2.10
"1747267501.0": 2.05
band_states:
"160m": Closed
"80m": Short
"40m": Long
"20m": Long
"10m": Closed
EA036:
ursi: EA036
name: Chilton
fof2: null
muf: null
luf: null
band_states: null
IonosondeStation: IonosondeStation:
type: object type: object
+4 -4
View File
@@ -90,7 +90,7 @@ input#search {
i#searchicon { i#searchicon {
position: absolute; position: absolute;
left: 0rem; left: 0;
top: 2px; top: 2px;
padding: 10px; padding: 10px;
pointer-events: none; pointer-events: none;
@@ -184,7 +184,7 @@ tr.new td {
background-color: var(--bs-success-border-subtle); background-color: var(--bs-success-border-subtle);
} }
100% { 100% {
background-color: intial; background-color: initial;
} }
} }
@@ -217,7 +217,7 @@ div#map {
} }
.leaflet-container { .leaflet-container {
font-family: var(--bs-body-font-family) !important; font-family: var(--bs-body-font-family) sans-serif !important;
} }
.leaflet-control-attribution { .leaflet-control-attribution {
background: none; background: none;
@@ -355,7 +355,7 @@ div.band-spot:hover span.band-spot-info {
/* GENERAL MOBILE SUPPORT */ /* GENERAL MOBILE SUPPORT */
@media (max-width: 991.99px) { @media (max-width: 991px) {
/* General "hide this on mobile" class */ /* General "hide this on mobile" class */
.hideonmobile { .hideonmobile {
display: none !important; display: none !important;
+19 -19
View File
@@ -33,44 +33,44 @@ function addSpot() {
saveSettings(); saveSettings();
// Unpack the user's entered values // Unpack the user's entered values
var dx = $("#dx-call").val().toUpperCase(); const dx = $("#dx-call").val().toUpperCase();
var freqStr = $("#freq").val(); const freqStr = $("#freq").val();
var mode = $("#mode")[0].value; const mode = $("#mode")[0].value;
var sig = $("#sig")[0].value; const sig = $("#sig")[0].value;
var sigRef = $("#sig-ref").val(); const sigRef = $("#sig-ref").val();
var dxGrid = $("#dx-grid").val(); const dxGrid = $("#dx-grid").val();
var comment = $("#comment").val(); const comment = $("#comment").val();
var de = $("#de-call").val().toUpperCase(); const de = $("#de-call").val().toUpperCase();
var spot = {} const spot = {};
if (dx != "") { if (dx !== "") {
spot["dx_call"] = dx; spot["dx_call"] = dx;
} else { } else {
showAddSpotError("A DX callsign is required in order to spot."); showAddSpotError("A DX callsign is required in order to spot.");
return; return;
} }
if (freqStr != "") { if (freqStr !== "") {
spot["freq"] = parseFloat(freqStr) * 1000; spot["freq"] = parseFloat(freqStr) * 1000;
} else { } else {
showAddSpotError("A frequency is required in order to spot."); showAddSpotError("A frequency is required in order to spot.");
return; return;
} }
if (mode != "") { if (mode !== "") {
spot["mode"] = mode; spot["mode"] = mode;
} }
if (sig != "") { if (sig !== "") {
spot["sig"] = sig; spot["sig"] = sig;
} }
if (sigRef != "") { if (sigRef !== "") {
spot["sig_refs"] = [{id: sigRef}]; spot["sig_refs"] = [{id: sigRef}];
} }
if (dxGrid != "") { if (dxGrid !== "") {
spot["dx_grid"] = dxGrid; spot["dx_grid"] = dxGrid;
} }
if (comment != "") { if (comment !== "") {
spot["comment"] = comment; spot["comment"] = comment;
} }
if (de != "") { if (de !== "") {
spot["de_call"] = de; spot["de_call"] = de;
} else { } else {
showAddSpotError("A spotter callsign is required in order to spot."); showAddSpotError("A spotter callsign is required in order to spot.");
@@ -83,7 +83,7 @@ function addSpot() {
contentType : 'application/json', contentType : 'application/json',
type : 'POST', type : 'POST',
timeout: 10000, timeout: 10000,
success: async function (result) { success: async function() {
$("#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-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(""); $("#result-bad").html("");
setTimeout(() => { setTimeout(() => {
@@ -103,7 +103,7 @@ function addSpot() {
// Show an "add spot" error. // Show an "add spot" error.
function showAddSpotError(text) { function showAddSpotError(text) {
var div = $("<div class='alert alert-danger alert-dismissible fade show mb-0 mt-4' role='alert'></div>"); 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("<i class='fa-solid fa-triangle-exclamation'></i> ");
div.append(document.createTextNode(text)); div.append(document.createTextNode(text));
div.append("<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>"); div.append("<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>");
+61 -61
View File
@@ -2,7 +2,7 @@
const REFRESH_INTERVAL_SEC = 60 * 10; const REFRESH_INTERVAL_SEC = 60 * 10;
// Storage for the alert data that the server gives us. // Storage for the alert data that the server gives us.
var alerts = [] let alerts = [];
// Load alerts and populate the table. // Load alerts and populate the table.
function loadAlerts() { function loadAlerts() {
@@ -19,15 +19,15 @@ function loadAlerts() {
// Build a query string for the API, based on the filters that the user has selected. // Build a query string for the API, based on the filters that the user has selected.
function buildQueryString(includeCredentials) { function buildQueryString(includeCredentials) {
var str = "?"; let str = "?";
["dx_continent", "source"].forEach(fn => { ["dx_continent", "source"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) { if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&"; str = str + getQueryStringFor(fn) + "&";
} }
}); });
str = str + "limit=" + $("#alerts-to-fetch option:selected").val(); str = str + "limit=" + $("#alerts-to-fetch option:selected").val();
var maxDur = $("#max-duration option:selected").val(); const maxDur = $("#max-duration option:selected").val();
if (maxDur != "9999999999") { if (maxDur !== "9999999999") {
str = str + "&max_duration=" + maxDur; str = str + "&max_duration=" + maxDur;
} }
if ($("#dxpeditions_skip_max_duration_check")[0].checked) { if ($("#dxpeditions_skip_max_duration_check")[0].checked) {
@@ -42,16 +42,16 @@ function buildQueryString(includeCredentials) {
// Update the alerts table // Update the alerts table
function updateTable() { function updateTable() {
// Use local time instead of UTC? // Use local time instead of UTC?
var useLocalTime = $("#timeZone")[0].value == "local"; const useLocalTime = $("#timeZone")[0].value === "local";
// Table data toggles // Table data toggles
var showStartTime = $("#tableShowStartTime")[0].checked; const showStartTime = $("#tableShowStartTime")[0].checked;
var showEndTime = $("#tableShowEndTime")[0].checked; const showEndTime = $("#tableShowEndTime")[0].checked;
var showDX = $("#tableShowDX")[0].checked; const showDX = $("#tableShowDX")[0].checked;
var showFreqsModes = $("#tableShowFreqsModes")[0].checked; const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
var showComment = $("#tableShowComment")[0].checked; const showComment = $("#tableShowComment")[0].checked;
var showSource = $("#tableShowSource")[0].checked; const showSource = $("#tableShowSource")[0].checked;
var showRef = $("#tableShowRef")[0].checked; const showRef = $("#tableShowRef")[0].checked;
// Populate table with headers // Populate table with headers
let table = $("#table"); let table = $("#table");
@@ -83,10 +83,10 @@ function updateTable() {
// Split alerts into three types, each of which will get its own table header: On now, next 24h, and later. "On now" // 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 // 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. // last hour.
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()) 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())); || ((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()));
next24h = alerts.filter(a => moment.unix(a["start_time"]).utc().isSameOrAfter() && moment.unix(a["start_time"]).utc().subtract(24, 'hours').isBefore()); const 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()); const later = alerts.filter(a => moment.unix(a["start_time"]).utc().subtract(24, 'hours').isSameOrAfter());
if (onNow.length > 0) { if (onNow.length > 0) {
table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">On Now</td></tr>'); table.find('tbody').append('<tr><td colspan="100" class="bg-primary-subtle" style="text-align:center;">On Now</td></tr>');
@@ -103,14 +103,14 @@ function updateTable() {
addAlertRowsToTable(table.find('tbody'), later); addAlertRowsToTable(table.find('tbody'), later);
} }
if (onNow.length == 0 && next24h.length == 0 && later.length == 0) { 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>'); 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 // Add a row to tbody for each alert in the provided list
function addAlertRowsToTable(tbody, alerts) { function addAlertRowsToTable(tbody, alerts) {
var count = 0; let count = 0;
alerts.forEach(a => { alerts.forEach(a => {
// Create row // Create row
let $tr = $('<tr>'); let $tr = $('<tr>');
@@ -118,29 +118,29 @@ function addAlertRowsToTable(tbody, alerts) {
// Apply striping to the table. We can't just use Bootstrap's table-striped class because we have all sorts of // 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 // 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. // which cause the table-striped colouring to go awry.
if (count % 2 == 1) { if (count % 2 === 1) {
$tr.addClass("table-active"); $tr.addClass("table-active");
} }
// Use local time instead of UTC? // Use local time instead of UTC?
var useLocalTime = $("#timeZone")[0].value == "local"; const useLocalTime = $("#timeZone")[0].value === "local";
// Table data toggles // Table data toggles
var showStartTime = $("#tableShowStartTime")[0].checked; const showStartTime = $("#tableShowStartTime")[0].checked;
var showEndTime = $("#tableShowEndTime")[0].checked; const showEndTime = $("#tableShowEndTime")[0].checked;
var showDX = $("#tableShowDX")[0].checked; const showDX = $("#tableShowDX")[0].checked;
var showFreqsModes = $("#tableShowFreqsModes")[0].checked; const showFreqsModes = $("#tableShowFreqsModes")[0].checked;
var showComment = $("#tableShowComment")[0].checked; const showComment = $("#tableShowComment")[0].checked;
var showSource = $("#tableShowSource")[0].checked; const showSource = $("#tableShowSource")[0].checked;
var showRef = $("#tableShowRef")[0].checked; const showRef = $("#tableShowRef")[0].checked;
// Get times for the alert, and convert to local time if necessary. // Get times for the alert, and convert to local time if necessary.
var start_time_utc = moment.unix(a["start_time"]).utc(); const start_time_utc = moment.unix(a["start_time"]).utc();
var start_time_local = start_time_utc.clone().local(); const start_time_local = start_time_utc.clone().local();
start_time = useLocalTime ? start_time_local : start_time_utc; const start_time = useLocalTime ? start_time_local : start_time_utc;
var end_time_utc = moment.unix(a["end_time"]).utc(); const end_time_utc = moment.unix(a["end_time"]).utc();
var end_time_local = end_time_utc.clone().local(); const end_time_local = end_time_utc.clone().local();
end_time = useLocalTime ? end_time_local : end_time_utc; 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 // 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. // different year to the current year, in which case the year is inserted between month and hour.
@@ -150,22 +150,22 @@ function addAlertRowsToTable(tbody, alerts) {
// Overriding all of that, if the start time is 00:00 and the end time is 23:59 when considered in UTC, the // 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. // 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. // Finally, if there is no end date set, "---" is displayed.
var whole_days = start_time_utc.format("HH:mm") == "00:00" && const whole_days = start_time_utc.format("HH:mm") === "00:00" &&
(end_time_utc != null || end_time_utc > 0 || end_time_utc.format("HH:mm") == "23:59"); (end_time_utc === 0 || end_time_utc.format("HH:mm") === "23:59");
var hours_minutes_format = whole_days ? "" : " HH:mm"; const hours_minutes_format = whole_days ? "" : " HH:mm";
var start_time_formatted = start_time.format("D MMM" + hours_minutes_format); let start_time_formatted = start_time.format("D MMM" + hours_minutes_format);
if (start_time.format("YYYY") != moment().format("YYYY")) { if (start_time.format("YYYY") !== moment().format("YYYY")) {
start_time_formatted = start_time.format("D MMM YYYY" + hours_minutes_format); 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")) { } else if (useLocalTime && start_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
start_time_formatted = start_time.format("[Today]" + hours_minutes_format); start_time_formatted = start_time.format("[Today]" + hours_minutes_format);
} }
var end_time_formatted = "---"; let end_time_formatted = "---";
if (end_time_utc != null && end_time_utc > 0 && end_time != null) { if (end_time_utc > 0 && end_time != null) {
var end_time_formatted = whole_days ? start_time_formatted : end_time.format("HH:mm"); 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("D MMM") !== start_time.format("D MMM")) {
if (end_time.format("YYYY") != moment().format("YYYY")) { if (end_time.format("YYYY") !== moment().format("YYYY")) {
end_time_formatted = end_time.format("D MMM YYYY" + hours_minutes_format); 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")) { } else if (useLocalTime && end_time.format("D MMM YYYY") === moment().format("D MMM YYYY")) {
end_time_formatted = end_time.format("[Today]" + hours_minutes_format); end_time_formatted = end_time.format("[Today]" + hours_minutes_format);
} else { } else {
end_time_formatted = end_time.format("D MMM" + hours_minutes_format); end_time_formatted = end_time.format("D MMM" + hours_minutes_format);
@@ -174,52 +174,52 @@ function addAlertRowsToTable(tbody, alerts) {
} }
// Format dx country // Format dx country
var dx_country = a["dx_country"] let dx_country = a["dx_country"];
if (dx_country == null) { if (dx_country == null) {
dx_country = "Unknown or not a country" dx_country = "Unknown or not a country"
} }
// Format DX flag // Format DX flag
var dx_flag = "<i class='fa-solid fa-globe-africa'></i>"; 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) { if (a["dx_dxcc_id"] && a["dx_dxcc_id"] != null && a["dx_dxcc_id"] !== 0) {
dx_flag = `<img src="img/flags/${a['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`; dx_flag = `<img src="img/flags/${a['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`;
} }
// Format dx calls // Format dx calls
var dx_calls_html = ""; let dx_calls_html = "";
if (a["dx_calls"] != null) { 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(", "); 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 // Format DXpedition country
var dx_country_html = ""; let dx_country_html = "";
if (a["is_dxpedition"] == true && a["dx_country"] != null && a["dx_country"] != "") { if (a["is_dxpedition"] === true && a["dx_country"] != null && a["dx_country"] !== "") {
dx_country_html = `<br/>${a["dx_country"]}`; dx_country_html = `<br/>${a["dx_country"]}`;
} }
// Format freqs & modes // Format freqs & modes
var freqsModesText = ""; let freqsModesText = "";
if (a["freqs_modes"] != null) { if (a["freqs_modes"] != null) {
freqsModesText = escapeHtml(a["freqs_modes"]); freqsModesText = escapeHtml(a["freqs_modes"]);
} }
// Format comment // Format comment
var commentText = ""; let commentText = "";
if (a["comment"] != null) { if (a["comment"] != null) {
commentText = escapeHtml(a["comment"]); commentText = escapeHtml(a["comment"]);
} }
// Sig or fallback to source // Sig or fallback to source
var sigSourceText = a["source"]; let sigSourceText = a["source"];
if (a["sig"]) { if (a["sig"]) {
sigSourceText = a["sig"]; sigSourceText = a["sig"];
} }
// Format sig_refs // Format sig_refs
var sig_refs = ""; let sig_refs = "";
if (a["sig_refs"] != null) { if (a["sig_refs"] != null) {
var items = [] const items = [];
for (var i = 0; i < a["sig_refs"].length; i++) { for (let i = 0; i < a["sig_refs"].length; i++) {
if (a["sig_refs"][i]["url"] != null) { 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>` 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 { } else {
@@ -254,11 +254,11 @@ function addAlertRowsToTable(tbody, alerts) {
tbody.append($tr); tbody.append($tr);
// Second row for mobile view only, containing source, ref, freqs/modes & comment // Second row for mobile view only, containing source, ref, freqs/modes & comment
$tr2 = $("<tr class='hidenotonmobile'>"); const $tr2 = $("<tr class='hidenotonmobile'>");
if (count % 2 == 1) { if (count % 2 === 1) {
$tr2.addClass("table-active"); $tr2.addClass("table-active");
} }
$td2 = $("<td colspan='100'>"); const $td2 = $("<td colspan='100'>");
if (showSource) { if (showSource) {
$td2.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> `); $td2.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(a["sig"], "fa-globe-africa")}'></i></span> `);
} }
@@ -319,7 +319,7 @@ $(document).ready(function() {
// Reload alerts on becoming visible. This forces a refresh when used as a PWA and the user switches back to the PWA // 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. // after some time has passed with it in the background.
addEventListener("visibilitychange", (event) => { addEventListener("visibilitychange", () => {
if (!document.hidden) { if (!document.hidden) {
loadAlerts(); loadAlerts();
} }
+20 -21
View File
@@ -25,7 +25,7 @@ function loadSpots() {
// Build a query string for the API, based on the filters that the user has selected. // Build a query string for the API, based on the filters that the user has selected.
function buildQueryString(includeCredentials) { function buildQueryString(includeCredentials) {
var str = "?"; let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => { ["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) { if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&"; str = str + getQueryStringFor(fn) + "&";
@@ -43,7 +43,7 @@ function buildQueryString(includeCredentials) {
// Update the bands display // Update the bands display
function updateBands() { function updateBands() {
// Stop here if nothing to display // Stop here if nothing to display
var bandsContainer = $("#bands-container"); const bandsContainer = $("#bands-container");
if (spots.length === 0) { if (spots.length === 0) {
bandsContainer.html("<div class='alert alert-danger' role='alert'>No spots match your filters.</div>"); bandsContainer.html("<div class='alert alert-danger' role='alert'>No spots match your filters.</div>");
return; return;
@@ -52,7 +52,7 @@ function updateBands() {
// Do some harsher de-duping. Because we only display callsign, frequency and mode here, the previous // 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. // 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. // Typically that's a person activating two programs at the same time, e.g. POTA & WWFF.
spotList = removeDuplicatesForBandPanel(spots); const spotList = removeDuplicatesForBandPanel(spots);
// Convert to a map of band names to the spots on that band. Bands with no // Convert to a map of band names to the spots on that band. Bands with no
// spots in view will not be present. // spots in view will not be present.
@@ -67,10 +67,10 @@ function updateBands() {
}); });
// Track if any columns end up taller than expected, so we can resize the container and avoid vertical scroll. // Track if any columns end up taller than expected, so we can resize the container and avoid vertical scroll.
var maxHeightBand = 0; let maxHeightBand = 0;
// Build up table content for each band // Build up table content for each band
var table = $('<table id="bands-table">').append('<thead><tr></tr></thead><tbody><tr></tr></tbody>'); const table = $('<table id="bands-table">').append('<thead><tr></tr></thead><tbody><tr></tr></tbody>');
bandToSpots.forEach(function (spotList, bandName) { bandToSpots.forEach(function (spotList, bandName) {
// Get the colours for the band from the first spot, and prepare the header // 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>`); table.find('thead tr').append(`<th style='background-color:${bandToColor(spotList[0].band)}; color:${bandToContrastColor(spotList[0].band)}'>${spotList[0].band}</th>`);
@@ -82,7 +82,7 @@ function updateBands() {
// Print the frequency band markers. This is 41 steps to divide the band evenly into 40 markers. One in every // 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. // four will show the actual frequency, the others will just be dashes.
bandMarkersDiv = $('<div class="band-markers">'); const bandMarkersDiv = $('<div class="band-markers">');
const freqStep = (band.end_freq - band.start_freq) / 40.0; const freqStep = (band.end_freq - band.start_freq) / 40.0;
for (let i = 0; i <= 40; i++) { for (let i = 0; i <= 40; i++) {
if (i % 4 === 0) { if (i % 4 === 0) {
@@ -95,8 +95,8 @@ function updateBands() {
} }
// Prepare the spots list // Prepare the spots list
var bandSpotsDiv = $("<div class='band-spots'>"); const bandSpotsDiv = $("<div class='band-spots'>");
var lastSpotPxDownBand = -999; let lastSpotPxDownBand = -999;
// Sort by frequency so have a consistent order in which to plan where they will appear on the band div. // 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; }); 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 // First calculate how we should be displaying the spots. There are three "modes" to try to place them in a
@@ -118,8 +118,8 @@ function updateBands() {
// Mode 1 or 2. Run through adding things to the list forwards as a test. // Mode 1 or 2. Run through adding things to the list forwards as a test.
spotList.forEach(s => { spotList.forEach(s => {
// Work out how far down the div to draw it // Work out how far down the div to draw it
var 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 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
var pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX; let pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX;
if (pxDownBand < lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX) { if (pxDownBand < lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX) {
pxDownBand = lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap pxDownBand = lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap
} }
@@ -135,8 +135,8 @@ function updateBands() {
lastSpotPxDownBand = 999999; lastSpotPxDownBand = 999999;
spotList.reverse().forEach(s => { spotList.reverse().forEach(s => {
// Work out how far down the div to draw it // Work out how far down the div to draw it
var 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 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
var pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX; let pxDownBand = percentDownBand * BAND_COLUMN_HEIGHT_PX;
if (pxDownBand > lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX) { if (pxDownBand > lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX) {
pxDownBand = lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap pxDownBand = lastSpotPxDownBand - BAND_COLUMN_SPOT_DIV_HEIGHT_PX; // Prevent overlap
} }
@@ -155,19 +155,19 @@ function updateBands() {
// Work out how tall the canvas should be. Normally this is matching the normal band column height, but if some // 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 // 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. // match, otherwise we have nowhere to draw their connecting lines.
var canvasHeight = Math.max(BAND_COLUMN_HEIGHT_PX, lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX); const canvasHeight = Math.max(BAND_COLUMN_HEIGHT_PX, lastSpotPxDownBand + BAND_COLUMN_SPOT_DIV_HEIGHT_PX);
maxHeightBand = Math.max(maxHeightBand, canvasHeight); maxHeightBand = Math.max(maxHeightBand, canvasHeight);
// Draw horizontal or diagonal lines to join up the "real" frequency with where the spot div ended up // Draw horizontal or diagonal lines to join up the "real" frequency with where the spot div ended up
var bandLinesCanvas = $(`<canvas class='band-lines-canvas' width='${BAND_COLUMN_CANVAS_WIDTH_PX}px' height='${canvasHeight}px' style='height:${canvasHeight}px !important;'>`); 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 => { spotList.forEach(s => {
// Work out how far down the div to draw it // Work out how far down the div to draw it
var 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 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
var 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 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
var 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 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 // Draw the line on the canvas
var ctx = bandLinesCanvas[0].getContext('2d'); const ctx = bandLinesCanvas[0].getContext('2d');
ctx.beginPath(); ctx.beginPath();
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.lineCap = "round"; ctx.lineCap = "round";
@@ -178,8 +178,8 @@ function updateBands() {
}); });
// Assemble the table cell // Assemble the table cell
td = $("<td>"); const td = $("<td>");
container = $("<div class='band-container'>"); const container = $("<div class='band-container'>");
container.append(bandLinesCanvas); container.append(bandLinesCanvas);
container.append(bandMarkersDiv); container.append(bandMarkersDiv);
container.append(bandSpotsDiv); container.append(bandSpotsDiv);
@@ -213,7 +213,6 @@ function removeDuplicatesForBandPanel(spotList) {
if (s.dx_call === check.dx_call && s.freq === check.freq && s.mode === check.mode) { if (s.dx_call === check.dx_call && s.freq === check.freq && s.mode === check.mode) {
// Find which one to keep and which to delete // Find which one to keep and which to delete
const checkSpotNewer = check.time > s.time; const checkSpotNewer = check.time > s.time;
const keepSpot = checkSpotNewer ? check : s;
const deleteSpot = checkSpotNewer ? s : check; const deleteSpot = checkSpotNewer ? s : check;
// Aggregate list of spots to remove // Aggregate list of spots to remove
spotsToRemove.push(deleteSpot.uid); spotsToRemove.push(deleteSpot.uid);
+22 -29
View File
@@ -1,7 +1,7 @@
// Storage for the options that the server gives us. This will define our filters. // Storage for the options that the server gives us. This will define our filters.
var options = {}; let options = {};
// Last time we updated the spots/alerts list on display. // Last time we updated the spots/alerts list on display.
var lastUpdateTime; let lastUpdateTime;
// Normally load user settings from local storage, unless embedded mode is in use // Normally load user settings from local storage, unless embedded mode is in use
let useLocalStorage = true; let useLocalStorage = true;
@@ -21,8 +21,8 @@ function saveSettings() {
}); });
// Password fields are only saved if the corresponding "remember password" checkbox is ticked. // Password fields are only saved if the corresponding "remember password" checkbox is ticked.
$(".password-field").each(function () { $(".password-field").each(function () {
var pwKey = "#" + $(this)[0].id + ":value"; const pwKey = "#" + $(this)[0].id + ":value";
var rememberCheckboxId = $(this).data("remember-checkbox"); const rememberCheckboxId = $(this).data("remember-checkbox");
if (rememberCheckboxId && $("#" + rememberCheckboxId)[0] && $("#" + rememberCheckboxId)[0].checked) { if (rememberCheckboxId && $("#" + rememberCheckboxId)[0] && $("#" + rememberCheckboxId)[0].checked) {
localStorage.setItem(pwKey, JSON.stringify($(this)[0].value)); localStorage.setItem(pwKey, JSON.stringify($(this)[0].value));
} else { } else {
@@ -39,7 +39,7 @@ function loadSettings() {
Object.keys(localStorage).forEach(function (key) { Object.keys(localStorage).forEach(function (key) {
if (key.startsWith("#") && key.includes(":")) { if (key.startsWith("#") && key.includes(":")) {
// Split the key back into an element ID and a property // Split the key back into an element ID and a property
var split = key.split(":"); const split = key.split(":");
$(split[0]).prop(split[1], JSON.parse(localStorage.getItem(key))); $(split[0]).prop(split[1], JSON.parse(localStorage.getItem(key)));
} }
}); });
@@ -76,21 +76,13 @@ function loadURLParams() {
updateFilterFromParam(params, "de_continent", "de_continent"); updateFilterFromParam(params, "de_continent", "de_continent");
} }
// Update an HTML checkbox element so that its selected matches the given parameter (which must have a true or false value)
function updateCheckboxFromParam(params, paramName, checkboxID) {
let v = params.get(paramName);
if (v != null) {
$("#" + checkboxID).prop("checked", (v === "true") ? true : false);
}
}
// Update an HTML select element so that its value matches the given parameter // Update an HTML select element so that its value matches the given parameter
function updateSelectFromParam(params, paramName, selectID) { function updateSelectFromParam(params, paramName, selectID) {
let v = params.get(paramName); let v = params.get(paramName);
if (v != null) { if (v != null) {
$("#" + selectID).prop("value", v); $("#" + selectID).prop("value", v);
// Extra check if this is the "color scheme" select // Extra check if this is the "color scheme" select
if (selectID == "color-scheme") { if (selectID === "color-scheme") {
setColorScheme(v); setColorScheme(v);
} }
} }
@@ -128,16 +120,16 @@ function getSelectedFilterOptions(parameter) {
// For a parameter, such as dx_continent, return true if all possible options are enabled. (In this case, we don't need // 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".) // to bother sending this as one of the query parameters to the API; no parameter provided implies "send everything".)
function allFilterOptionsSelected(parameter) { function allFilterOptionsSelected(parameter) {
var filter = $(".filter-button-" + parameter).filter(function () { const filter = $(".filter-button-" + parameter).filter(function () {
return !this.checked; return !this.checked;
}).get(); }).get();
return filter.length == 0; return filter.length === 0;
} }
// Generate a filter card with inline checkboxes plus All/None links. // Generate a filter card with inline checkboxes plus All/None links.
function generateMultiToggleFilterCard(elementID, filterQuery, options) { function generateMultiToggleFilterCard(elementID, filterQuery, options) {
var $row = $('<div>'); const $row = $('<div>');
options.forEach(o => { 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>`); $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>`);
}); });
@@ -161,12 +153,13 @@ function updateRefreshDisplay() {
let updatingString = "Updating..." let updatingString = "Updating..."
if (secSinceUpdate < REFRESH_INTERVAL_SEC) { if (secSinceUpdate < REFRESH_INTERVAL_SEC) {
count = REFRESH_INTERVAL_SEC - secSinceUpdate; count = REFRESH_INTERVAL_SEC - secSinceUpdate;
let number;
if (count <= 60) { if (count <= 60) {
var number = count.toFixed(0); number = count.toFixed(0);
updatingString = "<span class='nowrap'>Updating in " + number + " second" + (number != "1" ? "s" : "") + ".</span>"; updatingString = "<span class='nowrap'>Updating in " + number + " second" + (number !== "1" ? "s" : "") + ".</span>";
} else { } else {
var number = Math.round(count / 60.0).toFixed(0); number = Math.round(count / 60.0).toFixed(0);
updatingString = "<span class='nowrap'>Updating in " + number + " minute" + (number != "1" ? "s" : "") + ".</span>"; updatingString = "<span class='nowrap'>Updating in " + number + " minute" + (number !== "1" ? "s" : "") + ".</span>";
} }
} }
$("#timing-container").html("Last updated at " + lastUpdateTime.format('HH:mm') + " UTC. " + updatingString); $("#timing-container").html("Last updated at " + lastUpdateTime.format('HH:mm') + " UTC. " + updatingString);
@@ -188,7 +181,7 @@ function columnsUpdated() {
// Function to set the colour scheme based on the state of the UI select box // Function to set the colour scheme based on the state of the UI select box
function setColorSchemeFromUI() { function setColorSchemeFromUI() {
let theme = $("#color-scheme option:selected").val(); let theme = $("#color-scheme option:selected").val();
if (theme != "") { if (theme !== "") {
setColorScheme(theme); setColorScheme(theme);
saveSettings(); saveSettings();
} }
@@ -196,8 +189,8 @@ function setColorSchemeFromUI() {
// Function to set the color scheme. Supported values: "dark", "light", "auto" // Function to set the color scheme. Supported values: "dark", "light", "auto"
function setColorScheme(mode) { function setColorScheme(mode) {
let effectiveModeDark = mode == "dark"; let effectiveModeDark = mode === "dark";
if (mode == "auto") { if (mode === "auto") {
effectiveModeDark = window.matchMedia('(prefers-color-scheme: dark)').matches effectiveModeDark = window.matchMedia('(prefers-color-scheme: dark)').matches
} }
$("html").attr("data-bs-theme", effectiveModeDark ? "dark" : "light"); $("html").attr("data-bs-theme", effectiveModeDark ? "dark" : "light");
@@ -283,16 +276,16 @@ function closeDataPanel() {
// Build a query string fragment containing any QRZ.com / HamQTH credentials the user has supplied, // Build a query string fragment containing any QRZ.com / HamQTH credentials the user has supplied,
// provided the corresponding "enabled" checkbox is ticked. // provided the corresponding "enabled" checkbox is ticked.
function getCredentialQueryString() { function getCredentialQueryString() {
var str = ""; let str = "";
if ($("#qrz-enabled")[0] && $("#qrz-enabled")[0].checked) { if ($("#qrz-enabled")[0] && $("#qrz-enabled")[0].checked) {
var qrzUsername = $("#qrz-username").val(); const qrzUsername = $("#qrz-username").val();
var qrzPassword = $("#qrz-password").val(); const qrzPassword = $("#qrz-password").val();
if (qrzUsername) str += "&qrz_username=" + encodeURIComponent(qrzUsername); if (qrzUsername) str += "&qrz_username=" + encodeURIComponent(qrzUsername);
if (qrzPassword) str += "&qrz_password=" + encodeURIComponent(qrzPassword); if (qrzPassword) str += "&qrz_password=" + encodeURIComponent(qrzPassword);
} }
if ($("#hamqth-enabled")[0] && $("#hamqth-enabled")[0].checked) { if ($("#hamqth-enabled")[0] && $("#hamqth-enabled")[0].checked) {
var hamqthUsername = $("#hamqth-username").val(); const hamqthUsername = $("#hamqth-username").val();
var hamqthPassword = $("#hamqth-password").val(); const hamqthPassword = $("#hamqth-password").val();
if (hamqthUsername) str += "&hamqth_username=" + encodeURIComponent(hamqthUsername); if (hamqthUsername) str += "&hamqth_username=" + encodeURIComponent(hamqthUsername);
if (hamqthPassword) str += "&hamqth_password=" + encodeURIComponent(hamqthPassword); if (hamqthPassword) str += "&hamqth_password=" + encodeURIComponent(hamqthPassword);
} }
+8 -3
View File
@@ -17,6 +17,7 @@ function loadSolarConditions() {
const hfConditionClass = {'Good': 'bg-success-subtle', 'Fair': 'bg-warning-subtle', 'Poor': 'bg-danger-subtle'}; const hfConditionClass = {'Good': 'bg-success-subtle', 'Fair': 'bg-warning-subtle', 'Poor': 'bg-danger-subtle'};
if (jsonData.hf_conditions) { if (jsonData.hf_conditions) {
$('#hamqsl-section').show();
Object.entries(jsonData.hf_conditions).forEach(function ([key, condition]) { Object.entries(jsonData.hf_conditions).forEach(function ([key, condition]) {
const cell = $('#hf-conditions-' + key); const cell = $('#hf-conditions-' + key);
cell.text(condition); cell.text(condition);
@@ -116,6 +117,7 @@ function loadSolarConditions() {
// Ionosonde // Ionosonde
if (jsonData.ionosonde_data && Object.keys(jsonData.ionosonde_data).length > 0) { if (jsonData.ionosonde_data && Object.keys(jsonData.ionosonde_data).length > 0) {
$('#ionosonde-section').show();
ionosondeData = jsonData.ionosonde_data; ionosondeData = jsonData.ionosonde_data;
populateIonosondeDropdown(ionosondeData); populateIonosondeDropdown(ionosondeData);
renderIonosondeData(); renderIonosondeData();
@@ -123,6 +125,9 @@ function loadSolarConditions() {
// Forecast // Forecast
if (jsonData.k_index_forecast) {
$('#noaa-section').show();
}
renderKIndexForecast(jsonData.k_index_forecast); renderKIndexForecast(jsonData.k_index_forecast);
renderSolarStormForecast(jsonData.solar_storm_forecast); renderSolarStormForecast(jsonData.solar_storm_forecast);
renderBlackoutForecast(jsonData.blackout_forecast_r1r2, jsonData.blackout_forecast_r3_or_greater); renderBlackoutForecast(jsonData.blackout_forecast_r1r2, jsonData.blackout_forecast_r3_or_greater);
@@ -431,9 +436,9 @@ function renderIonosondeData() {
const latestDate = moment.utc(maxTs * 1000); const latestDate = moment.utc(maxTs * 1000);
$('#ionosonde-latest-time').text(latestDate.format('DD MMM YYYY HH:mm [UTC]') + ' (' + latestDate.fromNow() + ')'); $('#ionosonde-latest-time').text(latestDate.format('DD MMM YYYY HH:mm [UTC]') + ' (' + latestDate.fromNow() + ')');
} }
$('#ionosonde-latest-luf').text(latestLuf !== null ? latestLuf.toFixed(2) + ' MHz' : 'N/A'); $('#ionosonde-latest-luf').text(latestLuf !== null ? latestLuf.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-latest-fof2').text(latestFof2 !== null ? latestFof2.toFixed(2) + ' MHz' : 'N/A'); $('#ionosonde-latest-fof2').text(latestFof2 !== null ? latestFof2.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-latest-muf').text(latestMuf !== null ? latestMuf.toFixed(2) + ' MHz' : 'N/A'); $('#ionosonde-latest-muf').text(latestMuf !== null ? latestMuf.toFixed(2) + ' MHz' : 'Unknown');
$('#ionosonde-stale-warning').toggle(maxTs !== null && (Date.now() / 1000 - maxTs) > 12 * 3600); $('#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 // Populate band state tables. There are actually two tables to populate, which is pretty janky, but allows us to
+104
View File
@@ -0,0 +1,104 @@
//
// 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];
}
+34 -32
View File
@@ -12,19 +12,19 @@ const ITU_ZONES_COLOR_DARK = 'rgba(120, 120, 60, 1.0)';
const WAB_WAI_GRID_COLOR_DARK = 'rgba(60, 60, 120, 1.0)'; const WAB_WAI_GRID_COLOR_DARK = 'rgba(60, 60, 120, 1.0)';
// Map layers // Map layers
var backgroundTileLayer; let backgroundTileLayer;
var markersLayer; let markersLayer;
var geodesicsLayer; let geodesicsLayer;
var oms; let oms;
var terminator; let terminator;
var maidenheadGrid; let maidenheadGrid;
var cqZones; let cqZones;
var ituZones; let ituZones;
var wabwaiGrid; let wabwaiGrid;
// Tracks the currently-loaded basemap provider string to avoid unnecessary tile reloads // Tracks the currently-loaded basemap provider string to avoid unnecessary tile reloads
var loadedBasemap; let loadedBasemap;
// Tracks whether this is the first display of markers after page load // Tracks whether this is the first display of markers after page load
var firstLoad = true; let firstLoad = true;
// Load spots and populate the map. // Load spots and populate the map.
function loadSpots() { function loadSpots() {
@@ -41,7 +41,7 @@ function loadSpots() {
// Build a query string for the API, based on the filters that the user has selected. // Build a query string for the API, based on the filters that the user has selected.
function buildQueryString(includeCredentials) { function buildQueryString(includeCredentials) {
var str = "?"; let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => { ["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) { if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&"; str = str + getQueryStringFor(fn) + "&";
@@ -65,7 +65,7 @@ function updateMap() {
// Make new markers for all spots that match the filter // Make new markers for all spots that match the filter
spots.forEach(function (s) { spots.forEach(function (s) {
var m = L.marker([s["dx_latitude"], s["dx_longitude"]], {icon: getIcon(s)}); const m = L.marker([s["dx_latitude"], s["dx_longitude"]], {icon: getIcon(s)});
m.bindPopup(getTooltipText(s)); m.bindPopup(getTooltipText(s));
markersLayer.addLayer(m); markersLayer.addLayer(m);
oms.addMarker(m); oms.addMarker(m);
@@ -73,7 +73,7 @@ function updateMap() {
// Create geodesics if required // Create geodesics if required
if ($("#mapShowGeodesics")[0].checked && s["de_latitude"] != null && s["de_longitude"] != null) { if ($("#mapShowGeodesics")[0].checked && s["de_latitude"] != null && s["de_longitude"] != null) {
try { try {
var geodesic = L.geodesic([[s["de_latitude"], s["de_longitude"]], m.getLatLng()], { const geodesic = L.geodesic([[s["de_latitude"], s["de_longitude"]], m.getLatLng()], {
color: bandToColor(s['band']), color: bandToColor(s['band']),
wrap: false, wrap: false,
steps: 5 steps: 5
@@ -88,7 +88,7 @@ function updateMap() {
// On first load, zoom to the extent of the markers // On first load, zoom to the extent of the markers
if (firstLoad) { if (firstLoad) {
if (markersLayer.getLayers().length >= 2) { if (markersLayer.getLayers().length >= 2) {
var group = new L.featureGroup(markersLayer.getLayers()); const group = new L.featureGroup(markersLayer.getLayers());
map.fitBounds(group.getBounds().pad(0.1)); map.fitBounds(group.getBounds().pad(0.1));
} }
firstLoad = false; firstLoad = false;
@@ -110,48 +110,50 @@ function getIcon(s) {
// Tooltip text for the markers // Tooltip text for the markers
function getTooltipText(s) { function getTooltipText(s) {
// Format DX call // Format DX call
var dx_call = s["dx_call"]; let dx_call = s["dx_call"];
if (dx_call == null) { if (dx_call == null) {
dx_call = ""; dx_call = "";
dx_flag = "";
} }
if (s["dx_ssid"] != null) { if (s["dx_ssid"] != null) {
dx_call = dx_call + "-" + s["dx_ssid"]; dx_call = dx_call + "-" + s["dx_ssid"];
} }
// Format DX flag // Format DX flag
var dx_flag = "<i class='fa-solid fa-globe-africa'></i>"; let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
if (s["dx_flag"] && s["dx_flag"] != null && s["dx_flag"] != "") { if (dx_call == null) {
dx_flag = "";
}
if (s["dx_flag"] && s["dx_flag"] != null && s["dx_flag"] !== "") {
dx_flag = s["dx_flag"]; dx_flag = s["dx_flag"];
} }
// Format the frequency // Format the frequency
var freq_string = "Unknown" let freq_string = "Unknown";
if (s["freq"] != null) { if (s["freq"] != null) {
var mhz = Math.floor(s["freq"] / 1000000.0); const mhz = Math.floor(s["freq"] / 1000000.0);
var khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0); const khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0);
var hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0)); const hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0));
var hz_string = (hz > 0) ? hz.toFixed(0)[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>` 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 // Format comment
var commentText = ""; let commentText = "";
if (s["comment"] != null) { if (s["comment"] != null) {
commentText = escapeHtml(s["comment"]); commentText = escapeHtml(s["comment"]);
} }
// Sig or fallback to source // Sig or fallback to source
var sigSourceText = s["source"]; let sigSourceText = s["source"];
if (s["sig"]) { if (s["sig"]) {
sigSourceText = s["sig"]; sigSourceText = s["sig"];
} }
// Format sig_refs // Format sig_refs
var sig_refs = ""; let sig_refs = "";
if (s["sig_refs"] != null) { if (s["sig_refs"] != null) {
var items = [] const items = [];
for (var i = 0; i < s["sig_refs"].length; i++) { for (let i = 0; i < s["sig_refs"].length; i++) {
if (s["sig_refs"][i]["url"] != null) { 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>` 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 { } else {
@@ -162,7 +164,7 @@ function getTooltipText(s) {
} }
// DX // DX
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/>`; 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 // Frequency & band
ttt += `<span class='icon-wrapper'><i class='fa-solid fa-radio markerPopupIcon'></i></span>&nbsp;${freq_string}`; ttt += `<span class='icon-wrapper'><i class='fa-solid fa-radio markerPopupIcon'></i></span>&nbsp;${freq_string}`;
@@ -273,7 +275,7 @@ function setBasemap(basemapname) {
backgroundTileLayer.addTo(map); backgroundTileLayer.addTo(map);
backgroundTileLayer.bringToBack(); backgroundTileLayer.bringToBack();
if (basemapname === "OpenStreetMap.Mapnik.Dark") { if (basemapname === "OpenStreetMap.Mapnik.Dark") {
var container = backgroundTileLayer.getContainer(); const container = backgroundTileLayer.getContainer();
if (container) { if (container) {
container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)'; container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)';
} }
@@ -409,7 +411,7 @@ function setUpMap() {
backgroundTileLayer.addTo(map); backgroundTileLayer.addTo(map);
backgroundTileLayer.bringToBack(); backgroundTileLayer.bringToBack();
if (loadedBasemap === "OpenStreetMap.Mapnik.Dark") { if (loadedBasemap === "OpenStreetMap.Mapnik.Dark") {
var container = backgroundTileLayer.getContainer(); const container = backgroundTileLayer.getContainer();
if (container) { if (container) {
container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)'; container.style.filter = 'invert(100%) hue-rotate(180deg) brightness(80%)';
} }
+79 -69
View File
@@ -4,6 +4,14 @@ let restartSSEOnErrorTimeoutId;
// Table row count, to alternate shading // Table row count, to alternate shading
let rowCount = 0; 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. // Load spots and populate the table.
function loadSpots() { function loadSpots() {
// If we have an ongoing SSE connection, stop it so it doesn't interfere with our reload // If we have an ongoing SSE connection, stop it so it doesn't interfere with our reload
@@ -35,7 +43,7 @@ function startSSEConnection() {
evtSource.onmessage = function(event) { evtSource.onmessage = function(event) {
// Get the new spot // Get the new spot
newSpot = JSON.parse(event.data); 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 // 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 // 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 // time up to match it. This isn't great but since we poll spot providers every 2 minutes anyway, it shouldn't
@@ -55,7 +63,7 @@ function startSSEConnection() {
} }
// If we had zero spots before (i.e. one now), the table will have a "No spots" row that we need to remove now // 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. // that we have one.
if (spots.length == 1) { if (spots.length === 1) {
$("#table tbody tr").last().remove(); $("#table tbody tr").last().remove();
} }
@@ -68,7 +76,7 @@ function startSSEConnection() {
} }
}; };
evtSource.onerror = function(err) { evtSource.onerror = function() {
if (evtSource != null) { if (evtSource != null) {
evtSource.close(); evtSource.close();
} }
@@ -79,14 +87,14 @@ function startSSEConnection() {
// Build a query string for the API, based on the filters that the user has selected. // Build a query string for the API, based on the filters that the user has selected.
function buildQueryString(includeCredentials) { function buildQueryString(includeCredentials) {
var str = "?"; let str = "?";
["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => { ["dx_continent", "de_continent", "mode", "source", "band", "sig"].forEach(fn => {
if (!allFilterOptionsSelected(fn)) { if (!allFilterOptionsSelected(fn)) {
str = str + getQueryStringFor(fn) + "&"; str = str + getQueryStringFor(fn) + "&";
} }
}); });
str = str + "limit=" + $("#spots-to-fetch option:selected").val(); str = str + "limit=" + $("#spots-to-fetch option:selected").val();
if ($("#search").val() != "") { if ($("#search").val() !== "") {
str = str + "&text_includes=" + encodeURIComponent($("#search").val()); str = str + "&text_includes=" + encodeURIComponent($("#search").val());
} }
if (includeCredentials) { if (includeCredentials) {
@@ -98,22 +106,22 @@ function buildQueryString(includeCredentials) {
// Update the spots table // Update the spots table
function updateTable() { function updateTable() {
// Use local time instead of UTC? // Use local time instead of UTC?
var useLocalTime = $("#timeZone")[0].value == "local"; const useLocalTime = $("#timeZone")[0].value === "local";
// Get user grid if valid, this will be null if it's not. // Get user grid if valid, this will be null if it's not.
var userPos = latLonForGridCentre($("#userGrid").val()); const userPos = latLonForGridCentre($("#userGrid").val());
// Table data toggles // Table data toggles
var showTime = $("#tableShowTime")[0].checked; const showTime = $("#tableShowTime")[0].checked;
var showDX = $("#tableShowDX")[0].checked; const showDX = $("#tableShowDX")[0].checked;
var showFreq = $("#tableShowFreq")[0].checked; const showFreq = $("#tableShowFreq")[0].checked;
var showMode = $("#tableShowMode")[0].checked; const showMode = $("#tableShowMode")[0].checked;
var showComment = $("#tableShowComment")[0].checked; const showComment = $("#tableShowComment")[0].checked;
var showBearing = $("#tableShowBearing")[0].checked && userPos != null; const showBearing = $("#tableShowBearing")[0].checked && userPos != null;
var showType = $("#tableShowType")[0].checked; const showType = $("#tableShowType")[0].checked;
var showRef = $("#tableShowRef")[0].checked; const showRef = $("#tableShowRef")[0].checked;
var showDE = $("#tableShowDE")[0].checked; const showDE = $("#tableShowDE")[0].checked;
var showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked; const showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked;
// Populate table with headers // Populate table with headers
let table = $("#table"); let table = $("#table");
@@ -150,7 +158,7 @@ function updateTable() {
} }
table.find('tbody').empty(); table.find('tbody').empty();
if (spots.length == 0) { 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>'); table.find('tbody').append('<tr class="bg-danger-subtle"><td colspan="100" style="text-align:center;">No spots match your filters.</td></tr>');
} }
@@ -174,22 +182,22 @@ function addSpotToTopOfTable(s, highlightNew) {
// highlightNew = false for an initial load, true for new SSE-loaded spots // highlightNew = false for an initial load, true for new SSE-loaded spots
function createNewTableRowsForSpot(s, highlightNew) { function createNewTableRowsForSpot(s, highlightNew) {
// Use local time instead of UTC? // Use local time instead of UTC?
var useLocalTime = $("#timeZone")[0].value == "local"; const useLocalTime = $("#timeZone")[0].value === "local";
// Get user grid if valid, this will be null if it's not. // Get user grid if valid, this will be null if it's not.
var userPos = latLonForGridCentre($("#userGrid").val()); const userPos = latLonForGridCentre($("#userGrid").val());
// Table data toggles // Table data toggles
var showTime = $("#tableShowTime")[0].checked; const showTime = $("#tableShowTime")[0].checked;
var showDX = $("#tableShowDX")[0].checked; const showDX = $("#tableShowDX")[0].checked;
var showFreq = $("#tableShowFreq")[0].checked; const showFreq = $("#tableShowFreq")[0].checked;
var showMode = $("#tableShowMode")[0].checked; const showMode = $("#tableShowMode")[0].checked;
var showComment = $("#tableShowComment")[0].checked; const showComment = $("#tableShowComment")[0].checked;
var showBearing = $("#tableShowBearing")[0].checked && userPos != null; const showBearing = $("#tableShowBearing")[0].checked && userPos != null;
var showType = $("#tableShowType")[0].checked; const showType = $("#tableShowType")[0].checked;
var showRef = $("#tableShowRef")[0].checked; const showRef = $("#tableShowRef")[0].checked;
var showDE = $("#tableShowDE")[0].checked; const showDE = $("#tableShowDE")[0].checked;
var showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked; const showWorkedCheckbox = $("#tableShowWorkedCheckbox")[0].checked;
// Create row // Create row
let $tr = $('<tr>'); let $tr = $('<tr>');
@@ -197,13 +205,13 @@ function createNewTableRowsForSpot(s, highlightNew) {
// Apply striping to the table. We can't just use Bootstrap's table-striped class because we have all sorts of // 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 // 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. // which cause the table-striped colouring to go awry.
if (rowCount % 2 == 1) { if (rowCount % 2 === 1) {
$tr.addClass("table-active"); $tr.addClass("table-active");
} }
// Show faded out if QRT or already worked // Show faded out if QRT or already worked
let alreadyWorkedThis = alreadyWorked(s["dx_call"], s["band"], s["mode"]); let alreadyWorkedThis = alreadyWorked(s["dx_call"], s["band"], s["mode"]);
if (s["qrt"] == true || alreadyWorkedThis) { if (s["qrt"] === true || alreadyWorkedThis) {
$tr.addClass("table-faded"); $tr.addClass("table-faded");
} }
@@ -214,65 +222,67 @@ function createNewTableRowsForSpot(s, highlightNew) {
} }
// Format a UTC or local time for display // Format a UTC or local time for display
var time = moment.unix(s["time"]).utc(); const time = moment.unix(s["time"]).utc();
if (useLocalTime) { if (useLocalTime) {
time.local(); time.local();
} }
var time_formatted = time.format("HH:mm"); const time_formatted = time.format("HH:mm");
// Format DX call // Format DX call
var dx_call = s["dx_call"]; let dx_call = s["dx_call"];
if (dx_call == null) { if (dx_call == null) {
dx_call = ""; dx_call = "";
dx_flag = "";
} }
if (s["dx_ssid"] != null) { if (s["dx_ssid"] != null) {
dx_call = dx_call + "-" + s["dx_ssid"]; dx_call = dx_call + "-" + s["dx_ssid"];
} }
// Format dx country // Format dx country
var dx_country = s["dx_country"]; let dx_country = s["dx_country"];
if (dx_country == null) { if (dx_country == null) {
dx_country = "Unknown or not a country"; dx_country = "Unknown or not a country";
} }
// Format DX flag // Format DX flag
var dx_flag = "<i class='fa-solid fa-globe-africa'></i>"; let dx_flag = "<i class='fa-solid fa-globe-africa'></i>";
if (s["dx_dxcc_id"] && s["dx_dxcc_id"] != null && s["dx_dxcc_id"] != 0) { 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="img/flags/${s['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`; dx_flag = `<img src="img/flags/${s['dx_dxcc_id']}.png" class="flag" width="24" alt="${dx_country}" title="${dx_country}"/>`;
} }
// Format the frequency // Format the frequency
var freq_string = "Unknown" let freq_string = "Unknown";
if (s["freq"] != null) { if (s["freq"] != null) {
var mhz = Math.floor(s["freq"] / 1000000.0); const mhz = Math.floor(s["freq"] / 1000000.0);
var khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0); const khz = Math.floor((s["freq"] - (mhz * 1000000.0)) / 1000.0);
var hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0)); const hz = Math.floor(s["freq"] - (mhz * 1000000.0) - (khz * 1000.0));
var hz_string = (hz > 0) ? hz.toFixed(0)[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>` 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 // Format the mode
mode_string = s["mode"]; let mode_string = s["mode"];
if (s["mode"] == null) { if (s["mode"] == null) {
mode_string = ""; mode_string = "";
} else if (s["mode_source"] == "BANDPLAN") { } 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>"; 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 // Format comment
var commentText = ""; let commentText = "";
if (s["comment"] != null) { if (s["comment"] != null) {
commentText = escapeHtml(s["comment"]); commentText = escapeHtml(s["comment"]);
} }
// Format bearing text // Format bearing text
var 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>"; 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) { if (userPos != null && s["dx_latitude"] != null && s["dx_longitude"] != null) {
var bearing = calcBearing(userPos[0], userPos[1], s["dx_latitude"], s["dx_longitude"]); const bearing = calcBearing(userPos[0], userPos[1], s["dx_latitude"], s["dx_longitude"]);
bearingText = bearing.toFixed(0).padStart(3, '0') + "°"; bearingText = bearing.toFixed(0).padStart(3, '0') + "°";
if (s["dx_location_good"] == null || s["dx_location_good"] == false) { if (s["dx_location_good"] == null || s["dx_location_good"] === false) {
if (s["dx_location_source"] == "HOME QTH") { 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>"; 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 { } 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>"; 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>";
@@ -281,16 +291,16 @@ function createNewTableRowsForSpot(s, highlightNew) {
} }
// Format "type" (Sig or fallback to source) // Format "type" (Sig or fallback to source)
var typeText = s["source"]; let typeText = s["source"];
if (s["sig"]) { if (s["sig"]) {
typeText = s["sig"]; typeText = s["sig"];
} }
// Format sig_refs // Format sig_refs
var sig_refs = ""; let sig_refs = "";
if (s["sig_refs"] != null) { if (s["sig_refs"] != null) {
var items = [] const items = [];
for (var i = 0; i < s["sig_refs"].length; i++) { for (let i = 0; i < s["sig_refs"].length; i++) {
if (s["sig_refs"][i]["url"] != null) { 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>` 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 { } else {
@@ -301,19 +311,19 @@ function createNewTableRowsForSpot(s, highlightNew) {
} }
// Format de country // Format de country
var de_country = s["de_country"]; let de_country = s["de_country"];
if (de_country == null) { if (de_country == null) {
de_country = "Unknown or not a country"; de_country = "Unknown or not a country";
} }
// Format DE flag // Format DE flag
var de_flag = "<i class='fa-solid fa-circle-question'></i>"; 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) { if (s["de_dxcc_id"] && s["de_dxcc_id"] != null && s["de_dxcc_id"] !== 0) {
de_flag = `<img src="img/flags/${s['de_dxcc_id']}.png" class="flag" width="24" alt="${de_country}" title="${de_country}"/>`; de_flag = `<img src="img/flags/${s['de_dxcc_id']}.png" class="flag" width="24" alt="${de_country}" title="${de_country}"/>`;
} }
// Format de call // Format de call
var de_call = s["de_call"]; let de_call = s["de_call"];
if (de_call == null) { if (de_call == null) {
de_call = ""; de_call = "";
de_flag = ""; de_flag = "";
@@ -323,10 +333,10 @@ function createNewTableRowsForSpot(s, highlightNew) {
} }
// Format band name // Format band name
var bandFullName = s['band'] ? s['band'] + " band": "Unknown band"; const bandFullName = s['band'] ? s['band'] + " band" : "Unknown band";
// Format "worked" checkbox // Format "worked" checkbox
var 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.">`; 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 // Populate the row
if (showTime) { if (showTime) {
@@ -361,21 +371,21 @@ function createNewTableRowsForSpot(s, highlightNew) {
} }
// Second row for mobile view only, containing type, ref & comment // Second row for mobile view only, containing type, ref & comment
$tr2 = $("<tr class='hidenotonmobile'>"); const $tr2 = $("<tr class='hidenotonmobile'>");
// Apply styles as per the first row // Apply styles as per the first row
if (rowCount % 2 == 1) { if (rowCount % 2 === 1) {
$tr2.addClass("table-active"); $tr2.addClass("table-active");
} }
if (s["qrt"] == true || alreadyWorkedThis) { if (s["qrt"] === true || alreadyWorkedThis) {
$tr2.addClass("table-faded"); $tr2.addClass("table-faded");
} }
if (highlightNew) { if (highlightNew) {
$tr2.addClass("new"); $tr2.addClass("new");
} }
$td2 = $("<td colspan='100'>"); const $td2 = $("<td colspan='100'>");
$td2floatleft = $(`<div style="float: left;">`); const $td2floatleft = $(`<div style="float: left;">`);
if (showType) { if (showType) {
$td2floatleft.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(s["sig"], "fa-tower-cell")}'></i></span> ${typeText} `); $td2floatleft.append(`<span class='icon-wrapper'><i class='fa-solid ${sigToIcon(s["sig"], "fa-tower-cell")}'></i></span> ${typeText} `);
} }
@@ -383,7 +393,7 @@ function createNewTableRowsForSpot(s, highlightNew) {
$td2floatleft.append(`${sig_refs} `); $td2floatleft.append(`${sig_refs} `);
} }
$td2.append($td2floatleft); $td2.append($td2floatleft);
$td2floatright = $(`<div style="float: right;">`); const $td2floatright = $(`<div style="float: right;">`);
if (showBearing) { if (showBearing) {
$td2floatright.append(`${bearingText} &nbsp;`); $td2floatright.append(`${bearingText} &nbsp;`);
} }
@@ -451,13 +461,13 @@ function loadOptions() {
// Work out if the user's entered grid is a valid Maidenhead grid // Work out if the user's entered grid is a valid Maidenhead grid
function isUserGridValid() { function isUserGridValid() {
userGrid = $("#userGrid").val().toUpperCase(); const userGrid = $("#userGrid").val().toUpperCase();
return latLonForGridCentre(userGrid) != null; return latLonForGridCentre(userGrid) != null;
} }
// Method called when the user's grid input is changed. // Method called when the user's grid input is changed.
function userGridUpdated() { function userGridUpdated() {
var userGridValid = isUserGridValid(); const userGridValid = isUserGridValid();
if (userGridValid) { if (userGridValid) {
updateTable(); updateTable();
} }
+14 -14
View File
@@ -1,5 +1,5 @@
// Storage for the spot data that the server gives us. // Storage for the spot data that the server gives us.
var spots = [] 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 // 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 // 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 // table and the callsign-band-mode is in this list, it is shown struck through as already worked. This is persisted
@@ -9,9 +9,9 @@ let worked = []
// Dynamically add CSS code for the band checkboxes to show in the appropriate colour. // 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". // Some band names contain decimal points which are not allowed in CSS classes, so we text-replace them to "p".
function addBandToggleColourCSS(band_options) { function addBandToggleColourCSS(band_options) {
var $style = $('<style>'); const $style = $('<style>');
band_options.forEach(o => { band_options.forEach(o => {
var domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, ""); 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'])};}`); $style.append(`#filter-button-label-band-${domSafeName} { padding-left: 0.3em; border-left: 5px solid ${bandToColor(o['name'])};}`);
}); });
$('html > head').append($style); $('html > head').append($style);
@@ -19,9 +19,9 @@ function addBandToggleColourCSS(band_options) {
// Generate bands filter card. This one is a special case. // Generate bands filter card. This one is a special case.
function generateBandsMultiToggleFilterCard(band_options) { function generateBandsMultiToggleFilterCard(band_options) {
var $grid = $('<div class="row row-cols-3 row-cols-md-2 row-cols-lg-3 row-cols-xxl-4 g-1 mb-1">'); 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 => { band_options.forEach(o => {
var domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, ""); 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>`); $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($grid);
@@ -40,9 +40,9 @@ function setHamHFBandToggles() {
// Generate SIGs filter card. This one is also a special case. // Generate SIGs filter card. This one is also a special case.
function generateSIGsMultiToggleFilterCard(sig_options) { function generateSIGsMultiToggleFilterCard(sig_options) {
var $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">'); const $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">');
sig_options.forEach(o => { sig_options.forEach(o => {
var domSafeName = o["name"].replace(/^[^A-Za-z0-9]+|[^\w]+/gi, ""); 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>`); $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 // Bonus "NO_SIG" / "General DX" option
@@ -53,9 +53,9 @@ function generateSIGsMultiToggleFilterCard(sig_options) {
// Generate modes filter card. This one is also a special case. // Generate modes filter card. This one is also a special case.
function generateModesMultiToggleFilterCard(mode_options) { function generateModesMultiToggleFilterCard(mode_options) {
var $grid = $('<div class="row row-cols-3 row-cols-md-2 row-cols-lg-3 g-1 mb-1">'); const $grid = $('<div class="row row-cols-3 row-cols-md-2 row-cols-lg-3 g-1 mb-1">');
mode_options.forEach(o => { mode_options.forEach(o => {
var domSafeName = o.replace(/^[^A-Za-z0-9]+|[^\w]+/gi, ""); 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>`); $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($grid);
@@ -84,10 +84,10 @@ function setDigiModeToggles() {
// set which ones are enabled by default based on config rather than having them all enabled by default. We also sanitise // 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. // names here for HTML elements.
function generateSourcesMultiToggleFilterCard(source_options, sources_enabled_by_default) { function generateSourcesMultiToggleFilterCard(source_options, sources_enabled_by_default) {
var $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">'); const $grid = $('<div class="row row-cols-2 row-cols-xxl-3 g-1 mb-1">');
source_options.forEach(o => { source_options.forEach(o => {
var enable = sources_enabled_by_default.includes(o); const enable = sources_enabled_by_default.includes(o);
var domSafeName = o.replace(/^[^A-Za-z0-9]+|[^\w]+/gi, ""); 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>`); $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($grid);
@@ -115,7 +115,7 @@ function alreadyWorked(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 // 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. // after some time has passed with it in the background.
addEventListener("visibilitychange", (event) => { addEventListener("visibilitychange", () => {
if (!document.hidden) { if (!document.hidden) {
loadSpots(); loadSpots();
} }
@@ -124,7 +124,7 @@ addEventListener("visibilitychange", (event) => {
// Startup // Startup
$(document).ready(function() { $(document).ready(function() {
// Load worked list // Load worked list
var tmpWorked = JSON.parse(localStorage.getItem("worked")); const tmpWorked = JSON.parse(localStorage.getItem("worked"));
if (tmpWorked) { if (tmpWorked) {
worked = tmpWorked; worked = tmpWorked;
} }
+355
View File
@@ -0,0 +1,355 @@
//
// 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;
}
// 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 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",
"WWTOTA": "fa-tower-observation",
"WAB": "fa-table-cells-large",
"WAI": "fa-table-cells-large",
"Tiles": "fa-square",
"TOTA": "fa-toilet"
}
// 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;
}
}
}
+33
View File
@@ -0,0 +1,33 @@
//
// 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));
}
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 696 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 B

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 535 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+113
View File
@@ -0,0 +1,113 @@
/*
* L.Maidenhead displays a Maidenhead Locator of lines on the map.
*/
L.Maidenhead = L.LayerGroup.extend({
options: {
// Line and label color
color: 'rgba(255, 0, 0, 0.4)',
// Redraw on move or moveend
redraw: 'move'
},
initialize: function (options) {
L.LayerGroup.prototype.initialize.call(this);
L.Util.setOptions(this, options);
},
onAdd: function (map) {
this._map = map;
var grid = this.redraw();
this._map.on('viewreset '+ this.options.redraw, function () {
grid.redraw();
});
this.eachLayer(map.addLayer, map);
},
onRemove: function (map) {
// remove layer listeners and elements
map.off('viewreset '+ this.options.redraw, this.map);
this.eachLayer(this.removeLayer, this);
},
redraw: function () {
var d3 = new Array(20,10,10,10,10,10,1 ,1 ,1 ,1 ,1/24,1/24,1/24,1/24,1/24,1/240,1/240,1/240,1/240/24,1/240/24,1/240/24 );
var lat_cor = new Array(0 ,8 ,8 ,8 ,10,14,6 ,8 ,8 ,8 ,1.4 ,2.5 ,3 ,3.5 ,4 ,4 ,3.5 ,3.5 ,1.47 ,1.8 ,1.6 );
var bounds = map.getBounds();
var zoom = map.getZoom();
var unit = d3[Math.round(zoom)];
var lcor = lat_cor[Math.round(zoom)];
var w = bounds.getWest();
var e = bounds.getEast();
var n = bounds.getNorth();
var s = bounds.getSouth();
if (zoom==1) {var c = 2;} else {var c = 0.1;}
if (n > 85) n = 85;
if (s < -85) s = -85;
var left = Math.floor(w/(unit*2))*(unit*2);
var right = Math.ceil(e/(unit*2))*(unit*2);
var top = Math.ceil(n/unit)*unit;
var bottom = Math.floor(s/unit)*unit;
this.eachLayer(this.removeLayer, this);
for (var lon = left; lon < right; lon += (unit*2)) {
for (var lat = bottom; lat < top; lat += unit) {
var bounds = [[lat,lon],[lat+unit,lon+(unit*2)]];
this.addLayer(L.rectangle(bounds, {color: this.options.color, weight: 1, fill:false, interactive: false}));
//var pont = map.latLngToLayerPoint([lat,lon]);
//console.log(pont.x);
this.addLayer(this._getLabel(lon+unit-(unit/lcor),lat+(unit/2)+(unit/lcor*c)));
}
}
return this;
},
_getLabel: function(lon,lat) {
var title_size = new Array(0 ,10,12,16,20,26,12,16,24,36,12 ,14 ,20 ,36 ,60 ,12 ,20 ,36 ,8 ,12 ,24 );
var zoom = map.getZoom();
var size = title_size[Math.round(zoom)]+'px';
var title = '<span style="cursor: default;"><font style="color:'+this.options.color+'; font-size:'+size+'; font-weight: 900; ">' + this._getLocator(lon,lat) + '</font></span>';
var myIcon = L.divIcon({className: 'my-div-icon', html: title});
var marker = L.marker([lat,lon], {icon: myIcon}, clickable=false);
return marker;
},
_getLocator: function(lon,lat) {
var ydiv_arr=new Array(10, 1, 1/24, 1/240, 1/240/24);
var d1 = "ABCDEFGHIJKLMNOPQR".split("");
var d2 = "ABCDEFGHIJKLMNOPQRSTUVWX".split("");
var d4 = new Array(0 ,1 ,1 ,1 ,1 ,1 ,2 ,2 ,2 ,2 ,3 ,3 ,3 ,3 ,3 ,4 ,4 ,4 ,5 ,5 ,5 );
var locator = "";
var x = lon;
var y = lat;
var precision = d4[Math.round(map.getZoom())];
while (x < -180) {x += 360;}
while (x > 180) {x -=360;}
x = x + 180;
y = y + 90;
locator = locator + d1[Math.floor(x/20)] + d1[Math.floor(y/10)];
for (var i=0; i<4; i=i+1) {
if (precision > i+1) {
rlon = x%(ydiv_arr[i]*2);
rlat = y%(ydiv_arr[i]);
if ((i%2)==0) {
locator += Math.floor(rlon/(ydiv_arr[i+1]*2)) +""+ Math.floor(rlat/(ydiv_arr[i+1]));
} else {
locator += d2[Math.floor(rlon/(ydiv_arr[i+1]*2))] +""+ d2[Math.floor(rlat/(ydiv_arr[i+1]))];
}
}
}
return locator;
},
});
L.maidenhead = function (options) {
return new L.Maidenhead(options);
};
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
/**
* Minified by jsDelivr using Terser v5.37.0.
* Original file: /npm/@joergdietrich/leaflet.terminator@1.1.0/L.Terminator.js
*
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
*/
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i(require("leaflet")):"function"==typeof define&&define.amd?define(["leaflet"],i):(t.L=t.L||{},t.L.terminator=i(t.L))}(this,(function(t){"use strict";var i=(t=t&&t.hasOwnProperty("default")?t.default:t).Polygon.extend({options:{color:"#00",opacity:.5,fillColor:"#00",fillOpacity:.5,resolution:2},initialize:function(i){this.version="0.1.0",this._R2D=180/Math.PI,this._D2R=Math.PI/180,t.Util.setOptions(this,i);var n=this._compute(this.options.time);this.setLatLngs(n)},setTime:function(t){this.options.time=t;var i=this._compute(t);this.setLatLngs(i)},_sunEclipticPosition:function(t){var i=t-2451545,n=280.46+.9856474*i,e=357.528+.9856003*i;return e%=360,{lambda:(n%=360)+1.915*Math.sin(e*this._D2R)+.02*Math.sin(2*e*this._D2R),R:1.00014-.01671*Math.cos(e*this._D2R)-.0014*Math.cos(2*e*this._D2R)}},_eclipticObliquity:function(t){var i=(t-2451545)/36525;return 23.43929111-i*(46.836769/3600-i*(1831e-7/3600+i*(5.565e-7-i*(1.6e-10-4.34e-8*i/3600))))},_sunEquatorialPosition:function(t,i){var n=Math.atan(Math.cos(i*this._D2R)*Math.tan(t*this._D2R))*this._R2D,e=Math.asin(Math.sin(i*this._D2R)*Math.sin(t*this._D2R))*this._R2D;return{alpha:n+=90*Math.floor(t/90)-90*Math.floor(n/90),delta:e}},_hourAngle:function(t,i,n){return 15*(n+t/15)-i.alpha},_latitude:function(t,i){return Math.atan(-Math.cos(t*this._D2R)/Math.tan(i.delta*this._D2R))*this._R2D},_compute:function(t){for(var i=t?new Date(t):new Date,n=i/864e5+2440587.5,e=function(t){return(18.697374558+24.06570982441908*(t-2451545))%24}(n),o=[],s=this._sunEclipticPosition(n),a=this._eclipticObliquity(n),h=this._sunEquatorialPosition(s.lambda,a),r=0;r<=720*this.options.resolution;r++){var u=r/this.options.resolution-360,l=this._hourAngle(u,h,e);o[r+1]=[this._latitude(l,h),u]}return h.delta<0?(o[0]=[90,-360],o[o.length]=[90,360]):(o[0]=[-90,-360],o[o.length]=[-90,360]),o}});return function(t){return new i(t)}}));
//# sourceMappingURL=/sm/0ad6cc527a0e7748dc9ea3acda4c2088f86401baae9f9dddc41fc73f9afa2de2.map
File diff suppressed because one or more lines are too long
+259
View File
@@ -0,0 +1,259 @@
L.WorkedAllBritainIreland = L.LayerGroup.extend({
options: {
// Line and label color
color: 'rgba(80, 80, 80, 1)',
// Grid squares to draw
gbSquares: ["HP", "HT", "HU", "HW", "HX", "HY", "HZ", "NA", "NB", "NC", "ND", "NF", "NG", "NH", "NJ", "NK", "NL", "NM", "NN", "NO", "NR", "NS", "NT", "NU", "NW", "NX", "NY", "NZ", "OV", "SC", "SD", "SE", "SH", "SJ", "SK", "SM", "SN", "SO", "SP", "SR", "SS", "ST", "SU", "SV", "SW", "SX", "SY", "SZ", "TA", "TF", "TG", "TL", "TM", "TR", "TQ", "TV"],
ieSquares: ["B", "C", "D", "F", "G", "H", "J", "L", "M", "N", "O", "Q", "R", "S", "T", "V", "W", "X"],
ciSquares: ["WA", "WV"]
},
initialize: function (options) {
// Initialise the LayerGroup superclass and set the options for this class.
L.LayerGroup.prototype.initialize.call(this);
L.Util.setOptions(this, options);
// Workaround to load the geodesy modules in non-modular code. Once we have loaded all three modules, trigger a
// first draw.
import("https://misc.ianrenton.com/Leaflet.WorkedAllBritainIreland/modules/geodesy/osgridref.js")
.then(module => {
this._osGridLibrary = module;
if (this._ieGridLibrary && this._utmLibrary) {
this.redraw();
}
})
.catch(error => {
console.log("Error loading OS Grid Ref library, GB WAB squares may not be available.");
console.log(error);
});
import("https://misc.ianrenton.com/Leaflet.WorkedAllBritainIreland/modules/geodesy/iegridref.js")
.then(module => {
this._ieGridLibrary = module;
if (this._osGridLibrary && this._utmLibrary) {
this.redraw();
}
})
.catch(error => {
console.log("Error loading IE Grid Ref library, NI WAB squares may not be available.");
console.log(error);
});
import("https://misc.ianrenton.com/Leaflet.WorkedAllBritainIreland/modules/geodesy/utm_ci.js")
.then(module => {
this._utmLibrary = module;
if (this._osGridLibrary && this._ieGridLibrary) {
this.redraw();
}
})
.catch(error => {
console.log("Error loading UTM library, Channel Islands WAB squares may not be available.");
console.log(error);
});
},
onAdd: function (map) {
this._map = map;
var grid = this.redraw();
map.on('moveend', function () { grid.redraw(); });
map.on('zoomend', function () { grid.redraw(); });
this.eachLayer(map.addLayer, map);
},
onRemove: function (map) {
map.off('moveend', this.map);
map.off('zoomend', this.map);
this.eachLayer(this.removeLayer, this);
},
redraw: function () {
// Don't proceed unless we have a map object and our libraries are loaded
if (this._map && this._osGridLibrary && this._ieGridLibrary && this._utmLibrary) {
// Remove existing content
this.eachLayer(this.removeLayer, this);
// Determine detail level based on current map zoom.
const detailLevel = (map.getZoom() > 4) ? (map.getZoom() > 8) ? 2 : 1 : 0;
// Generate new content for the three grid systems.
this.options.gbSquares.forEach(squareRef => {
this._addWABGraphicsForSquare(squareRef, "GB", detailLevel);
});
this.options.ieSquares.forEach(squareRef => {
this._addWABGraphicsForSquare(squareRef, "IE", detailLevel);
});
this.options.ciSquares.forEach(squareRef => {
this._addWABGraphicsForSquare(squareRef, "CI", detailLevel);
});
}
return this;
},
// Add WAB graphics to the layer for the given square, using the given grid system ("GB", "IE" or "CI") and the
// required level of detail.
_addWABGraphicsForSquare: function (squareRef, gridSystem, detailLevel) {
if (detailLevel === 0 || detailLevel === 1) {
// If detail level is 0 or 1, we want a single large square.
const swCorner = this._gridRefToLatLon(squareRef + " 00000 00000", gridSystem);
const nwCorner = this._gridRefToLatLon(squareRef + " 99999 00000", gridSystem);
const neCorner = this._gridRefToLatLon(squareRef + " 99999 99999", gridSystem);
const seCorner = this._gridRefToLatLon(squareRef + " 00000 99999", gridSystem);
const centre = this._gridRefToLatLon(squareRef + " 50000 50000", gridSystem);
let square = L.polygon([swCorner, nwCorner, neCorner, seCorner], {color: this.options.color, interactive: false});
this.addLayer(square);
// Additionally if detail level is 1, we want to label it.
if (detailLevel === 1) {
let label = new L.marker(centre, {
icon: new L.DivIcon({
html: '<span style="position: relative; top: -40%; left: -40%; text-align: center; cursor: hand; color:'+this.options.color+'; font-weight: bold; font-size:120%;">' + squareRef + '</font></span>',
className: 'wabSquareLabel' // Prevent default background & border and provide ability to customise
})
}, clickable=false);
this.addLayer(label);
}
} else if (detailLevel === 2) {
// If detail level is 2, we want to generate all the inner squares (with labels)
// instead of just one square. But, doing this for every square will cause CPU issues,
// so we only want to generate graphics if they would actually end up on screen.
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
// Bail out if we have a grid reference that doesn't apply. This is where GB grid overlaps with NI etc.
// are deconflicted.
if (this._validSmallSquare(squareRef, i, j)) {
// If we get this far, now calculate the coordinates of the box.
const swCorner = this._gridRefToLatLon(squareRef + " " + i + "0000 " + j + "0000", gridSystem);
const nwCorner = this._gridRefToLatLon(squareRef + " " + i + "9999 " + j + "0000", gridSystem);
const neCorner = this._gridRefToLatLon(squareRef + " " + i + "9999 " + j + "9999", gridSystem);
const seCorner = this._gridRefToLatLon(squareRef + " " + i + "0000 " + j + "9999", gridSystem);
const centre = this._gridRefToLatLon(squareRef + " " + i + "5000 " + j + "5000", gridSystem);
// Find out if this box is going to be on our screen. If not, don't draw anything.
if (map.getBounds().contains(swCorner) || map.getBounds().contains(nwCorner)
|| map.getBounds().contains(neCorner) || map.getBounds().contains(seCorner)) {
let square = L.polygon([swCorner, nwCorner, neCorner, seCorner], {color: this.options.color, interactive: false});
this.addLayer(square);
let label = new L.marker(centre, {
icon: new L.DivIcon({
html: '<span style="position: relative; top: -20%; left: -100%; text-align: center; cursor: hand; color:'+this.options.color+'; font-weight: bold; font-size:120%;">' + squareRef + i + j + '</font></span>',
className: 'wabSquareLabelLong' // Prevent default background & border and provide ability to customise
})
}, clickable=false);
this.addLayer(label);
}
}
}
}
}
},
// Determine if a given small square is OK to draw. This is where e.g. overlapping GB and IE squares are
// deconflicted in the Irish Sea.
_validSmallSquare: function (squareRef, i, j) {
let valid = true;
if (squareRef === "WA" && j > 1) {
valid = false;
} else if (squareRef === "TR" && i > 4 && j < 5) {
valid = false;
} else if (squareRef === "SM" && i < 4) {
valid = false;
} else if (squareRef === "SM" && i < 7 && j > 4) {
valid = false;
} else if (squareRef === "TV" && i === 9 && j === 0) {
valid = false;
} else if (squareRef === "NW" && i < 9) {
valid = false;
} else if (squareRef === "NR" && i < 5 && j < 3) {
valid = false;
} else if (squareRef === "C" && j > 6) {
valid = false;
} else if (squareRef === "D" && (i > 5 || j > 5 || (i > 2 && j > 3))) {
valid = false;
} else if (squareRef === "J" && i > 6) {
valid = false;
} else if (squareRef === "O" && i > 8) {
valid = false;
} else if (squareRef === "T" && i > 6 && j < 5) {
valid = false;
}
return valid;
},
// Convert the given grid reference to lat/lon, using the given grid system ("GB", "IE" or "CI")
_gridRefToLatLon: function (grid, gridSystem) {
if (gridSystem === "GB") {
return this._osgbGridRefToLatLon(grid);
} else if (gridSystem === "IE") {
return this._osieGridRefToLatLon(grid);
} else if (gridSystem === "CI") {
return this._ciGridRefToLatLon(grid);
} else {
return null;
}
},
// OSGB grid reference to lat/lon
_osgbGridRefToLatLon: function (grid) {
if (this._osGridLibrary) {
return this._osGridLibrary.default.parse(grid).toLatLon();
} else {
return null;
}
},
// Lat/lon to OSGB grid reference
_latLonToOSGBGridRef: function (lat, lon) {
if (this._osGridLibrary) {
return new this._osGridLibrary.LatLon(lat, lon).toOsGrid();
} else {
return null;
}
},
// OSIE grid reference to lat/lon
_osieGridRefToLatLon: function (grid) {
if (this._ieGridLibrary) {
return this._ieGridLibrary.default.parse(grid).toLatLon();
} else {
return null;
}
},
// Lat/lon to OSIE grid reference
_latLonToOSIEGridRef: function (lat, lon) {
if (this._ieGridLibrary) {
return new this._ieGridLibrary.LatLon(lat, lon).toOsGrid();
} else {
return null;
}
},
// CI grid reference to lat/lon
_ciGridRefToLatLon: function (grid) {
if (this._utmLibrary) {
return this._utmLibrary.default.parseChannelIslandGrid(grid).toLatLon();
} else {
return null;
}
},
// Lat/lon to CI grid reference
_latLonToCIGridRef: function (lat, lon) {
if (this._utmLibrary) {
let utm = (new this._utmLibrary.LatLon(lat, lon)).toUtm();
// todo convert UTM coordinate system back to CI grid ref cells
return null;
} else {
return null;
}
}
});
L.workedAllBritainIreland = function (options) {
return new L.WorkedAllBritainIreland(options);
};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
!function(){var t,n=document.createElement("pre"),h=document.createElement("canvas"),r=h.getContext("2d"),i={font:"Sans-serif",align:"left",color:"#000000",size:16,background:"rgba(0, 0, 0, 0)",stroke:0,strokeColor:"#FFFFFF",lineHeight:"1.2em",bold:!1,italic:!1};function s(t){t=String(t),n.innerText=t,n.setAttribute("style",this._style),document.body.append(n);var e=t.split("\n"),i=this.style.stroke,s=n.offsetHeight/e.length,l=.25*s;h.width=n.offsetWidth+2*i,h.height=n.offsetHeight,r.clearRect(0,0,h.width,h.height),r.fillStyle=this.style.background,r.beginPath(),r.fillRect(0,0,h.width,h.height),r.fill();var o="";switch(this.style.italic&&(o+="italic "),this.style.bold&&(o+="bold "),o+=this.style.size+"pt "+this.style.font,r.font=o,r.textAlign=this.style.align,r.lineWidth=this.style.stroke,r.strokeStyle=this.style.strokeColor,r.fillStyle=this.style.color,r.textAlign){case"center":i=h.width/2;break;case"right":i=h.width-i}e.forEach(function(t,e){this.style.stroke&&r.strokeText(t,i,s*(e+1)-l),r.fillText(t,i,s*(e+1)-l)}.bind(this)),document.body.removeChild(n)}window.TextImage=function(t){return this instanceof TextImage?(this.setStyle(t),this):new TextImage(t)},(t=window.TextImage.prototype).setStyle=function(t){for(var e in this.style=t||{},i)this.style[e]||(this.style[e]=i[e]);return this._style="font: ",this.style.italic&&(this._style+="italic "),this.style.bold&&(this._style+="bold "),this._style+=this.style.size+"pt "+this.style.font+";",this._style+="line-height:"+this.style.lineHeight+";",this._style+="text-align: "+this.style.align+";",this._style+="color: "+this.style.color+";",this._style+="background-color: "+this.style.background+";",this._style+=";padding: 0; display: block; position: fixed; top: 100%; overflow: hidden;",this},t.toDataURL=function(t){return t&&s.call(this,t),h.toDataURL()},t.toImage=function(t,e){s.call(this,t);var i=new Image;return e&&(i.onload=e),i.src=h.toDataURL(),i}}();
File diff suppressed because one or more lines are too long