Add TFR warning banner for airspace restrictions

Fetches active Temporary Flight Restrictions from the FAA website,
filters by configured state (LOCATION_STATE env var), and displays
a red warning banner at the top of the dashboard when TFRs are present.
Data is cached for 30 minutes and degrades gracefully if the FAA is unreachable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-16 18:43:34 -08:00
parent 88787b2eb1
commit 4974780d89
11 changed files with 336 additions and 3 deletions

View File

@@ -8,6 +8,8 @@ import (
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
@@ -78,6 +80,9 @@ func main() {
Logger: logger,
})
// Create FAA TFR client
faaClient := client.NewFAAClient()
// Create HTTP server
srv := server.New(cfg.Addr(), logger)
@@ -88,6 +93,7 @@ func main() {
config: cfg,
weatherSvc: weatherSvc,
assessmentSvc: assessmentSvc,
faaClient: faaClient,
}
srv.SetupRoutes(handler)
@@ -194,6 +200,12 @@ type Handler struct {
config *config.Config
weatherSvc *service.WeatherService
assessmentSvc *service.AssessmentService
faaClient *client.FAAClient
// TFR cache
tfrCache []model.TFR
tfrCacheAt time.Time
tfrCacheMu sync.RWMutex
}
// Health handles health check requests
@@ -371,6 +383,63 @@ func (h *Handler) AssessConditions(w http.ResponseWriter, r *http.Request) {
server.RespondJSON(w, 200, response)
}
const tfrCacheTTL = 30 * time.Minute
// GetTFRs handles airspace TFR requests
func (h *Handler) GetTFRs(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Check cache
h.tfrCacheMu.RLock()
if h.tfrCache != nil && time.Since(h.tfrCacheAt) < tfrCacheTTL {
tfrs := h.tfrCache
h.tfrCacheMu.RUnlock()
server.RespondJSON(w, 200, map[string]interface{}{
"tfrs": tfrs,
"count": len(tfrs),
"last_checked": h.tfrCacheAt.UTC(),
})
return
}
h.tfrCacheMu.RUnlock()
// Fetch from FAA
allTfrs, err := h.faaClient.FetchTFRs(ctx)
if err != nil {
h.logger.Error("failed to fetch TFRs", "error", err)
// Return empty on error — don't show banner
server.RespondJSON(w, 200, map[string]interface{}{
"tfrs": []model.TFR{},
"count": 0,
"last_checked": time.Now().UTC(),
})
return
}
// Filter by configured state
var filtered []model.TFR
for _, tfr := range allTfrs {
if strings.EqualFold(tfr.State, h.config.LocationState) {
filtered = append(filtered, tfr)
}
}
if filtered == nil {
filtered = []model.TFR{}
}
// Update cache
h.tfrCacheMu.Lock()
h.tfrCache = filtered
h.tfrCacheAt = time.Now()
h.tfrCacheMu.Unlock()
server.RespondJSON(w, 200, map[string]interface{}{
"tfrs": filtered,
"count": len(filtered),
"last_checked": time.Now().UTC(),
})
}
// WeatherFetcher runs background weather fetching
type WeatherFetcher struct {
logger *slog.Logger

View File

@@ -0,0 +1,136 @@
package client
import (
"context"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"time"
"github.com/scottyah/paragliding/internal/model"
)
const (
faaTFRListURL = "https://tfr.faa.gov/tfr2/list.jsp"
faaBaseURL = "https://tfr.faa.gov"
)
// FAAClient fetches TFR data from the FAA website
type FAAClient struct {
httpClient *http.Client
}
// NewFAAClient creates a new FAA TFR client
func NewFAAClient() *FAAClient {
return &FAAClient{
httpClient: &http.Client{
Timeout: 15 * time.Second,
},
}
}
var (
anchorRe = regexp.MustCompile(`(?is)<a\s+([^>]*)>(.*?)</a>`)
hrefRe = regexp.MustCompile(`(?i)href="([^"]*)"`)
dateRe = regexp.MustCompile(`^\d{2}/\d{2}/\d{4}$`)
htmlTagRe = regexp.MustCompile(`<[^>]*>`)
)
type anchor struct {
href string
text string
}
// FetchTFRs retrieves the list of active TFRs from the FAA website
func (c *FAAClient) FetchTFRs(ctx context.Context) ([]model.TFR, error) {
req, err := http.NewRequestWithContext(ctx, "GET", faaTFRListURL, nil)
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("User-Agent", "ParaglidingWeatherApp/1.0")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("fetch TFR list: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("TFR list returned status %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
return parseTFRList(string(body)), nil
}
// extractAnchors finds all <a> tags in HTML and returns their href and text content
func extractAnchors(html string) []anchor {
matches := anchorRe.FindAllStringSubmatch(html, -1)
anchors := make([]anchor, 0, len(matches))
for _, m := range matches {
text := htmlTagRe.ReplaceAllString(m[2], "")
text = strings.TrimSpace(text)
a := anchor{text: text}
if hrefMatch := hrefRe.FindStringSubmatch(m[1]); hrefMatch != nil {
a.href = hrefMatch[1]
}
anchors = append(anchors, a)
}
return anchors
}
// parseTFRList extracts TFR entries from the FAA list page HTML.
// The page contains a table where each row has anchor tags for:
// date, notam ID (with detail link), facility, state, type, description, zoom link
func parseTFRList(html string) []model.TFR {
rows := strings.Split(html, "<tr")
var tfrs []model.TFR
for _, row := range rows {
anchors := extractAnchors(row)
if len(anchors) < 6 {
continue
}
// First anchor should contain a date (mm/dd/yyyy)
if !dateRe.MatchString(anchors[0].text) {
continue
}
// Build detail URL from the NOTAM anchor's href
detailURL := anchors[1].href
if detailURL != "" {
detailURL = strings.Replace(detailURL, "..", faaBaseURL, 1)
detailURL = strings.ReplaceAll(detailURL, "\n", "")
detailURL = strings.ReplaceAll(detailURL, "\r", "")
}
desc := anchors[5].text
desc = strings.ReplaceAll(desc, "\n", "")
desc = strings.ReplaceAll(desc, "\r", "")
// Collapse multiple spaces
for strings.Contains(desc, " ") {
desc = strings.ReplaceAll(desc, " ", " ")
}
tfr := model.TFR{
Date: anchors[0].text,
NotamID: anchors[1].text,
Facility: anchors[2].text,
State: anchors[3].text,
Type: anchors[4].text,
Description: strings.TrimSpace(desc),
DetailURL: detailURL,
}
tfrs = append(tfrs, tfr)
}
return tfrs
}

View File

@@ -20,6 +20,9 @@ type Config struct {
LocationLon float64 `envconfig:"LOCATION_LON" default:"-122.4194"`
LocationName string `envconfig:"LOCATION_NAME" default:"San Francisco"`
// Location state (for filtering TFRs)
LocationState string `envconfig:"LOCATION_STATE" default:"CA"`
// Timezone configuration
Timezone string `envconfig:"TIMEZONE" default:"America/Los_Angeles"`

View File

@@ -0,0 +1,12 @@
package model
// TFR represents a Temporary Flight Restriction
type TFR struct {
Date string `json:"date"`
NotamID string `json:"notam_id"`
Facility string `json:"facility"`
State string `json:"state"`
Type string `json:"type"`
Description string `json:"description"`
DetailURL string `json:"detail_url"`
}

View File

@@ -14,6 +14,7 @@ type RouteHandler interface {
GetForecast(w http.ResponseWriter, r *http.Request)
GetHistorical(w http.ResponseWriter, r *http.Request)
AssessConditions(w http.ResponseWriter, r *http.Request)
GetTFRs(w http.ResponseWriter, r *http.Request)
}
// SetupRoutes configures all API routes
@@ -30,6 +31,11 @@ func (s *Server) SetupRoutes(handler RouteHandler) {
r.Get("/historical", handler.GetHistorical)
r.Post("/assess", handler.AssessConditions)
})
// Airspace routes
r.Route("/airspace", func(r chi.Router) {
r.Get("/tfrs", handler.GetTFRs)
})
})
}