diff --git a/app.go b/app.go index 13e6cf1..d1bc21f 100644 --- a/app.go +++ b/app.go @@ -74,6 +74,7 @@ import ( "hamlog/internal/tunergenius" "hamlog/internal/uls" "hamlog/internal/ultrabeam" + "hamlog/internal/watchlist" "hamlog/internal/winkeyer" wruntime "github.com/wailsapp/wails/v2/pkg/runtime" @@ -735,6 +736,9 @@ type App struct { uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened awardRefs *awardref.Repo qslTemplates *qslcard.Repo + watchlist *watchlist.Store // Tools → Watchlist (global watchlist.json) + watchAlertMu sync.Mutex // throttles watchlist alerts… + watchAlertAt map[string]time.Time // …per entry operating *operating.Repo udp *udp.Manager udpRepo *udp.Repo @@ -1385,6 +1389,8 @@ func (a *App) startup(ctx context.Context) { // POTA: background poller of api.pota.app so cluster spots can be tagged // when the DX station is currently activating a park. Best-effort. a.pota = pota.New(func(format string, args ...any) { applog.Printf(format, args...) }) + a.watchlist = watchlist.New(filepath.Join(a.dataDir, "watchlist.json")) + a.watchAlertAt = map[string]time.Time{} go a.pota.Run(a.ctx) // DX Cluster (multi-server): the spot callback enriches each spot @@ -1796,6 +1802,9 @@ func (a *App) setSettingGlobal(key, val string) { } func (a *App) shutdown(ctx context.Context) { + if a.watchlist != nil { + a.watchlist.Flush() // the save debounce would lose the last edits + } // If the user managed to skip beforeClose (force kill, OS shutdown, // crash recovery) we still try the backup here as a best-effort // safety net. HasBackupToday makes a double-run a no-op. @@ -9003,6 +9012,10 @@ func (a *App) clusterEventWorker() { a.detectBandOpening(s) // Fire any matching alert rules (sound / visual / e-mail). a.evaluateAlerts(s) + // The watchlist sees the same live stream the alerts do — never the + // SH/DX replay above, which would mark forty stations "just seen" with + // spots from three hours ago. + a.watchSpot(s.DXCall, s.Band, alerts.InferMode(s.Comment, s.FreqHz), s.Country, s.Comment, s.FreqHz) // Mirror the spot onto the FlexRadio panadapter when enabled. Infer the // mode (from the comment, else the band plan) so clicking the spot on the // panadapter tunes AND switches mode — a DX cluster line carries no mode, diff --git a/app_watchlist.go b/app_watchlist.go new file mode 100644 index 0000000..f26821d --- /dev/null +++ b/app_watchlist.go @@ -0,0 +1,145 @@ +package main + +// Watchlist bindings — the DXHunter watchlist concept as an OpsLog tab. +// The store lives in internal/watchlist (global watchlist.json, DXHunter's own +// schema); this file is the Wails boundary plus the two places the list meets +// the rest of the app: the spot stream (MarkSeen + alert) and the logbook (the +// worked-today answer contest entries are judged by). + +import ( + "fmt" + "strings" + "time" + + "hamlog/internal/qso" + "hamlog/internal/watchlist" + + wruntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +// WatchlistEntries returns the list for the tab. +func (a *App) WatchlistEntries() []watchlist.Entry { + if a.watchlist == nil { + return nil + } + return a.watchlist.Entries() +} + +// WatchlistAdd adds a callsign or prefix; contest entries are judged per UTC day. +func (a *App) WatchlistAdd(callsign string, contest bool) error { + if a.watchlist == nil { + return fmt.Errorf("watchlist not initialized") + } + return a.watchlist.Add(callsign, contest) +} + +// WatchlistRemove deletes an entry. +func (a *App) WatchlistRemove(callsign string) error { + if a.watchlist == nil { + return fmt.Errorf("watchlist not initialized") + } + return a.watchlist.Remove(callsign) +} + +// WatchlistSetNotify arms the existing alert path (sound + toast) for an entry. +func (a *App) WatchlistSetNotify(callsign string, on bool) error { + if a.watchlist == nil { + return fmt.Errorf("watchlist not initialized") + } + return a.watchlist.SetNotify(callsign, on) +} + +// WatchlistSetContest flips the per-entry contest rule. +func (a *App) WatchlistSetContest(callsign string, on bool) error { + if a.watchlist == nil { + return fmt.Errorf("watchlist not initialized") + } + return a.watchlist.SetContest(callsign, on) +} + +// WatchlistSlotQuery asks whether one spot's slot is worked — against the whole +// log for a normal entry, against TODAY (UTC) for a contest one. +type WatchlistSlotQuery struct { + Call string `json:"call"` + Band string `json:"band"` + Mode string `json:"mode"` + Contest bool `json:"contest"` +} + +// WatchlistWorkedSlots answers a batch of slot questions for the tab. +// +// One pass over today's contacts and the in-memory worked index rather than a +// query per spot: the tab refreshes on every spot burst, and a busy evening +// must not turn into a query storm. Contest entries read the TODAY set — the +// midnight-UTC reset is the query's date bound, nothing stored, nothing to +// reset. Mode is compared at CLASS grain (FT8 and FT4 are both Digital), +// matching how the cluster's own worked_slot judges a slot. +func (a *App) WatchlistWorkedSlots(queries []WatchlistSlotQuery) []bool { + out := make([]bool, len(queries)) + if a.qso == nil || len(queries) == 0 { + return out + } + // Today's slots, only if some entry needs them. + needToday := false + for _, q := range queries { + if q.Contest { + needToday = true + break + } + } + today := map[string]bool{} + if needToday { + midnight := time.Now().UTC().Truncate(24 * time.Hour) + rows, err := a.qso.SlotsSince(a.ctx, midnight) + if err == nil { + for _, r := range rows { + today[wcbmKey(r.Callsign, r.Band, qso.ModeClass(r.Mode))] = true + } + } + } + for i, q := range queries { + key := wcbmKey(q.Call, q.Band, qso.ModeClass(q.Mode)) + if q.Contest { + out[i] = today[key] + } else { + out[i] = a.isWorkedBandMode(q.Call, q.Band, qso.ModeClass(q.Mode)) + } + } + return out +} + +// watchSpot runs one live spot through the watchlist: last-seen bookkeeping and +// the alert, through the SAME event the alert rules fire — the frontend already +// knows how to toast and sound it, and a second notification path would be a +// second thing to misconfigure. +func (a *App) watchSpot(dxCall, band, mode, country, comment string, freqHz int64) { + if a.watchlist == nil { + return + } + entry, notify, ok := a.watchlist.MarkSeen(dxCall) + if !ok || !notify || a.ctx == nil { + return + } + // Throttled per entry: a DXpedition lights up every skimmer on the planet, + // and forty alerts a minute for one station is a alarm nobody keeps on. + a.watchAlertMu.Lock() + last := a.watchAlertAt[entry] + now := time.Now() + if now.Sub(last) < 2*time.Minute { + a.watchAlertMu.Unlock() + return + } + a.watchAlertAt[entry] = now + a.watchAlertMu.Unlock() + wruntime.EventsEmit(a.ctx, "alert:fired", map[string]any{ + "rule": "Watchlist " + entry, + "call": strings.ToUpper(strings.TrimSpace(dxCall)), + "band": band, + "mode": mode, + "freq_hz": freqHz, + "country": country, + "comment": comment, + "sound": true, + "visual": true, + }) +} diff --git a/changelog.json b/changelog.json index 85d5512..86705cb 100644 --- a/changelog.json +++ b/changelog.json @@ -9,7 +9,8 @@ "Elecraft console: a mode row — CW, USB, LSB, DATA and DATA RTTY. The two DATA buttons set the K3’s submode as well (DATA A for FT8/FT4, FSK D for RTTY): switching to DATA by mode alone kept whatever submode the last session left, which is how a K3 “in DATA” keys FT8 with no audio.", "DX Cluster settings: “I chase POTA” and “I chase SOTA”, on by default. Unticked, the NEW POTA badge, colour and filter disappear — a new-band + new-POTA spot reads NEW BAND alone — and the reference columns stay empty.", "Elecraft console: RIT and XIT use the same control as the Icom and TCI consoles — ± buttons, mouse wheel, typed value, Ctrl+←/→ — and the power slider moves in 1 W steps instead of 5.", - "Bulk edit: My DXCC, My CQ zone and My ITU zone join the My-station fields — numbers checked against their real ranges, empty clears." + "Bulk edit: My DXCC, My CQ zone and My ITU zone join the My-station fields — numbers checked against their real ranges, empty clears.", + "Watchlist (Tools): the DXHunter watchlist as an OpsLog tab — callsigns or prefixes you are hunting, the live cluster spots under each with the NEW badges and a Needed/Worked verdict per slot, an ON AIR badge, per-entry alerts through the normal alert path, and CONTEST entries judged per UTC day (at midnight everything is workable again). Reads and writes DXHunter’s own watchlist.json format — drop your existing file into the data folder to carry it over." ], "fr": [ "TCI (SunSDR) : l'abonnement aux mesures est renouvelé quand la radio annonce qu'elle est prête — envoyé seulement à la connexion, il pouvait tomber pendant l'envoi initial de l'état et être ignoré, laissant la puissance et le ROS vides en émission. Le journal enregistre aussi l'abonnement et les premières trames de mesure, pour distinguer « la radio ne les envoie jamais » de « elles arrivaient et étaient perdues ».", @@ -18,7 +19,8 @@ "Console Elecraft : une rangée de modes — CW, USB, LSB, DATA et DATA RTTY. Les deux boutons DATA règlent aussi le sous-mode du K3 (DATA A pour FT8/FT4, FSK D pour le RTTY) : passer en DATA par le seul mode gardait le sous-mode de la session précédente, et un K3 « en DATA » manipulait le FT8 sans audio.", "Réglages DX Cluster : « Je chasse le POTA » et « Je chasse le SOTA », cochés par défaut. Décochés, le badge, la couleur et le filtre NOUVEAU POTA disparaissent — un spot nouvelle bande + nouveau POTA affiche seulement NOUVELLE BANDE — et les colonnes de références restent vides.", "Console Elecraft : le RIT et le XIT utilisent la même commande que les consoles Icom et TCI — boutons ±, molette, valeur tapée, Ctrl+←/→ — et le curseur de puissance avance par pas de 1 W au lieu de 5.", - "Édition groupée : My DXCC, My CQ zone et My ITU zone rejoignent les champs Ma station — valeurs vérifiées contre leurs bornes réelles, vide efface." + "Édition groupée : My DXCC, My CQ zone et My ITU zone rejoignent les champs Ma station — valeurs vérifiées contre leurs bornes réelles, vide efface.", + "Watchlist (Outils) : la watchlist de DXHunter en onglet OpsLog — indicatifs ou préfixes chassés, les spots cluster en direct sous chaque entrée avec les badges NOUVEAU et un verdict Manquant/Contacté par créneau, un badge ON AIR, des alertes par entrée via le circuit d'alerte normal, et des entrées CONTEST jugées par jour UTC (à minuit tout redevient à faire). Lit et écrit le format watchlist.json de DXHunter — déposez votre fichier existant dans le dossier data pour le récupérer." ] }, { diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 493ac8f..daa3138 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -69,6 +69,7 @@ import { } from '@/components/ui/dropdown-menu'; import { APP_VERSION, APP_AUTHOR } from '@/version'; import { QSLManagerPanel } from '@/components/QSLManagerModal'; +import { WatchlistTab } from '@/components/WatchlistTab'; import { QslDesignerModal } from '@/components/qsl/QslDesignerModal'; import { SendEQSLModal } from '@/components/qsl/SendEQSLModal'; import { AutoEQSL } from '@/components/qsl/AutoEQSL'; @@ -1684,6 +1685,9 @@ export default function App() { // NET Control tab — enabled from Tools (persisted; once on it's a tab like Cluster). const [netEnabled, setNetEnabled] = useState(() => localStorage.getItem('opslog.netEnabled') === '1'); useEffect(() => { localStorage.setItem('opslog.netEnabled', netEnabled ? '1' : '0'); }, [netEnabled]); + // Watchlist tab — opt-in from Tools, persisted, closable like NET Control. + const [watchlistEnabled, setWatchlistEnabled] = useState(() => localStorage.getItem('opslog.watchlistEnabled') === '1'); + useEffect(() => { localStorage.setItem('opslog.watchlistEnabled', watchlistEnabled ? '1' : '0'); }, [watchlistEnabled]); // Contest tab is hidden until enabled from Tools → Contest mode. const [contestTabEnabled, setContestTabEnabled] = useState(() => localStorage.getItem('opslog.contestTab') === '1'); useEffect(() => { localStorage.setItem('opslog.contestTab', contestTabEnabled ? '1' : '0'); }, [contestTabEnabled]); @@ -5004,6 +5008,7 @@ export default function App() { { type: 'item', label: (cwEnabled ? '✓ ' : '') + t('tools.cwDecoder'), action: 'tools.cwdecoder' }, { type: 'separator' }, { type: 'item', label: (netEnabled ? '✓ ' : '') + t('tools.net'), action: 'tools.net' }, + { type: 'item', label: (watchlistEnabled ? '✓ ' : '') + t('tools.watchlist'), action: 'tools.watchlist' }, { type: 'item', label: (contestTabEnabled ? '✓ ' : '') + t('tools.contest'), action: 'tools.contest' }, { type: 'item', label: t('tools.alerts'), action: 'tools.alerts' }, { type: 'separator' }, @@ -5027,7 +5032,7 @@ export default function App() { { type: 'separator' }, { type: 'item', label: t('help.about'), action: 'help.about' }, ]}, - ], [total, selectedId, selectedIds, exporting, wkEnabled, dvkEnabled, cwEnabled, netEnabled, contestTabEnabled, smtpConfigured, sendingLog, t]); + ], [total, selectedId, selectedIds, exporting, wkEnabled, dvkEnabled, cwEnabled, netEnabled, watchlistEnabled, contestTabEnabled, smtpConfigured, sendingLog, t]); function handleMenu(action: string) { switch (action) { @@ -5055,6 +5060,7 @@ export default function App() { case 'tools.dvk': setDvkEnabled((v) => !v); break; case 'tools.cwdecoder': toggleCwDecoder(); break; case 'tools.net': setNetEnabled((v) => { const nv = !v; if (nv) setActiveTab('net'); return nv; }); break; + case 'tools.watchlist': setWatchlistEnabled((v) => { const nv = !v; if (nv) setActiveTab('watchlist'); return nv; }); break; case 'tools.contest': setContestTabEnabled((v) => { const nv = !v; if (nv) setActiveTab('contest'); else setActiveTab((tb) => (tb === 'contest' ? 'recent' : tb)); return nv; }); break; case 'tools.alerts': setAlertsOpen(true); break; case 'tools.duplicates': setShowDuplicates(true); break; @@ -7601,6 +7607,21 @@ export default function App() { )} + {watchlistEnabled && ( + + {t('tab.watchlist')} + { e.stopPropagation(); }} + onClick={(e) => { e.stopPropagation(); setWatchlistEnabled(false); setActiveTab((t) => (t === 'watchlist' ? 'recent' : t)); }} + > + + + + )} {catState.backend === 'flex' && Flex Console} {catState.backend === 'icom' && Icom Console} {catState.backend === 'yaesu' && Yaesu Console} @@ -8312,6 +8333,12 @@ export default function App() { {/* Band Map: several bands shown side-by-side (panadapter-style strips). Pick bands with the chips; each strip is clickable to tune the rig. */} + {watchlistEnabled && ( + + + + )} {netEnabled && ( ; + onSpotSelect?: (s: ClusterSpot) => void; + onSpotClick?: (s: ClusterSpot) => void; +} + +// A spot is ON AIR for the badge while its last sighting is this fresh. +const ON_AIR_MS = 10 * 60 * 1000; + +function matchesEntry(call: string, pattern: string): boolean { + const c = call.toUpperCase(); + return c === pattern || c.startsWith(pattern); +} + +export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: Props) { + const { t } = useI18n(); + const [entries, setEntries] = useState([]); + const [addCall, setAddCall] = useState(''); + const [addContest, setAddContest] = useState(false); + const [search, setSearch] = useState(''); + const [neededOnly, setNeededOnly] = useState(false); + const [activeOnly, setActiveOnly] = useState(false); + const [family, setFamily] = useState<'all' | 'normal' | 'contest'>('all'); + const [error, setError] = useState(''); + const [removeArm, setRemoveArm] = useState(''); + // worked answer per "call|band|modeclass|contest" key. + const [worked, setWorked] = useState>({}); + + const refresh = useCallback(async () => { + try { setEntries(((await WatchlistEntries()) ?? []) as any as WLEntry[]); } + catch (e: any) { setError(String(e?.message ?? e)); } + }, []); + useEffect(() => { void refresh(); }, [refresh]); + + // Live spots per entry — prefix-matched, newest first, deduped per band+mode + // (one line per slot; the freshest spot represents it). + const spotsFor = useMemo(() => { + const map = new Map(); + for (const e of entries) map.set(e.callsign, []); + for (const s of spots) { + for (const e of entries) { + if (matchesEntry(s.dx_call ?? '', e.callsign)) { map.get(e.callsign)!.push(s); break; } + } + } + for (const [k, list] of map) { + const seen = new Set(); + map.set(k, list.filter((s) => { + const key = `${(s.band ?? '')}|${inferSpotMode(s.comment ?? '', s.freq_hz)}|${s.dx_call}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + })); + } + return map; + }, [spots, entries]); + + // The worked answers, refreshed when the visible slots change. Debounced: a + // spot burst must cost one round trip, not one per spot. + const queryTimer = useRef(undefined); + useEffect(() => { + if (queryTimer.current) window.clearTimeout(queryTimer.current); + queryTimer.current = window.setTimeout(async () => { + const queries: { call: string; band: string; mode: string; contest: boolean }[] = []; + const keys: string[] = []; + for (const e of entries) { + for (const s of spotsFor.get(e.callsign) ?? []) { + const mode = inferSpotMode(s.comment ?? '', s.freq_hz) || ''; + queries.push({ call: s.dx_call, band: s.band ?? '', mode, contest: e.isContest }); + keys.push(`${s.dx_call}|${s.band ?? ''}|${mode}|${e.isContest ? 1 : 0}`); + } + } + if (queries.length === 0) { setWorked({}); return; } + try { + const res: boolean[] = (await WatchlistWorkedSlots(queries as any)) ?? []; + const next: Record = {}; + keys.forEach((k, i) => { next[k] = !!res[i]; }); + setWorked(next); + } catch { /* the badges just stay conservative */ } + }, 400) as unknown as number; + return () => { if (queryTimer.current) window.clearTimeout(queryTimer.current); }; + }, [spotsFor, entries]); + + const workedFor = (e: WLEntry, s: ClusterSpot): boolean => + worked[`${s.dx_call}|${s.band ?? ''}|${inferSpotMode(s.comment ?? '', s.freq_hz) || ''}|${e.isContest ? 1 : 0}`] ?? false; + + const add = async () => { + const c = addCall.trim().toUpperCase(); + if (!c) return; + setError(''); + try { await WatchlistAdd(c, addContest); setAddCall(''); await refresh(); } + catch (e: any) { setError(String(e?.message ?? e)); } + }; + + const remove = async (call: string) => { + if (removeArm !== call) { setRemoveArm(call); window.setTimeout(() => setRemoveArm(''), 2500); return; } + try { await WatchlistRemove(call); await refresh(); } + catch (e: any) { setError(String(e?.message ?? e)); } + }; + + const isOnAir = (e: WLEntry): boolean => + (spotsFor.get(e.callsign) ?? []).some((s) => { + const ts = Date.parse(String((s as any).received_at ?? '')); + return ts > 0 && Date.now() - ts < ON_AIR_MS; + }); + + const shown = entries.filter((e) => { + if (family === 'normal' && e.isContest) return false; + if (family === 'contest' && !e.isContest) return false; + if (search && !e.callsign.includes(search.trim().toUpperCase())) return false; + if (activeOnly && (spotsFor.get(e.callsign) ?? []).length === 0) return false; + if (neededOnly && !(spotsFor.get(e.callsign) ?? []).some((s) => !workedFor(e, s))) return false; + return true; + }); + + // The cluster's own badge for a spot, read from the shared status index. + const dxccBadge = (s: ClusterSpot): { label: string; color: string } | null => { + const st = spotStatus[spotStatusKey(s.dx_call, s.band ?? '', s.comment ?? '', s.freq_hz)]; + switch (st?.status) { + case 'new': return { label: t('wl.newDxcc'), color: 'var(--danger)' }; + case 'new-band-mode': return { label: t('clg2.newBandMode'), color: 'var(--danger)' }; + case 'new-band': return { label: t('clg2.newBand'), color: 'var(--warning)' }; + case 'new-mode': return { label: t('clg2.newMode'), color: 'var(--caution)' }; + case 'new-slot': return { label: t('clg2.newSlot'), color: '#5AC8FA' }; + default: return null; + } + }; + + const chip = (color: string, text: string, extra?: string) => ( + + {text} + + ); + + return ( +
+ {/* toolbar */} +
+ + setAddCall(e.target.value)} + onKeyDown={(e) => { if (e.key === 'Enter') void add(); }} /> + + +
+
+ + setSearch(e.target.value)} /> +
+ {/* families kept together, told apart — per review of the DXHunter port, + no global contest mode: each entry carries its own rule. */} +
+ {([['all', t('wl.famAll')], ['normal', t('wl.famNormal')], ['contest', t('wl.famContest')]] as const).map(([k, label]) => ( + + ))} +
+ + +
+ {error &&
{error}
} + + {/* cards */} +
+ {shown.length === 0 ? ( +
+ {entries.length === 0 ? t('wl.empty') : t('wl.noneMatch')} +
+ ) : shown.map((e) => { + const list = spotsFor.get(e.callsign) ?? []; + const needed = list.filter((s) => !workedFor(e, s)).length; + return ( +
0 ? 'border-warning/50' : 'border-border', + e.isContest && 'border-l-4 border-l-warning')}> +
+ {e.callsign} + {isOnAir(e) && chip('var(--danger)', t('wl.onAir'), 'animate-pulse')} + {e.isContest && ( + + {t('wl.contest')} + + )} + {e.isExpedition && chip('var(--chart-5)', t('wl.expedition'))} + {e.clubLogTotalQSOs > 0 && {e.clubLogTotalQSOs.toLocaleString()} QSOs} + {e.clubLogHasOQRS && chip('var(--success)', 'OQRS')} + {list.length > 0 && (needed > 0 + ? chip('var(--warning)', e.isContest ? t('wl.nToday', { n: needed }) : t('wl.nNeeded', { n: needed })) + : chip('var(--success)', e.isContest ? t('wl.workedToday') : t('wl.allWorked')))} + {e.lastSeenStr && e.lastSeenStr !== 'Never' && ( + · {e.lastSeenStr} + )} + {e.spotCount > 0 && ( + · {t('wl.totalSpots', { n: e.spotCount })} + )} +
+ + + +
+ + {list.length > 0 ? ( +
+ {list.slice(0, 12).map((s, i) => { + const done = workedFor(e, s); + const badge = dxccBadge(s); + const mode = inferSpotMode(s.comment ?? '', s.freq_hz); + return ( + + ); + })} +
+ ) : ( +
+ {t('wl.noSpots')} +
+ )} +
+ ); + })} +
+
+ ); +} diff --git a/frontend/src/lib/i18n.tsx b/frontend/src/lib/i18n.tsx index 9079b1b..f110b84 100644 --- a/frontend/src/lib/i18n.tsx +++ b/frontend/src/lib/i18n.tsx @@ -38,6 +38,20 @@ const en: Dict = { 'cwd.tipOnCw': 'CW decoder — on (decoding) · click to disable', 'cwd.tipOnIdle': 'CW decoder — on, idle until CW mode · click to disable', 'cwd.tipOff': 'CW decoder · click to enable (decodes RX audio in CW mode)', + 'tools.watchlist': 'Watchlist…', 'tab.watchlist': 'Watchlist', + 'wl.addPh': 'Callsign or prefix', 'wl.add': 'Add', 'wl.contest': 'Contest', + 'wl.contestHint': 'Contest station: worked/needed is judged against the current UTC day — at 00:00 UTC every slot can be worked again.', + 'wl.searchPh': 'Search…', 'wl.famAll': 'All', 'wl.famNormal': 'DX', 'wl.famContest': 'Contest', + 'wl.activeOnly': 'Active only', 'wl.neededOnly': 'Needed only', + 'wl.empty': 'Add the callsigns or prefixes you are hunting — a prefix catches the portable forms too (RI0SP matches RI0SP/MM). Spots from the cluster appear under each entry with what they are worth.', + 'wl.noneMatch': 'Nothing matches the current filters.', + 'wl.onAir': 'ON AIR', 'wl.expedition': 'DXpedition', + 'wl.nNeeded': '{n} needed', 'wl.nToday': '{n} today', 'wl.allWorked': 'All worked', 'wl.workedToday': 'Worked today', + 'wl.totalSpots': '{n} spots', 'wl.toggleContest': 'Contest entry: judged per UTC day', + 'wl.notifyOn': 'Alert me when this station is spotted', 'wl.notifyOff': 'Stop alerting for this station', + 'wl.remove': 'Remove (click twice)', 'wl.noSpots': 'No live spots', + 'wl.newDxcc': 'NEW DXCC', 'wl.worked': 'Worked', 'wl.needed': 'Needed!', 'wl.todayOk': 'Today ✓', 'wl.workToday': 'Work today!', + 'wl.spotTip': 'Click: fill the callsign · double-click: tune and work', 'tools.net': 'NET Control', 'tools.alerts': 'Alert management…', 'tools.contest': 'Contest mode', 'alert.tuneHint': 'Click to tune the rig to this spot (freq + mode) and fill the call', 'alert.dismiss': 'Dismiss', 'alert.pending': '{n} recent spot alert(s) — click to view', 'alert.noneShort': 'No recent alerts', 'alert.recent': 'Recent alerts', 'alert.clear': 'Clear', 'menu.help': 'Help', 'prof.switchTitle': 'Switch station profile', 'prof.manage': 'Manage profiles…', 'logview.title': "Diagnostic log", 'logview.empty': "(log is empty)", 'logview.searchPh': "Filter lines — e.g. cluster, acom, cat", 'logview.matches': "{n} of {total} lines", 'logview.autoScroll': "Follow the end", 'logview.updated': "refreshed {time}", 'logview.copy': "Copy", 'logview.toEnd': "Jump to end", 'help.about': 'About OpsLog', 'help.donate': '♥ Support OpsLog (donate)', 'tools.duplicates': 'Find duplicates…', @@ -548,6 +562,20 @@ const fr: Dict = { 'cwd.tipOnCw': 'Décodeur CW — actif (décode) · clic pour désactiver', 'cwd.tipOnIdle': 'Décodeur CW — actif, en veille hors mode CW · clic pour désactiver', 'cwd.tipOff': 'Décodeur CW · clic pour activer (décode l’audio RX en mode CW)', + 'tools.watchlist': 'Watchlist…', 'tab.watchlist': 'Watchlist', + 'wl.addPh': 'Indicatif ou préfixe', 'wl.add': 'Ajouter', 'wl.contest': 'Contest', + 'wl.contestHint': "Station contest : contacté/manquant est jugé sur la journée UTC courante — à 00:00 UTC chaque créneau redevient à faire.", + 'wl.searchPh': 'Chercher…', 'wl.famAll': 'Tous', 'wl.famNormal': 'DX', 'wl.famContest': 'Contest', + 'wl.activeOnly': 'Actifs seulement', 'wl.neededOnly': 'Manquants seulement', + 'wl.empty': "Ajoutez les indicatifs ou préfixes que vous chassez — un préfixe attrape aussi les formes portables (RI0SP matche RI0SP/MM). Les spots du cluster apparaissent sous chaque entrée avec ce qu'ils valent.", + 'wl.noneMatch': 'Rien ne correspond aux filtres actuels.', + 'wl.onAir': 'ON AIR', 'wl.expedition': 'DXpédition', + 'wl.nNeeded': '{n} manquants', 'wl.nToday': "{n} aujourd'hui", 'wl.allWorked': 'Tout contacté', 'wl.workedToday': "Contacté aujourd'hui", + 'wl.totalSpots': '{n} spots', 'wl.toggleContest': 'Entrée contest : jugée par jour UTC', + 'wl.notifyOn': "M'alerter quand cette station est spottée", 'wl.notifyOff': "Ne plus alerter pour cette station", + 'wl.remove': 'Supprimer (cliquer deux fois)', 'wl.noSpots': 'Aucun spot en cours', + 'wl.newDxcc': 'NOUV DXCC', 'wl.worked': 'Contacté', 'wl.needed': 'Manquant !', 'wl.todayOk': "Auj. ✓", 'wl.workToday': "À faire auj. !", + 'wl.spotTip': "Clic : remplir l'indicatif · double-clic : régler la radio et travailler", 'tools.net': 'Contrôle de NET', 'tools.alerts': 'Gestion des alertes…', 'tools.contest': 'Mode contest', 'alert.tuneHint': 'Cliquer pour accorder la radio sur ce spot (fréq + mode) et remplir l\'indicatif', 'alert.dismiss': 'Fermer', 'alert.pending': '{n} alerte(s) de spot récente(s) — cliquer pour voir', 'alert.noneShort': 'Aucune alerte récente', 'alert.recent': 'Alertes récentes', 'alert.clear': 'Effacer', 'menu.help': 'Aide', 'prof.switchTitle': 'Changer de profil de station', 'prof.manage': 'Gérer les profils…', 'logview.title': "Journal de diagnostic", 'logview.empty': "(journal vide)", 'logview.searchPh': "Filtrer les lignes — ex. cluster, acom, cat", 'logview.matches': "{n} lignes sur {total}", 'logview.autoScroll': "Suivre la fin", 'logview.updated': "actualisé {time}", 'logview.copy': "Copier", 'logview.toEnd': "Aller à la fin", 'help.about': 'À propos d\'OpsLog', 'help.donate': '♥ Soutenir OpsLog (don)', 'tools.duplicates': 'Trouver les doublons…', diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index 54236f9..91c44fa 100644 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -30,6 +30,7 @@ import {lotwusers} from '../models'; import {lookup} from '../models'; import {netctl} from '../models'; import {scp} from '../models'; +import {watchlist} from '../models'; export function ACOMSetOperate(arg1:boolean):Promise; @@ -1357,6 +1358,18 @@ export function UploadCallsign(arg1:string):Promise; export function UploadQSOsManual(arg1:string,arg2:Array):Promise; +export function WatchlistAdd(arg1:string,arg2:boolean):Promise; + +export function WatchlistEntries():Promise>; + +export function WatchlistRemove(arg1:string):Promise; + +export function WatchlistSetContest(arg1:string,arg2:boolean):Promise; + +export function WatchlistSetNotify(arg1:string,arg2:boolean):Promise; + +export function WatchlistWorkedSlots(arg1:Array):Promise>; + export function WebPublishColumns():Promise>>; export function WinkeyerBackspace():Promise; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index dd95b75..ecc094f 100644 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -2654,6 +2654,30 @@ export function UploadQSOsManual(arg1, arg2) { return window['go']['main']['App']['UploadQSOsManual'](arg1, arg2); } +export function WatchlistAdd(arg1, arg2) { + return window['go']['main']['App']['WatchlistAdd'](arg1, arg2); +} + +export function WatchlistEntries() { + return window['go']['main']['App']['WatchlistEntries'](); +} + +export function WatchlistRemove(arg1) { + return window['go']['main']['App']['WatchlistRemove'](arg1); +} + +export function WatchlistSetContest(arg1, arg2) { + return window['go']['main']['App']['WatchlistSetContest'](arg1, arg2); +} + +export function WatchlistSetNotify(arg1, arg2) { + return window['go']['main']['App']['WatchlistSetNotify'](arg1, arg2); +} + +export function WatchlistWorkedSlots(arg1) { + return window['go']['main']['App']['WatchlistWorkedSlots'](arg1); +} + export function WebPublishColumns() { return window['go']['main']['App']['WebPublishColumns'](); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 5766cdd..1937b4a 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -4301,6 +4301,24 @@ export namespace main { this.text = source["text"]; } } + export class WatchlistSlotQuery { + call: string; + band: string; + mode: string; + contest: boolean; + + static createFrom(source: any = {}) { + return new WatchlistSlotQuery(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.call = source["call"]; + this.band = source["band"]; + this.mode = source["mode"]; + this.contest = source["contest"]; + } + } export class WebPublishStatus { last_run: string; last_err: string; @@ -5990,6 +6008,68 @@ export namespace udp { } +export namespace watchlist { + + export class Entry { + callsign: string; + // Go type: time + lastSeen: any; + lastSeenStr: string; + // Go type: time + addedAt: any; + spotCount: number; + isContest: boolean; + notify: boolean; + isExpedition: boolean; + clubLogQSOs24h: number; + clubLogTotalQSOs: number; + clubLogHasOQRS: boolean; + clubLogLiveStream: boolean; + // Go type: time + clubLogUpdatedAt?: any; + + static createFrom(source: any = {}) { + return new Entry(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.callsign = source["callsign"]; + this.lastSeen = this.convertValues(source["lastSeen"], null); + this.lastSeenStr = source["lastSeenStr"]; + this.addedAt = this.convertValues(source["addedAt"], null); + this.spotCount = source["spotCount"]; + this.isContest = source["isContest"]; + this.notify = source["notify"]; + this.isExpedition = source["isExpedition"]; + this.clubLogQSOs24h = source["clubLogQSOs24h"]; + this.clubLogTotalQSOs = source["clubLogTotalQSOs"]; + this.clubLogHasOQRS = source["clubLogHasOQRS"]; + this.clubLogLiveStream = source["clubLogLiveStream"]; + this.clubLogUpdatedAt = this.convertValues(source["clubLogUpdatedAt"], null); + } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } + } + +} + export namespace webpub { export class Config { diff --git a/internal/qso/qso.go b/internal/qso/qso.go index 6d37eaf..f862371 100644 --- a/internal/qso/qso.go +++ b/internal/qso/qso.go @@ -2003,6 +2003,43 @@ func bandStatusCode(callWorked, callConfirmed, entityConfirmed bool) int { // modeClass collapses ADIF modes into the three buckets DXers care about. // Anything not voice and not CW is treated as digital. +// ModeClass is modeClass for callers outside the package — the watchlist +// judges slots at the same grain the cluster does. +func ModeClass(mode string) string { return modeClass(mode) } + +// SlotRow is one (callsign, band, mode) triple from SlotsSince. +type SlotRow struct { + Callsign string + Band string + Mode string +} + +// SlotsSince lists the slots of every contact made since the given instant — +// the contest watchlist's "worked today", where the day boundary lives in this +// query's bound and nowhere else. +func SlotsSince(r *Repo, ctx context.Context, since time.Time) ([]SlotRow, error) { + return r.SlotsSince(ctx, since) +} + +func (r *Repo) SlotsSince(ctx context.Context, since time.Time) ([]SlotRow, error) { + rows, err := r.db.QueryContext(ctx, + "SELECT callsign, band, mode FROM qso WHERE qso_date >= ?", + since.UTC().Format(isoMillis)) + if err != nil { + return nil, err + } + defer rows.Close() + var out []SlotRow + for rows.Next() { + var sr SlotRow + if err := rows.Scan(&sr.Callsign, &sr.Band, &sr.Mode); err != nil { + return nil, err + } + out = append(out, sr) + } + return out, rows.Err() +} + func modeClass(mode string) string { switch strings.ToUpper(mode) { case "SSB", "USB", "LSB", "AM", "FM", "DIGITALVOICE", "PHONE": diff --git a/internal/watchlist/watchlist.go b/internal/watchlist/watchlist.go new file mode 100644 index 0000000..9ec3871 --- /dev/null +++ b/internal/watchlist/watchlist.go @@ -0,0 +1,236 @@ +// Package watchlist is the DXHunter watchlist, transplanted: a list of +// callsigns (or prefixes) the operator is hunting, matched against the live +// spot stream, with per-entry state that survives restarts. +// +// The JSON file is DXHunter's OWN schema, field for field — including the +// ClubLog expedition block this phase does not fill yet. Deliberate: the +// operator asked to carry their watchlist.json across, and a file that +// round-trips unchanged is the whole of "same format". The file is GLOBAL +// (dataDir, beside nets.json), not per profile: a DXpedition worth hunting is +// worth hunting whichever station is on. +// +// The CONTEST idea is per entry, not a global mode as in DXHunter: an entry +// marked contest is judged against the CURRENT UTC DAY — at midnight UTC +// yesterday's contacts stop counting and every slot reads "work today" again. +// Nothing resets and nothing is stored for it: the day boundary lives in the +// query, which is why it cannot drift or need a timer. +package watchlist + +import ( + "encoding/json" + "fmt" + "os" + "sort" + "strings" + "sync" + "time" +) + +// Entry is one watched callsign. JSON tags match DXHunter's watchlist.json +// exactly — see the package comment before renaming anything. +type Entry struct { + Callsign string `json:"callsign"` + LastSeen time.Time `json:"lastSeen"` + LastSeenStr string `json:"lastSeenStr"` + AddedAt time.Time `json:"addedAt"` + SpotCount int `json:"spotCount"` + IsContest bool `json:"isContest"` + Notify bool `json:"notify"` + // ClubLog expedition enrichment — phase 2. Carried so a DXHunter file + // round-trips; not filled by OpsLog yet. + IsExpedition bool `json:"isExpedition"` + ClubLogQSOs24h int `json:"clubLogQSOs24h"` + ClubLogTotalQSOs int `json:"clubLogTotalQSOs"` + ClubLogHasOQRS bool `json:"clubLogHasOQRS"` + ClubLogLiveStream bool `json:"clubLogLiveStream"` + ClubLogUpdatedAt time.Time `json:"clubLogUpdatedAt,omitempty"` +} + +// Store owns the file. All methods are safe for concurrent use; writes are +// debounced so a burst of MarkSeen calls costs one disk write. +type Store struct { + mu sync.RWMutex + entries map[string]*Entry + path string + + saveMu sync.Mutex + saveTimer *time.Timer + ioMu sync.Mutex +} + +func New(path string) *Store { + s := &Store{entries: map[string]*Entry{}, path: path} + s.load() + return s +} + +func (s *Store) load() { + data, err := os.ReadFile(s.path) + if err != nil { + return // absent on first run — created on first save + } + var list []Entry + if err := json.Unmarshal(data, &list); err != nil { + return // a corrupt file must not take the app down; it is left for repair + } + s.mu.Lock() + defer s.mu.Unlock() + for i := range list { + e := list[i] + e.Callsign = strings.ToUpper(strings.TrimSpace(e.Callsign)) + if e.Callsign == "" { + continue + } + s.entries[e.Callsign] = &e + } +} + +// Entries returns a snapshot, watched-first ordering left to the UI. +func (s *Store) Entries() []Entry { + s.mu.RLock() + defer s.mu.RUnlock() + out := make([]Entry, 0, len(s.entries)) + for _, e := range s.entries { + c := *e + c.LastSeenStr = lastSeenLabel(c.LastSeen) + out = append(out, c) + } + sort.Slice(out, func(i, j int) bool { return out[i].Callsign < out[j].Callsign }) + return out +} + +// Add creates an entry; contest marks it as re-workable every UTC day. +func (s *Store) Add(callsign string, contest bool) error { + call := strings.ToUpper(strings.TrimSpace(callsign)) + if call == "" { + return fmt.Errorf("callsign required") + } + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.entries[call]; ok { + return fmt.Errorf("%s is already on the watchlist", call) + } + s.entries[call] = &Entry{Callsign: call, AddedAt: time.Now(), IsContest: contest} + s.scheduleSave() + return nil +} + +// Remove deletes an entry. +func (s *Store) Remove(callsign string) error { + call := strings.ToUpper(strings.TrimSpace(callsign)) + s.mu.Lock() + defer s.mu.Unlock() + if _, ok := s.entries[call]; !ok { + return fmt.Errorf("%s is not on the watchlist", call) + } + delete(s.entries, call) + s.scheduleSave() + return nil +} + +// SetNotify arms or disarms the alert for one entry. +func (s *Store) SetNotify(callsign string, on bool) error { + return s.patch(callsign, func(e *Entry) { e.Notify = on }) +} + +// SetContest flips the per-entry contest rule. +func (s *Store) SetContest(callsign string, on bool) error { + return s.patch(callsign, func(e *Entry) { e.IsContest = on }) +} + +func (s *Store) patch(callsign string, fn func(*Entry)) error { + call := strings.ToUpper(strings.TrimSpace(callsign)) + s.mu.Lock() + defer s.mu.Unlock() + e, ok := s.entries[call] + if !ok { + return fmt.Errorf("%s is not on the watchlist", call) + } + fn(e) + s.scheduleSave() + return nil +} + +// Match returns the entry a spotted callsign belongs to, or "". +// +// Prefix match, exactly as DXHunter does it: an entry RI0SP must catch +// RI0SP/MM and RI0SP/P — expeditions sign portable more often than not, and an +// exact-only match left lastSeen stale while fresh spots scrolled past. +func (s *Store) Match(callsign string) (string, bool) { + call := strings.ToUpper(strings.TrimSpace(callsign)) + if call == "" { + return "", false + } + s.mu.RLock() + defer s.mu.RUnlock() + for pattern := range s.entries { + if call == pattern || strings.HasPrefix(call, pattern) { + return pattern, true + } + } + return "", false +} + +// MarkSeen records a spot against the matching entry and reports whether the +// entry wants an alert. +func (s *Store) MarkSeen(callsign string) (entry string, notify bool, ok bool) { + pattern, found := s.Match(callsign) + if !found { + return "", false, false + } + s.mu.Lock() + defer s.mu.Unlock() + e := s.entries[pattern] + if e == nil { + return "", false, false + } + e.LastSeen = time.Now() + e.SpotCount++ + s.scheduleSave() + return e.Callsign, e.Notify, true +} + +// scheduleSave debounces the write: a burst of spots costs one file write two +// seconds after the last of them. Callers hold s.mu. +func (s *Store) scheduleSave() { + s.saveMu.Lock() + defer s.saveMu.Unlock() + if s.saveTimer != nil { + s.saveTimer.Stop() + } + s.saveTimer = time.AfterFunc(2*time.Second, func() { s.persist() }) +} + +func (s *Store) persist() { + list := s.Entries() + data, err := json.MarshalIndent(list, "", " ") + if err != nil { + return + } + s.ioMu.Lock() + defer s.ioMu.Unlock() + _ = os.WriteFile(s.path, data, 0o644) +} + +// Flush writes now — for shutdown, where the two-second debounce would lose +// the last edits. +func (s *Store) Flush() { s.persist() } + +// lastSeenLabel is DXHunter's "Just now / 5m ago / 3h ago / 2d ago" string, +// computed at read time so it never goes stale in the file. +func lastSeenLabel(t time.Time) string { + if t.IsZero() { + return "Never" + } + d := time.Since(t) + switch { + case d < time.Minute: + return "Just now" + case d < time.Hour: + return fmt.Sprintf("%dm ago", int(d.Minutes())) + case d < 24*time.Hour: + return fmt.Sprintf("%dh ago", int(d.Hours())) + default: + return fmt.Sprintf("%dd ago", int(d.Hours()/24)) + } +} diff --git a/internal/watchlist/watchlist_test.go b/internal/watchlist/watchlist_test.go new file mode 100644 index 0000000..46f4c03 --- /dev/null +++ b/internal/watchlist/watchlist_test.go @@ -0,0 +1,78 @@ +package watchlist + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestPrefixMatch(t *testing.T) { + s := New(filepath.Join(t.TempDir(), "watchlist.json")) + if err := s.Add("RI0SP", false); err != nil { + t.Fatal(err) + } + // The reason prefix matching exists: expeditions sign portable. + for _, call := range []string{"RI0SP", "RI0SP/MM", "RI0SP/P"} { + if _, ok := s.Match(call); !ok { + t.Errorf("Match(%q) = false, want true", call) + } + } + if _, ok := s.Match("RI0S"); ok { + t.Error("a SHORTER call must not match the entry") + } + if _, ok := s.Match("F4BPO"); ok { + t.Error("an unrelated call matched") + } +} + +func TestDXHunterFileRoundTrips(t *testing.T) { + // A real DXHunter entry, ClubLog block included. It must survive + // load → save byte-meaningfully: same keys, values preserved. + src := `[{"callsign":"C5SP","lastSeen":"0001-01-01T00:00:00Z","lastSeenStr":"Never", + "addedAt":"2026-01-17T00:18:43.89Z","spotCount":7,"isContest":true,"notify":true, + "isExpedition":true,"clubLogQSOs24h":120,"clubLogTotalQSOs":30500, + "clubLogHasOQRS":true,"clubLogLiveStream":true,"clubLogUpdatedAt":"2026-08-28T22:32:18Z"}]` + dir := t.TempDir() + path := filepath.Join(dir, "watchlist.json") + if err := os.WriteFile(path, []byte(src), 0o644); err != nil { + t.Fatal(err) + } + s := New(path) + s.Flush() + out, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var list []map[string]any + if err := json.Unmarshal(out, &list); err != nil { + t.Fatal(err) + } + if len(list) != 1 { + t.Fatalf("got %d entries", len(list)) + } + e := list[0] + for k, want := range map[string]any{ + "callsign": "C5SP", "isContest": true, "notify": true, + "isExpedition": true, "clubLogQSOs24h": float64(120), + "clubLogTotalQSOs": float64(30500), "clubLogHasOQRS": true, + } { + if e[k] != want { + t.Errorf("%s = %v, want %v", k, e[k], want) + } + } +} + +func TestMarkSeenAndNotify(t *testing.T) { + s := New(filepath.Join(t.TempDir(), "watchlist.json")) + _ = s.Add("HB040A", false) + _ = s.SetNotify("HB040A", true) + entry, notify, ok := s.MarkSeen("HB040A") + if !ok || !notify || entry != "HB040A" { + t.Fatalf("MarkSeen = %q %v %v", entry, notify, ok) + } + list := s.Entries() + if list[0].SpotCount != 1 || list[0].LastSeenStr != "Just now" { + t.Errorf("entry after MarkSeen: %+v", list[0]) + } +}