forked from linkong/planet
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93eb41a9f7 | ||
|
|
dd176a6ae6 | ||
|
|
f14ff6ec0f | ||
|
|
39854b9983 | ||
|
|
3b4347c87d |
No files matched your search
@@ -150,3 +150,9 @@ temp/
|
||||
# Runtime Data
|
||||
# ----------------------
|
||||
data/ai/bgp-briefs/
|
||||
data/earth-boundary-sources/
|
||||
|
||||
# Generated Earth boundary tile artifacts. Keep source configs and builders in
|
||||
# Git; publish PMTiles/MVT artifacts through release/deploy storage instead of
|
||||
# committing thousands of generated tile files.
|
||||
frontend/public/earth/data/boundaries/
|
||||
@@ -244,7 +244,7 @@ bun run build
|
||||
./planet.sh start --allow-lan
|
||||
```
|
||||
|
||||
这会让前端监听 `0.0.0.0:3000`,后端监听 `0.0.0.0:8000`。
|
||||
这会让前端监听 `0.0.0.0:3000`,后端监听 `0.0.0.0:8000`,AI Provider 通过 Docker 发布到 `0.0.0.0:8010`。启动前脚本会检查这三个端口;如果 WSL/Linux 侧无法释放端口,并检测到 Windows 侧 listener 或旧 `portproxy`,会请求管理员 PowerShell 清理。
|
||||
|
||||
### 2. 先确认 WSL 内部服务正常
|
||||
|
||||
@@ -253,14 +253,16 @@ bun run build
|
||||
```bash
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
ss -ltnp | grep -E ':3000|:8000'
|
||||
curl http://localhost:8010/health
|
||||
ss -ltnp | grep -E ':3000|:8000|:8010'
|
||||
```
|
||||
|
||||
预期:
|
||||
|
||||
- `3000` 返回前端 HTML
|
||||
- `8000/health` 返回健康检查 JSON
|
||||
- `ss` 中能看到 `0.0.0.0:3000` 和 `0.0.0.0:8000`
|
||||
- `8010/health` 返回 AI Provider 健康检查 JSON
|
||||
- `ss` 中能看到 `0.0.0.0:3000`、`0.0.0.0:8000` 和 `0.0.0.0:8010`,或 Docker 已发布 `8010`
|
||||
|
||||
如果这一步不通,先不要继续做 Windows 转发。
|
||||
|
||||
@@ -271,42 +273,31 @@ ss -ltnp | grep -E ':3000|:8000'
|
||||
```powershell
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
在常见的 WSL2 开发环境下,Windows 通常可以直接通过 `localhost` 访问 WSL 中的服务。
|
||||
|
||||
### 4. 如果需要让局域网设备访问,再做 Windows 端口转发
|
||||
### 4. 如果需要让局域网设备访问,清理端口和防火墙
|
||||
|
||||
注意:下面的命令必须在“以管理员身份运行”的 PowerShell 中执行。
|
||||
`./planet.sh start --allow-lan` 不再启动额外的 Windows 端口转发进程。它直接让开发服务对 `3000` / `8000` / `8010` 开放,并在启动前尝试释放这些端口。端口被 Windows 侧 listener 或旧 `portproxy` 占用时,脚本会请求一次管理员 PowerShell 清理。
|
||||
|
||||
先把 Windows 对外网卡上的 `3000` / `8000` 转发到 Windows 本机 `127.0.0.1`:
|
||||
如果以前手动配置过持久 `portproxy`,若自动请求被取消,可以手动清理,避免 `iphlpsvc` 继续占用端口:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=3000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8000
|
||||
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=3000 connectaddress=127.0.0.1 connectport=3000
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8000 connectaddress=127.0.0.1 connectport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8010
|
||||
```
|
||||
|
||||
再放行 Windows 防火墙:
|
||||
脚本会检测 Windows 防火墙是否已放行 `3000` / `8000` / `8010`。如果缺少规则,会触发一次 Windows UAC 管理员 PowerShell 请求来自动创建。若自动请求被取消,也可以手动执行:
|
||||
|
||||
```powershell
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 3000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8010" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8010
|
||||
```
|
||||
|
||||
检查转发规则是否生效:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy show all
|
||||
```
|
||||
|
||||
预期能看到:
|
||||
|
||||
- `0.0.0.0:3000 -> 127.0.0.1:3000`
|
||||
- `0.0.0.0:8000 -> 127.0.0.1:8000`
|
||||
|
||||
### 5. 查 Windows 局域网 IP,并让其他设备访问
|
||||
|
||||
在 Windows PowerShell 中执行:
|
||||
@@ -321,6 +312,8 @@ ipconfig
|
||||
|
||||
- `http://<Windows局域网IP>:3000/earth`
|
||||
- `http://<Windows局域网IP>:3000/admin`
|
||||
- `http://<Windows局域网IP>:8000/health`
|
||||
- `http://<Windows局域网IP>:8010/health`
|
||||
|
||||
例如:
|
||||
|
||||
@@ -329,7 +322,7 @@ ipconfig
|
||||
### 6. 常见现象与判断
|
||||
|
||||
- WSL 中 `curl localhost:3000` 能通,但 Windows 访问 `WSL 的局域网 IP:3000` 不通:这是正常现象之一,优先验证 Windows 的 `localhost:3000`
|
||||
- Windows `localhost:3000` 能通,但局域网设备访问 `Windows 局域网 IP:3000` 不通:通常缺少 `portproxy` 或防火墙放行
|
||||
- Windows `localhost:3000` 能通,但局域网设备访问 `Windows 局域网 IP:3000` 不通:通常是 Windows 防火墙、网络配置或旧 `portproxy` 残留
|
||||
- `whoami /groups` 中 `S-1-5-32-544` 显示 `deny only`:说明当前 PowerShell 不是提权管理员窗口
|
||||
|
||||
### 7. 本项目一次性验证顺序
|
||||
@@ -338,10 +331,12 @@ ipconfig
|
||||
|
||||
1. WSL 中执行 `curl http://localhost:3000`
|
||||
2. WSL 中执行 `curl http://localhost:8000/health`
|
||||
3. Windows 中执行 `curl http://localhost:3000`
|
||||
4. Windows 中执行 `curl http://localhost:8000/health`
|
||||
5. 管理员 PowerShell 配置 `portproxy` 和防火墙
|
||||
6. 用手机或其他电脑访问 `http://<Windows局域网IP>:3000/earth`
|
||||
3. WSL 中执行 `curl http://localhost:8010/health`
|
||||
4. Windows 中执行 `curl http://localhost:3000`
|
||||
5. Windows 中执行 `curl http://localhost:8000/health`
|
||||
6. Windows 中执行 `curl http://localhost:8010/health`
|
||||
7. 按脚本提示完成 Windows 防火墙或端口清理 UAC 请求
|
||||
8. 用手机或其他电脑访问 Windows 对外端口,例如 `http://<Windows局域网IP>:3000/earth`
|
||||
|
||||
## 启动容错参数
|
||||
|
||||
|
||||
@@ -1,45 +1,76 @@
|
||||
# TODO
|
||||
|
||||
- [x] 把 BGP 观测站和异常点的 `hover/click` 手感再磨细一点
|
||||
- [x] 开始做 BGP 异常和海缆/区域的关联展示
|
||||
- [x] 做 Earth 侧的 `BGP activity layer`,让低 incident 密度时地图仍然有持续可感知的观测存在感
|
||||
- [x] 给 Earth BGP 补三层状态表达:`平稳观测态 / 局部波动态 / 事件活跃态`
|
||||
- [x] 把“当前无活跃事件”改造成“观测网络仍在运行、当前未发现聚合级事件”的状态表达
|
||||
- [x] 做 collector / region 近 15 分钟 activity score 聚合接口或动态聚合逻辑
|
||||
- [x] 把 Earth 的 BGP incident 改成 `紧凑事件核 + 向外扩张环形 pulse`,替换当前大面积 glow
|
||||
- [x] 为 BGP incident 建立符号系统:按事件类型用不同 marker,而不是都用同一种亮点
|
||||
- [x] 把 incident 地理定位从 `collector-centric` 改成 `prefix-centric`,优先使用 `prefix_geography`,其次 `prefix_scope`,再次 ASN 区域,最后才回退到观测区域质心
|
||||
- [x] 新增 `prefix_geography` 数据层,不再把 `prefix_scope` 当成 prefix 地理归属本身
|
||||
- [x] 接入 `IPtoASN / IPtoCountry` 作为 prefix-centric geography 的主数据源
|
||||
- [x] 接入 `OpenGeoFeed` 作为 prefix geography 的高质量覆盖/override 数据源
|
||||
- [x] 把 RIR delegated 设计成 prefix geography 的 fallback,而不是主来源
|
||||
- [ ] 为 `aiprovider` 建立 `provider -> api adapter -> compat policy` 的配置中心,优先落成 `json` 或 `yaml` 文件,运行时按 `provider/model` 读取兼容设置,而不是把专项兼容继续散落在 Python 分支里
|
||||
- [ ] 为市面上主流 AI 服务补专项兼容配置并固化到配置文件中,至少覆盖 `OpenAI / Anthropic / MiniMax / Ollama / Moonshot / DeepSeek / Qwen / GLM / Gemini / OpenRouter / vLLM / LM Studio / One API`
|
||||
- [ ] 在兼容配置中补齐可声明项:`api adapter`、`base_url pattern`、`auth header`、`thinking default`、`reasoning block mapping`、`stream path`、`tool-call capability`、`multimodal capability`、`provider-specific request patch`
|
||||
- [ ] 接入 `inetnum` / `inet6num` whois 作为比 RIR 更细粒度的后备层
|
||||
- [x] 在 activity layer 之后继续补 `route leak` 和 `path instability / flap` detector
|
||||
- [ ] 对 [frontend/public/earth/js/bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js) 做按职责拆分的小重构,拆成 data / markers / overlays / animation,降低后续维护复杂度
|
||||
- [ ] 可选优化(非必做):将 BGP incident/collector 标点改为 HTML marker(参考 worldmonitor 的 `htmlElementsData` 思路),实现近乎固定屏幕尺寸与更高密度可点击性
|
||||
- [ ] 保持 Earth 当前这批纯个人偏好设置继续走本地持久化:`旋转模式`、HUD 面板显示/隐藏、`地形透明度` 暂不升级到后端系统设置,避免把设备级偏好过早做成全局配置
|
||||
- [ ] 如果后续明确需要“账号级同步 Earth 偏好”,再单独设计 `Earth user preferences`:优先按用户维度而不是全局系统设置保存,并规划 `localStorage -> backend` 的平滑迁移策略
|
||||
- [ ] 为 Planet / Earth 补一个可用的日志查看系统:先明确前后端/AI Provider/采集任务的日志入口、最近日志聚合、筛选与 tail 能力,再决定是先做脚本级统一入口还是控制台内置日志面板
|
||||
- [ ] 重写控制台 UI,逐步抛弃 Ant Design,建立自有组件体系,并统一采用 `tabler.io` / Tabler Icons 作为控制台主图标库
|
||||
- [ ] 把 Earth 态势新闻源从 [earth_news.py](/home/ray/dev/linkong/planet/backend/app/services/earth_news.py) 的硬编码列表抽成可配置目录,优先保持当前“实时聚合”链路不变,只先解决新闻源不可配置的问题
|
||||
- [ ] 为 Earth 态势新闻设计后续采集器化方案:明确新闻数据模型、去重策略、区域映射、过期清理和 Earth/AI 复用方式,再决定何时把新闻从实时抓取升级成正式 collector
|
||||
- [ ] AIS v3.1:修复船只聚合完整性,`/geo/vessels` 合并 raw observation 聚合结果与 legacy `vessel_position + vessel_static` 最新结果,确保 BarentsWatch-only 船只不会因为 AISStream 子集存在而消失,并增加 raw/legacy/final unique MMSI 诊断统计
|
||||
- [ ] AIS v3.2:把 AISStream 从收满 `max_messages` 后结束的批采集改成长连接 streaming service,持续写入 raw observations,通过内部 `/ws` 的 `vessels` channel 推送新船、位置和航向增量,Earth 前端按 MMSI upsert marker
|
||||
- [ ] AIS v3.3:修正 AISStream 采集页面状态语义,使用 connecting/streaming/reconnecting/stopped 与 indeterminate 状态,展示运行时长、消息数、unique MMSI、message rate、最近消息和错误,不再用一次性 REST 进度条表示长连接
|
||||
- [ ] AIS v3.4:修复船只身份字段和名称聚合,MMSI/IMO/callsign 按字符串显示且不带千分位符;查询并列出所有仍以 MMSI 号码或 `MMSI <number>` 作为船名的记录,标注来源、最近观测、message types 和缺失原因,并把这批 fallback-name 船只纳入名称聚合修复集合
|
||||
- [ ] Earth Live Sync:建立统一态势实时同步链路,新增 `earth_summary` WS channel,任意采集器成功后广播轻量 summary invalidation,前端收到后重新拉 `/api/v1/visualization/geo/summary` 并更新 HUD;同时为 BGP 增加 `bgp` WS channel,使 BGP incidents/anomalies/collectors 在不刷新页面时也能 upsert 图层;卫星采集完成后触发 summary 刷新,必要时按 TLE 版本重新 hydrate 卫星数据
|
||||
- [ ] AIS v4:开放船只多源聚合策略配置,支持 source priority、字段级规则、freshness 窗口和高级保护开关;保存时校验未知字段、非法模式和危险动态字段锁定,并在聚合接口返回命中的配置版本
|
||||
- [ ] AIS v5:实现船舶资料 enrichment 与冲突治理,按 `mmsi + imo + name + callsign` 异步补充船型细分、AIS 大类、旗国、尺寸、建造年份、运营方和图片缓存;详情面板展示缓存资料和字段来源,不在实时 AIS 请求链路现场抓第三方页面
|
||||
- [ ] 为 Earth 地球表面增加一层与基础纹理对齐的材质/纹理 overlay,并在同层叠加国界轮廓参考线;要求国界线与底图稳定对齐,且 hover 到国家轮廓时能高亮当前国家,便于校准地表和增强交互
|
||||
- [ ] 把 Earth 新闻接入通用巡航队列:按新闻发生地和时间排序生成巡航目标,巡航聚焦到新闻事件时显示对应新闻卡片,并保持实现边界为“通用巡航层 + 新闻业务适配层”,不要再把新闻逻辑直接耦合回 `main.js` 状态机
|
||||
- [ ] 为未知位置的算力中心建立分层坐标补全链路:优先 `精确坐标 > 站点/园区命中 > 城市 > 州/省 > 国家内主要算力城市 > 国家质心`,并把每次回退的 `confidence / reason / precision` 明确写进统一 GeoJSON
|
||||
- [ ] 为算力中心补一份可维护的本地位置注册表,例如 `canonical_name / aliases / operator / country / region / city / lat / lon / confidence / source_note`,避免把地点知识长期硬编码在 `visualization.py`
|
||||
- [ ] 增强 `epoch_ai_gpu` 和相关算力采集器的源页面解析:即使公开 API 不给坐标,也继续尝试从详情页、HTML、内嵌 JSON、schema.org、OpenGraph、脚本变量和 PDF/新闻稿链接里抽地点线索
|
||||
- [ ] 为未知位置算力中心增加外部富化策略评估:可选接入公开知识源或搜索兜底,只抓“站点名/园区名/城市名”级别线索,不直接抓经纬度结论,并把结果作为候选证据而不是真值
|
||||
- [ ] 为算力中心建立 `operator / cluster name / facility alias` 归一化层,先解决 `xAI / Colossus / Memphis`、`OpenAI / Stargate`、`CoreWeave`、`Lambda`、`Crusoe` 这类同一对象多种写法导致的地点匹配失败
|
||||
- [ ] 为估算位置增加更细的视觉和产品表达:除了问号角标,还要支持 tooltip/详情中的“估算依据”“精度级别”“最后核验时间”,并允许在设置中单独开关“仅看精确位置”
|
||||
- [ ] 为国家级估算点设计更合理的落点策略:优先落在“该国主要算力/数据中心城市候选集”而不是几何质心,必要时同国多节点做稳定散列分配,避免大量节点堆在荒漠或海上
|
||||
- [ ] 为未知位置算力中心建立人工校验工作流:支持导出待核验清单、记录人工确认结果,并把人工确认反哺到位置注册表,逐步减少问号点比例
|
||||
This file is the active backlog only. Completed history belongs in `docs/CHANGELOG.md`; detailed designs belong in `docs/plans/`.
|
||||
|
||||
## Earth
|
||||
|
||||
- [x] High-precision country boundary tile framework: implement the static vector tile builder, versioned seed output, frontend bbox tile loader, debounce, in-flight dedupe, and LRU cache described in [Earth High Precision Boundary Tiles Plan](/home/ray/dev/linkong/planet/docs/plans/earth-high-precision-boundary-tiles-plan.md).
|
||||
- [x] Add the `pmtiles-mvt` frontend tile provider contract, MVT decoder dependencies, static PMTiles Nginx handling, collector artifact registration, production readiness check, and user operation docs for Earth boundaries.
|
||||
- [x] Split Earth boundary ingestion into standard source collectors (`earth_admin0_boundaries`, `earth_coastline`, `earth_claim_lines`) plus the downstream `earth_boundary_tiles` PMTiles builder.
|
||||
- [ ] Replace debug GeoJSON boundary tiles with the real `earth-boundaries-china-pov-v1.pmtiles` production artifact after audited admin-0 / coastline / claim-line sources and the PMTiles toolchain are available.
|
||||
- [ ] Import authoritative China POV / coastline / claim-line source packages through the three standard Earth boundary source collectors, then rebuild a versioned PMTiles artifact so highest zoom `8-10` preserves trusted source geometry instead of seed data.
|
||||
- [ ] Earth boundary data: acquire or generate auditable China POV geometry for Zangnan, Aksai Chin, Taiwan/Penghu, Diaoyu Dao and affiliated islands, Chiwei Yu, South China Sea islands, Kosovo, Gaza, and the official dashed maritime claim line before implementing final visual changes.
|
||||
- [ ] Earth high-resolution basemap tiles: implement the viewport-loaded imagery layer described in [Earth High Resolution Basemap Tiles Plan](/home/ray/dev/linkong/planet/docs/plans/earth-high-resolution-basemap-tiles-plan.md), using high-precision coastline as the alignment reference instead of replacing the globe with one huge texture.
|
||||
- [ ] Presentation controller ownership: replace the singleton card fallback in [presentation-controller.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/presentation-controller.js) with a presentation/card token check before BGP/News migrate onto the shared controller, so connectors only attach to their owning card.
|
||||
- [ ] BGP frontend maintainability: split [bgp.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/bgp.js) by responsibility into data loading, marker rendering, overlays, and animation once the current interaction behavior is stable.
|
||||
- [ ] Optional BGP marker experiment: evaluate HTML markers for BGP incident/collector points if WebGL marker density or fixed screen-size clickability becomes a real blocker.
|
||||
- [ ] Earth news cruise: connect Earth news to the generic cruise queue via a news adapter rather than coupling news-specific sequencing into `main.js`.
|
||||
|
||||
## Compute Centers And Location
|
||||
|
||||
- [ ] Unknown compute-center locations: continue reducing unresolved records through the shared location pipeline, with confidence, precision, reason, and verification date preserved in GeoJSON/details.
|
||||
- [ ] Compute-center registry: keep expanding the local canonical location registry with `canonical_name`, aliases, operator, country/region/city, coordinates, confidence, and source notes.
|
||||
- [ ] Compute-center enrichment: improve source-page parsing for Epoch AI and related collectors by extracting location clues from detail pages, embedded JSON, schema.org, OpenGraph, script variables, PDFs, and press releases.
|
||||
- [ ] Compute-center identity normalization: normalize operator / cluster / facility aliases such as `xAI / Colossus / Memphis`, `OpenAI / Stargate`, `CoreWeave`, `Lambda`, and `Crusoe`.
|
||||
- [ ] Compute-center manual review: add an export/review/import workflow for unresolved or estimated locations and feed confirmed results back into the registry.
|
||||
|
||||
## AIS / Vessels
|
||||
|
||||
- [ ] AIS aggregation strategy v4: expose source priority, field-level merge rules, freshness windows, and protected dynamic-field rules in configuration, with validation and strategy version returned by vessel APIs.
|
||||
- [ ] AIS vessel enrichment v5: add asynchronous vessel profile enrichment for ship type detail, AIS class, flag, dimensions, build year, operator, and cached media. Do not fetch third-party pages in the realtime AIS request path.
|
||||
- [ ] AIS identity cleanup: continue identifying vessels whose display name is only `MMSI <number>` and backfill names from AISStream static messages, BarentsWatch static fields, or enrichment cache.
|
||||
|
||||
## AI Provider And Agents
|
||||
|
||||
- [ ] AI provider compatibility center: move provider/model compatibility rules into a JSON/YAML config read by runtime, instead of continuing to scatter provider-specific branches through Python code.
|
||||
- [ ] Provider compatibility coverage: add explicit config for OpenAI, Anthropic, MiniMax, Ollama, Moonshot, DeepSeek, Qwen, GLM, Gemini, OpenRouter, vLLM, LM Studio, and One API.
|
||||
- [ ] Compatibility schema: cover adapter type, base URL pattern, auth header, thinking/reasoning defaults, stream path, tool-call capability, multimodal capability, and provider-specific request patches.
|
||||
- [ ] BGP geography fallback: evaluate `inetnum` / `inet6num` whois as a finer fallback layer after `prefix_geography`, `OpenGeoFeed`, and RIR delegated data.
|
||||
|
||||
## Platform
|
||||
|
||||
- [ ] Earth preferences scope: keep current device-local Earth preferences in `localStorage`; only design backend user preferences if account-level synchronization becomes a real product requirement.
|
||||
- [ ] System logs: finish a usable Planet log viewing flow that covers backend, frontend, AI Provider, and collector/task logs, with filtering and tailing.
|
||||
- [ ] Console UI modernization: gradually replace Ant Design with Planet-owned components and a consistent Tabler Icons based icon system.
|
||||
- [ ] Earth live sync: design a unified realtime invalidation path for summary/BGP/satellite updates if polling and current WebSocket channels become insufficient.
|
||||
|
||||
## Archive
|
||||
|
||||
Archived items stay here so old context is not lost. Completed items remain checked; obsolete, invalid, or superseded items stay unchecked and include the reason.
|
||||
|
||||
### Completed
|
||||
|
||||
- [x] Refined BGP observer and anomaly `hover/click` feel.
|
||||
- [x] Added BGP anomaly relationship display with cables / regions.
|
||||
- [x] Added the Earth BGP activity layer so the map still feels alive when incident density is low.
|
||||
- [x] Added BGP state expression for stable observation, local fluctuation, and active incident states.
|
||||
- [x] Reframed "no active incident" as "observation network is running; no aggregate incident detected".
|
||||
- [x] Added collector / region recent activity scoring.
|
||||
- [x] Replaced oversized BGP incident glow with compact incident core plus outward pulse rings.
|
||||
- [x] Added BGP incident symbol types instead of using one generic bright marker.
|
||||
- [x] Switched BGP incident geography from collector-centric to prefix-centric priority.
|
||||
- [x] Added `prefix_geography` as a separate data layer instead of treating `prefix_scope` as prefix geography.
|
||||
- [x] Added IPtoASN / IPtoCountry as the main prefix-centric geography source.
|
||||
- [x] Added OpenGeoFeed as a high-quality prefix geography override source.
|
||||
- [x] Made RIR delegated data a prefix geography fallback rather than the primary source.
|
||||
- [x] Added route leak and path instability / flap detectors after the activity layer work.
|
||||
|
||||
### Obsolete Or Superseded
|
||||
|
||||
- [ ] AIS v3.1 old `/geo/vessels` full-merge requirement. Superseded by `/api/v1/vessels/snapshot`, controlled legacy fallback, and diagnostics in the AIS aggregation plan.
|
||||
- [ ] AIS v3.2 old framing of AISStream as a batch collector that needed conversion. Superseded by the implemented long-lived AISStream collector and realtime stream UI.
|
||||
- [ ] AIS v3.3 old one-shot REST progress semantics for AISStream. Superseded by realtime stream status handling.
|
||||
- [ ] AIS v3.4 broad identity cleanup wording. Folded into the active AIS identity cleanup and v5 enrichment tasks.
|
||||
- [ ] Earth surface material overlay for boundary calibration. Superseded by the high-precision boundary tile plan; future work must use source-faithful boundary/coastline data rather than overlay calibration against the coarse base map.
|
||||
- [ ] Hardcoded Earth news source extraction as a standalone task. Superseded by the broader Earth news source configuration and collector plans.
|
||||
- [ ] Country-level compute-center fallback placement as a standalone task. Superseded by the shared location pipeline and registry/manual-review backlog.
|
||||
@@ -152,6 +152,7 @@ class ProviderService:
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"temperature": 0.2,
|
||||
"max_tokens": self.max_tokens,
|
||||
}
|
||||
return await self._post(
|
||||
path="/chat/completions",
|
||||
@@ -229,6 +230,7 @@ class ProviderService:
|
||||
"prompt": prompt,
|
||||
"options": {
|
||||
"temperature": 0.2,
|
||||
"num_predict": self.max_tokens,
|
||||
},
|
||||
}
|
||||
return await self._post(
|
||||
|
||||
@@ -13,6 +13,11 @@ import httpx
|
||||
|
||||
from app.core.target_schema_registry import get_target_schema, list_target_schemas
|
||||
from app.core.datasource_defaults import DEFAULT_DATASOURCES
|
||||
from app.core.earth_boundary_defaults import (
|
||||
EARTH_BOUNDARY_DEFAULT_SOURCES,
|
||||
EARTH_BOUNDARY_SOURCE_MAPPING,
|
||||
default_earth_boundary_config,
|
||||
)
|
||||
from app.db.session import get_db
|
||||
from app.models.user import User
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
@@ -50,6 +55,25 @@ from app.services.datasource_connectivity import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
def _default_builtin_config(name: str) -> dict[str, Any]:
|
||||
if name in {"earth_admin0_boundaries", "earth_coastline", "earth_claim_lines"}:
|
||||
return default_earth_boundary_config(name)
|
||||
if name == "earth_boundary_tiles":
|
||||
return {
|
||||
"timeout": 30,
|
||||
"retry": 0,
|
||||
"input_mode": "latest_collected_earth_boundary_sources",
|
||||
}
|
||||
return {"timeout": 30, "retry": 3}
|
||||
|
||||
|
||||
def _default_builtin_source_type(name: str) -> str:
|
||||
if name == "aisstream_vessels":
|
||||
return "websocket"
|
||||
if name == "earth_boundary_tiles":
|
||||
return "internal"
|
||||
return "http"
|
||||
|
||||
|
||||
class DataSourceConfigCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
@@ -364,7 +388,7 @@ async def list_all_datasources(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""List all data sources: YAML defaults + DB overrides"""
|
||||
from app.core.data_sources import COLLECTOR_URL_KEYS, get_data_sources_config
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
|
||||
config = get_data_sources_config()
|
||||
|
||||
@@ -372,20 +396,22 @@ async def list_all_datasources(
|
||||
db_configs = {c.name: c for c in db_query.scalars().all()}
|
||||
|
||||
result = []
|
||||
for name, yaml_key in COLLECTOR_URL_KEYS.items():
|
||||
for name, metadata in DEFAULT_DATASOURCES.items():
|
||||
yaml_url = config.get_yaml_url(name)
|
||||
db_config = db_configs.get(name)
|
||||
default_config = _default_builtin_config(name)
|
||||
default_url = EARTH_BOUNDARY_DEFAULT_SOURCES.get(name, {}).get("endpoint") or yaml_url
|
||||
|
||||
result.append(
|
||||
{
|
||||
"name": name,
|
||||
"default_url": yaml_url,
|
||||
"endpoint": db_config.endpoint if db_config else yaml_url,
|
||||
"default_url": default_url,
|
||||
"endpoint": db_config.endpoint if db_config else default_url,
|
||||
"is_overridden": db_config is not None and db_config.endpoint != yaml_url
|
||||
if yaml_url
|
||||
if default_url
|
||||
else db_config is not None,
|
||||
"is_active": db_config.is_active if db_config else True,
|
||||
"source_type": db_config.source_type if db_config else "http",
|
||||
"source_type": db_config.source_type if db_config else _default_builtin_source_type(name),
|
||||
"auth_type": db_config.auth_type if db_config else "none",
|
||||
"auth_configured": {
|
||||
"api_key": bool((db_config.auth_config or {}).get("api_key"))
|
||||
@@ -393,11 +419,11 @@ async def list_all_datasources(
|
||||
else False,
|
||||
},
|
||||
"headers": db_config.headers if db_config else {},
|
||||
"config": strip_connectivity_validation(db_config.config if db_config else {}),
|
||||
"config": strip_connectivity_validation(db_config.config if db_config else default_config),
|
||||
"config_id": db_config.id if db_config else None,
|
||||
"description": db_config.description
|
||||
if db_config
|
||||
else f"Data source from YAML: {yaml_key}",
|
||||
else f"内置采集器默认配置:{metadata.get('display_name') or metadata.get('name') or name}",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
|
||||
("cables", ("cable", "landing", "telegeography", "arcgis", "fao")),
|
||||
("satellites", ("tle", "satellite", "spacetrack", "celestrak")),
|
||||
("bgp", ("bgp", "asn", "prefix_geo", "opengeofeed", "nro")),
|
||||
("earth", ("earth_", "earth_boundary", "boundary", "country boundary", "coastline", "claim")),
|
||||
("compute", ("top500", "gpu", "supercomputer", "compute")),
|
||||
("ai", ("huggingface", "epoch_ai")),
|
||||
("media", ("news", "tv", "live_stream")),
|
||||
@@ -150,6 +151,33 @@ async def _load_latest_task_ids(
|
||||
return {datasource_id: task_id for datasource_id, task_id in result.all()}
|
||||
|
||||
|
||||
async def _load_latest_tasks(
|
||||
db: AsyncSession,
|
||||
datasource_ids: list[int],
|
||||
) -> dict[int, CollectionTask]:
|
||||
if not datasource_ids:
|
||||
return {}
|
||||
|
||||
ranked_tasks = (
|
||||
select(
|
||||
CollectionTask.id.label("task_id"),
|
||||
CollectionTask.datasource_id.label("datasource_id"),
|
||||
func.row_number().over(
|
||||
partition_by=CollectionTask.datasource_id,
|
||||
order_by=(CollectionTask.created_at.desc().nullslast(), CollectionTask.id.desc()),
|
||||
).label("row_num"),
|
||||
)
|
||||
.where(CollectionTask.datasource_id.in_(datasource_ids))
|
||||
.subquery()
|
||||
)
|
||||
result = await db.execute(
|
||||
select(CollectionTask)
|
||||
.join(ranked_tasks, CollectionTask.id == ranked_tasks.c.task_id)
|
||||
.where(ranked_tasks.c.row_num == 1)
|
||||
)
|
||||
return {task.datasource_id: task for task in result.scalars().all()}
|
||||
|
||||
|
||||
async def _load_collected_record_counts(
|
||||
db: AsyncSession,
|
||||
sources: list[str],
|
||||
@@ -208,7 +236,7 @@ async def _load_datasource_endpoint_overrides(
|
||||
async def _load_datasource_list_context(
|
||||
db: AsyncSession,
|
||||
datasources: list[DataSource],
|
||||
) -> tuple[dict[int, CollectionTask], dict[str, str]]:
|
||||
) -> tuple[dict[int, CollectionTask], dict[int, CollectionTask], dict[str, str]]:
|
||||
datasource_ids = [datasource.id for datasource in datasources]
|
||||
sources = [datasource.source for datasource in datasources]
|
||||
|
||||
@@ -232,8 +260,9 @@ async def _load_datasource_list_context(
|
||||
if stale_datasource_ids:
|
||||
running_tasks = await _load_latest_running_tasks(db, datasource_ids)
|
||||
|
||||
latest_tasks = await _load_latest_tasks(db, datasource_ids)
|
||||
endpoint_overrides = await _load_datasource_endpoint_overrides(db, sources)
|
||||
return running_tasks, endpoint_overrides
|
||||
return running_tasks, latest_tasks, endpoint_overrides
|
||||
|
||||
|
||||
def _apply_datasource_query_filters(
|
||||
@@ -251,11 +280,6 @@ def _apply_datasource_query_filters(
|
||||
query = query.where(DataSource.is_active == is_active)
|
||||
if priority:
|
||||
query = query.where(DataSource.priority == priority)
|
||||
if run_status and run_status not in {"running", "collected", "uncollected"}:
|
||||
if run_status == "not_run":
|
||||
query = query.where(DataSource.last_status.is_(None))
|
||||
else:
|
||||
query = query.where(DataSource.last_status == run_status)
|
||||
if q:
|
||||
like_value = f"%{q.strip()}%"
|
||||
query = query.where(
|
||||
@@ -272,6 +296,7 @@ def _filter_datasources_in_memory(
|
||||
datasources: list[DataSource],
|
||||
*,
|
||||
running_tasks: dict[int, CollectionTask],
|
||||
latest_tasks: dict[int, CollectionTask],
|
||||
record_counts: dict[str, int],
|
||||
product: Optional[str] = None,
|
||||
run_status: Optional[str] = None,
|
||||
@@ -281,6 +306,14 @@ def _filter_datasources_in_memory(
|
||||
filtered: list[DataSource] = []
|
||||
for datasource in datasources:
|
||||
record_count = record_counts.get(datasource.source, 0)
|
||||
latest_task = latest_tasks.get(datasource.id)
|
||||
effective_status = (
|
||||
"running"
|
||||
if datasource.id in running_tasks
|
||||
else latest_task.status
|
||||
if latest_task is not None
|
||||
else datasource.last_status
|
||||
)
|
||||
if product and datasource_product_key(datasource) != product:
|
||||
continue
|
||||
if collected is not None and (record_count > 0) != collected:
|
||||
@@ -291,6 +324,10 @@ def _filter_datasources_in_memory(
|
||||
continue
|
||||
if run_status == "running" and datasource.id not in running_tasks:
|
||||
continue
|
||||
if run_status == "not_run" and effective_status is not None:
|
||||
continue
|
||||
if run_status not in {None, "running", "not_run", "collected", "uncollected"} and effective_status != run_status:
|
||||
continue
|
||||
if run_status == "collected" and record_count <= 0:
|
||||
continue
|
||||
if run_status == "uncollected" and record_count > 0:
|
||||
@@ -639,11 +676,12 @@ async def list_datasources(
|
||||
|
||||
collector_list = []
|
||||
config = get_data_sources_config()
|
||||
running_tasks, endpoint_overrides = await _load_datasource_list_context(db, datasources)
|
||||
running_tasks, latest_tasks, endpoint_overrides = await _load_datasource_list_context(db, datasources)
|
||||
record_counts = await _load_collected_record_counts(db, [datasource.source for datasource in datasources])
|
||||
datasources = _filter_datasources_in_memory(
|
||||
datasources,
|
||||
running_tasks=running_tasks,
|
||||
latest_tasks=latest_tasks,
|
||||
record_counts=record_counts,
|
||||
product=product,
|
||||
run_status=run_status,
|
||||
@@ -652,9 +690,11 @@ async def list_datasources(
|
||||
)
|
||||
for datasource in datasources:
|
||||
running_task = running_tasks.get(datasource.id)
|
||||
latest_task = latest_tasks.get(datasource.id)
|
||||
display_task = running_task or latest_task
|
||||
endpoint = endpoint_overrides.get(datasource.source) or config.get_yaml_url(datasource.source)
|
||||
last_run_at = datasource.last_run_at
|
||||
last_status = datasource.last_status
|
||||
last_run_at = datasource.last_run_at or (latest_task.completed_at if latest_task else None)
|
||||
last_status = datasource.last_status or (latest_task.status if latest_task else None)
|
||||
collected_records = record_counts.get(datasource.source, 0)
|
||||
|
||||
collector_list.append(
|
||||
@@ -675,16 +715,17 @@ async def list_datasources(
|
||||
"last_run_at": to_iso8601_utc(last_run_at),
|
||||
"last_status": last_status,
|
||||
"is_running": running_task is not None,
|
||||
"task_id": running_task.id if running_task else None,
|
||||
"progress": running_task.progress if running_task else None,
|
||||
"phase": running_task.phase if running_task else None,
|
||||
"phase_progress": running_task.phase_progress if running_task else None,
|
||||
"phase_message": running_task.phase_message if running_task else None,
|
||||
"phase_current": running_task.phase_current if running_task else None,
|
||||
"phase_total": running_task.phase_total if running_task else None,
|
||||
"phase_unit": running_task.phase_unit if running_task else None,
|
||||
"records_processed": running_task.records_processed if running_task else None,
|
||||
"total_records": running_task.total_records if running_task else None,
|
||||
"task_id": display_task.id if display_task else None,
|
||||
"progress": display_task.progress if display_task else None,
|
||||
"phase": display_task.phase if display_task else None,
|
||||
"phase_progress": display_task.phase_progress if display_task else None,
|
||||
"phase_message": display_task.phase_message if display_task else None,
|
||||
"phase_current": display_task.phase_current if display_task else None,
|
||||
"phase_total": display_task.phase_total if display_task else None,
|
||||
"phase_unit": display_task.phase_unit if display_task else None,
|
||||
"records_processed": display_task.records_processed if display_task else None,
|
||||
"total_records": display_task.total_records if display_task else None,
|
||||
"error_message": display_task.error_message if display_task else None,
|
||||
"collected_records": collected_records,
|
||||
"has_collected_data": collected_records > 0,
|
||||
}
|
||||
@@ -729,11 +770,12 @@ async def trigger_datasource_batch(
|
||||
|
||||
result = await db.execute(query)
|
||||
datasources = result.scalars().all()
|
||||
running_tasks, _ = await _load_datasource_list_context(db, datasources)
|
||||
running_tasks, latest_tasks, _ = await _load_datasource_list_context(db, datasources)
|
||||
record_counts = await _load_collected_record_counts(db, [datasource.source for datasource in datasources])
|
||||
datasources = _filter_datasources_in_memory(
|
||||
datasources,
|
||||
running_tasks=running_tasks,
|
||||
latest_tasks=latest_tasks,
|
||||
record_counts=record_counts,
|
||||
product=None if payload.source_ids else payload.product,
|
||||
run_status=None if payload.source_ids else payload.run_status,
|
||||
@@ -935,6 +977,14 @@ async def get_task_status(
|
||||
raise HTTPException(status_code=404, detail="Task not found")
|
||||
else:
|
||||
task = await get_running_task(db, datasource.id)
|
||||
if task is None:
|
||||
result = await db.execute(
|
||||
select(CollectionTask)
|
||||
.where(CollectionTask.datasource_id == datasource.id)
|
||||
.order_by(CollectionTask.created_at.desc().nullslast(), CollectionTask.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
task = result.scalar_one_or_none()
|
||||
|
||||
if not task:
|
||||
return {
|
||||
@@ -963,4 +1013,5 @@ async def get_task_status(
|
||||
"records_processed": task.records_processed,
|
||||
"total_records": task.total_records,
|
||||
"status": task.status,
|
||||
"error_message": task.error_message,
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db.session import get_db
|
||||
from app.services.earth_news import get_earth_news_payload
|
||||
|
||||
router = APIRouter()
|
||||
@@ -9,5 +11,6 @@ router = APIRouter()
|
||||
async def get_earth_feed(
|
||||
lat: float | None = Query(None, description="Current Earth view center latitude"),
|
||||
lon: float | None = Query(None, description="Current Earth view center longitude"),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
return await get_earth_news_payload(lat=lat, lon=lon)
|
||||
return await get_earth_news_payload(lat=lat, lon=lon, db=db)
|
||||
@@ -59,6 +59,7 @@ from app.services.scheduler import sync_datasource_job
|
||||
from app.services.tv_streams import DEFAULT_TV_SETTINGS, get_tv_settings_payload, normalize_tv_settings
|
||||
|
||||
router = APIRouter()
|
||||
AI_PROVIDER_QUICK_CONNECT_TIMEOUT_SECONDS = 5
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
"system": {
|
||||
@@ -484,7 +485,9 @@ def _is_secret_placeholder(value: Optional[str], current_preview: str = "") -> b
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return True
|
||||
return text == current_preview or text.startswith("••••") or "*" in text
|
||||
if text == current_preview or text.startswith("••••"):
|
||||
return True
|
||||
return all(char in {"*", "•", " ", "\t"} for char in text)
|
||||
|
||||
|
||||
def _build_ai_provider_payload(current_payload: dict, update: AIProviderIntegrationUpdate) -> dict:
|
||||
@@ -561,6 +564,54 @@ def _runtime_config_from_ai_payload(ai_payload: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _ai_provider_runtime_fingerprint(ai_payload: dict) -> dict:
|
||||
runtime_config = _runtime_config_from_ai_payload(ai_payload)
|
||||
llm_config = runtime_config.get("llm_config") or {}
|
||||
return {
|
||||
"service_url": runtime_config.get("service_url") or "",
|
||||
"service_token": runtime_config.get("service_token") or "",
|
||||
"timeout_seconds": int(runtime_config.get("timeout_seconds") or 0),
|
||||
"retry_attempts": int(runtime_config.get("retry_attempts") or 0),
|
||||
"provider": llm_config.get("provider") or "",
|
||||
"provider_api": llm_config.get("provider_api") or "",
|
||||
"base_url": llm_config.get("base_url") or "",
|
||||
"model": llm_config.get("model") or "",
|
||||
"api_key": llm_config.get("api_key") or "",
|
||||
"max_tokens": int(llm_config.get("max_tokens") or 0),
|
||||
"anthropic_version": llm_config.get("anthropic_version") or "",
|
||||
}
|
||||
|
||||
|
||||
async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict:
|
||||
runtime_config = _runtime_config_from_ai_payload(ai_payload)
|
||||
client = AIProviderClient(
|
||||
service_url=runtime_config["service_url"],
|
||||
service_token=runtime_config["service_token"],
|
||||
timeout=runtime_config["timeout_seconds"],
|
||||
retry_attempts=runtime_config["retry_attempts"],
|
||||
llm_config=runtime_config.get("llm_config") or {},
|
||||
)
|
||||
status_result = await client.get_status()
|
||||
if not status_result.configured:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="AI Provider 可访问,但当前 provider/model/key 未完整配置。",
|
||||
)
|
||||
analysis_result = await client.analyze(
|
||||
SituationalAnalysisRequest(
|
||||
title="保存前完整连接测试",
|
||||
objective="请用一句话回复连接可用。",
|
||||
observations=["这是保存 AI Provider 配置前的完整 LLM 调用测试。"],
|
||||
constraints=["回复尽量简短。"],
|
||||
)
|
||||
)
|
||||
return {
|
||||
"status": status_result.model_dump(),
|
||||
"provider": analysis_result.provider,
|
||||
"model": analysis_result.model,
|
||||
}
|
||||
|
||||
|
||||
def _web_search_provider_defaults(provider: str) -> dict:
|
||||
return web_search_provider_defaults(provider).model_dump()
|
||||
|
||||
@@ -910,7 +961,10 @@ async def save_external_integrations_payload(
|
||||
update: ExternalIntegrationsUpdate,
|
||||
) -> dict:
|
||||
current_payload = await get_setting_payload(db, "external_integrations")
|
||||
current_ai_payload = _normalize_ai_provider_payload(current_payload.get("ai_provider") or {})
|
||||
ai_payload = _build_ai_provider_payload(current_payload, update.ai_provider)
|
||||
if _ai_provider_runtime_fingerprint(ai_payload) != _ai_provider_runtime_fingerprint(current_ai_payload):
|
||||
await _validate_ai_provider_full_connection(ai_payload)
|
||||
web_search_payload = _build_web_search_payload(current_payload, update.web_search)
|
||||
ocr_payload = _build_ocr_payload(current_payload, update.ocr)
|
||||
|
||||
@@ -1219,12 +1273,16 @@ async def connect_ai_provider_integration(
|
||||
current_payload = await get_setting_payload(db, "external_integrations")
|
||||
draft_ai_payload = _build_ai_provider_payload(current_payload, payload)
|
||||
runtime_config = _runtime_config_from_ai_payload(draft_ai_payload)
|
||||
quick_llm_config = {
|
||||
**(runtime_config.get("llm_config") or {}),
|
||||
"max_tokens": 1,
|
||||
}
|
||||
client = AIProviderClient(
|
||||
service_url=runtime_config["service_url"],
|
||||
service_token=runtime_config["service_token"],
|
||||
timeout=runtime_config["timeout_seconds"],
|
||||
retry_attempts=runtime_config["retry_attempts"],
|
||||
llm_config=runtime_config.get("llm_config") or {},
|
||||
timeout=min(int(runtime_config["timeout_seconds"] or 60), AI_PROVIDER_QUICK_CONNECT_TIMEOUT_SECONDS),
|
||||
retry_attempts=1,
|
||||
llm_config=quick_llm_config,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -1236,29 +1294,22 @@ async def connect_ai_provider_integration(
|
||||
"message": "AI Provider 可访问,但当前 provider/model/key 未完整配置。",
|
||||
"status": status_result.model_dump(),
|
||||
}
|
||||
analysis_result = await client.analyze(
|
||||
probe_result = await client.analyze(
|
||||
SituationalAnalysisRequest(
|
||||
title="连接测试",
|
||||
objective="请用一句话回复连接可用。",
|
||||
observations=["这是配置中心发起的 LLM 连接测试。"],
|
||||
constraints=["回复尽量简短。"],
|
||||
title="快速连接测试",
|
||||
objective="Reply OK.",
|
||||
observations=[],
|
||||
constraints=["Output only OK."],
|
||||
)
|
||||
)
|
||||
current_web_search = _normalize_web_search_payload(current_payload.get("web_search") or {})
|
||||
current_ocr = _normalize_ocr_payload(current_payload.get("ocr") or {})
|
||||
await save_setting_payload(
|
||||
db,
|
||||
"external_integrations",
|
||||
{"ai_provider": draft_ai_payload, "web_search": current_web_search, "ocr": current_ocr},
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"connected": True,
|
||||
"message": "AI Provider 连接成功,已保存为全局默认配置。",
|
||||
"message": "连接测试通过",
|
||||
"status": status_result.model_dump(),
|
||||
"provider": analysis_result.provider,
|
||||
"model": analysis_result.model,
|
||||
"integrations": await serialize_external_integrations(db),
|
||||
"provider": probe_result.provider,
|
||||
"model": probe_result.model,
|
||||
"mode": "quick_probe",
|
||||
}
|
||||
except HTTPException as exc:
|
||||
return {
|
||||
|
||||
@@ -58,7 +58,7 @@ async def websocket_endpoint(
|
||||
|
||||
is_anonymous = payload is None
|
||||
user_id = str(payload.get("sub")) if payload else f"anonymous:{id(websocket)}"
|
||||
supported_channels = ["vessels"] if is_anonymous else [
|
||||
supported_channels = ["vessels", "earth_news"] if is_anonymous else [
|
||||
"gpu_clusters",
|
||||
"submarine_cables",
|
||||
"ixp_nodes",
|
||||
@@ -66,6 +66,7 @@ async def websocket_endpoint(
|
||||
"dashboard",
|
||||
"datasource_tasks",
|
||||
"vessels",
|
||||
"earth_news",
|
||||
]
|
||||
await manager.connect(websocket, user_id)
|
||||
|
||||
|
||||
@@ -257,6 +257,56 @@ DEFAULT_DATASOURCES = {
|
||||
"credential_provider": "aisstream",
|
||||
"credential_status": "supported",
|
||||
},
|
||||
"earth_admin0_boundaries": {
|
||||
"id": 29,
|
||||
"name": "Earth Admin-0 Boundaries",
|
||||
"display_name": "Earth Admin-0 国界源",
|
||||
"module": "L3",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 10080,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"earth_coastline": {
|
||||
"id": 30,
|
||||
"name": "Earth Coastline",
|
||||
"display_name": "Earth 海岸线源",
|
||||
"module": "L3",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 10080,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"earth_claim_lines": {
|
||||
"id": 31,
|
||||
"name": "Earth Claim Lines",
|
||||
"display_name": "Earth 主张线源",
|
||||
"module": "L3",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 10080,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"earth_boundary_tiles": {
|
||||
"id": 32,
|
||||
"name": "Earth PMTiles Builder",
|
||||
"display_name": "Earth PMTiles 构建器",
|
||||
"module": "L3",
|
||||
"priority": "P1",
|
||||
"frequency_minutes": 10080,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
"media_news_archive": {
|
||||
"id": 33,
|
||||
"name": "Media News Archive",
|
||||
"display_name": "媒体新闻归档",
|
||||
"module": "L4",
|
||||
"priority": "P2",
|
||||
"frequency_minutes": 720,
|
||||
"is_free": True,
|
||||
"requires_credentials": False,
|
||||
},
|
||||
}
|
||||
|
||||
ID_TO_COLLECTOR = {info["id"]: name for name, info in DEFAULT_DATASOURCES.items()}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Default Earth boundary source configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
EARTH_BOUNDARY_SOURCE_MAPPING: dict[str, Any] = {
|
||||
"source": {"items_path": "$.features[*]"},
|
||||
"fields": {
|
||||
"source_id": {"path": "$.properties.id", "type": "string"},
|
||||
"name": {"path": "$.properties.name", "type": "string"},
|
||||
"geometry": {"path": "$.geometry", "type": "object"},
|
||||
"properties": {"path": "$.properties", "type": "object"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
EARTH_BOUNDARY_DEFAULT_SOURCES: dict[str, dict[str, Any]] = {
|
||||
"earth_admin0_boundaries": {
|
||||
"endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_countries.geojson",
|
||||
"source_kind": "admin0-boundaries",
|
||||
"license": "Natural Earth public domain",
|
||||
},
|
||||
"earth_coastline": {
|
||||
"endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_coastline.geojson",
|
||||
"source_kind": "coastline",
|
||||
"license": "Natural Earth public domain",
|
||||
},
|
||||
"earth_claim_lines": {
|
||||
"endpoint": "https://www.arcgis.com/sharing/rest/content/items/faaa1908c3ab43f0823c6fde9f18389c/data",
|
||||
"source_kind": "claim-lines",
|
||||
"license": "CC BY 4.0; source item owner mapmakersami",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def default_earth_boundary_config(name: str) -> dict[str, Any]:
|
||||
source = EARTH_BOUNDARY_DEFAULT_SOURCES.get(name)
|
||||
if not source:
|
||||
return {}
|
||||
return {
|
||||
"method": "GET",
|
||||
"timeout": 120,
|
||||
"retry": 3,
|
||||
"target_schema": "earth_boundary_source",
|
||||
"license": source["license"],
|
||||
"mapping_json": EARTH_BOUNDARY_SOURCE_MAPPING,
|
||||
}
|
||||
@@ -47,6 +47,18 @@ class GenericRecord(BaseModel):
|
||||
return value
|
||||
|
||||
|
||||
class EarthBoundarySourceRecord(BaseModel):
|
||||
source_id: str | None = None
|
||||
source_kind: str = Field(pattern="^(admin0-boundaries|coastline|claim-lines)$")
|
||||
name: str | None = None
|
||||
geometry: dict[str, Any] | None = None
|
||||
properties: dict[str, Any] = Field(default_factory=dict)
|
||||
artifact_path: str | None = None
|
||||
sha256: str | None = None
|
||||
feature_count: int | None = Field(default=None, ge=0)
|
||||
license: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TargetField:
|
||||
name: str
|
||||
@@ -143,6 +155,24 @@ TARGET_SCHEMAS: dict[str, TargetSchema] = {
|
||||
TargetField("observed_at", "datetime", False, "观测时间", "2026-04-28T00:00:00Z"),
|
||||
),
|
||||
),
|
||||
"earth_boundary_source": TargetSchema(
|
||||
key="earth_boundary_source",
|
||||
label="Earth 边界矢量源",
|
||||
description="Admin-0 国界、海岸线、主张线等 Earth 边界源数据 artifact。",
|
||||
destination="collected_data",
|
||||
model=EarthBoundarySourceRecord,
|
||||
fields=(
|
||||
TargetField("source_id", "string", False, "来源侧 ID", "feature-1"),
|
||||
TargetField("source_kind", "string", True, "边界源类型", "admin0-boundaries"),
|
||||
TargetField("name", "string", False, "记录名称", "China"),
|
||||
TargetField("geometry", "object", False, "GeoJSON geometry", {"type": "Polygon", "coordinates": []}),
|
||||
TargetField("properties", "object", False, "GeoJSON properties", {"ISO_A3": "CHN"}),
|
||||
TargetField("artifact_path", "string", False, "完整源数据本地 artifact 路径", "data/earth-boundary-sources/earth_admin0_boundaries/abc.geojson"),
|
||||
TargetField("sha256", "string", False, "源数据 artifact SHA-256", "abc123"),
|
||||
TargetField("feature_count", "integer", False, "源数据 feature 数", 1),
|
||||
TargetField("license", "string", False, "源数据许可", "ODbL"),
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -134,6 +134,7 @@ async def init_db():
|
||||
import app.models.vessel # noqa: F401
|
||||
import app.models.vessel_enrichment # noqa: F401
|
||||
import app.models.datasource_mapping # noqa: F401
|
||||
import app.models.earth_news # noqa: F401
|
||||
|
||||
logger.warning_event(
|
||||
"Database pool settings active",
|
||||
|
||||
@@ -18,6 +18,10 @@ from app.services.scheduler import (
|
||||
stop_scheduler,
|
||||
sync_scheduler_with_datasources,
|
||||
)
|
||||
from app.services.earth_news_worker import (
|
||||
start_earth_news_target_worker,
|
||||
stop_earth_news_target_worker,
|
||||
)
|
||||
|
||||
|
||||
configure_logging()
|
||||
@@ -53,7 +57,9 @@ async def lifespan(app: FastAPI):
|
||||
start_scheduler()
|
||||
await sync_scheduler_with_datasources()
|
||||
broadcaster.start()
|
||||
start_earth_news_target_worker()
|
||||
yield
|
||||
await stop_earth_news_target_worker()
|
||||
broadcaster.stop()
|
||||
stop_scheduler()
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.models.playground_message import PlaygroundMessage
|
||||
from app.models.system_log import SystemLog, AuditLog
|
||||
from app.models.vessel import AISConflictRecord, AISRawObservation, AISSourceHealth, VesselPosition, VesselStatic
|
||||
from app.models.datasource_mapping import DataSourceMappingTemplate
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
|
||||
__all__ = [
|
||||
"User",
|
||||
@@ -43,4 +44,5 @@ __all__ = [
|
||||
"AISConflictRecord",
|
||||
"AISSourceHealth",
|
||||
"DataSourceMappingTemplate",
|
||||
"EarthNewsItem",
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from sqlalchemy import Boolean, Column, DateTime, Float, Index, JSON, String, Text
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class EarthNewsItem(Base):
|
||||
__tablename__ = "earth_news_items"
|
||||
|
||||
id = Column(String(160), primary_key=True)
|
||||
title = Column(String(500), nullable=False)
|
||||
summary = Column(Text, nullable=False, default="")
|
||||
url = Column(Text, nullable=False)
|
||||
source = Column(String(255), nullable=False, default="")
|
||||
feed_name = Column(String(255), nullable=False, default="")
|
||||
region = Column(String(80), nullable=False, index=True)
|
||||
homepage_url = Column(Text, nullable=False, default="")
|
||||
published_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
|
||||
latitude = Column(Float, nullable=False)
|
||||
longitude = Column(Float, nullable=False)
|
||||
location_label = Column(String(255), nullable=False)
|
||||
location_source = Column(String(80), nullable=False, default="region_anchor")
|
||||
verified = Column(Boolean, nullable=False, default=False, index=True)
|
||||
location_meta = Column(JSON, nullable=False, default=dict)
|
||||
|
||||
first_seen_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
last_seen_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
|
||||
resolved_at = Column(DateTime(timezone=True), nullable=True, index=True)
|
||||
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_earth_news_region_published", "region", "published_at"),
|
||||
Index("idx_earth_news_region_seen", "region", "last_seen_at"),
|
||||
)
|
||||
@@ -36,8 +36,15 @@ from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
|
||||
from app.services.collectors.opengeofeed import OpenGeoFeedPrefixGeoCollector
|
||||
from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector
|
||||
from app.services.collectors.news_live_streams import NewsLiveStreamsCollector
|
||||
from app.services.collectors.media_news_archive import MediaNewsArchiveCollector
|
||||
from app.services.collectors.aisstream import AISStreamCollector
|
||||
from app.services.collectors.vessel_ais import VesselAISCollector
|
||||
from app.services.collectors.earth_boundaries import (
|
||||
EarthAdmin0BoundaryCollector,
|
||||
EarthBoundaryTileCollector,
|
||||
EarthClaimLinesCollector,
|
||||
EarthCoastlineCollector,
|
||||
)
|
||||
|
||||
collector_registry.register(TOP500Collector())
|
||||
collector_registry.register(EpochAIGPUCollector())
|
||||
@@ -65,8 +72,13 @@ collector_registry.register(IPtoASNPrefixGeoCollector())
|
||||
collector_registry.register(OpenGeoFeedPrefixGeoCollector())
|
||||
collector_registry.register(NRODelegatedPrefixGeoCollector())
|
||||
collector_registry.register(NewsLiveStreamsCollector())
|
||||
collector_registry.register(MediaNewsArchiveCollector())
|
||||
collector_registry.register(VesselAISCollector())
|
||||
collector_registry.register(AISStreamCollector())
|
||||
collector_registry.register(EarthAdmin0BoundaryCollector())
|
||||
collector_registry.register(EarthCoastlineCollector())
|
||||
collector_registry.register(EarthClaimLinesCollector())
|
||||
collector_registry.register(EarthBoundaryTileCollector())
|
||||
|
||||
__all__ = [
|
||||
"BaseCollector",
|
||||
@@ -100,6 +112,11 @@ __all__ = [
|
||||
"OpenGeoFeedPrefixGeoCollector",
|
||||
"NRODelegatedPrefixGeoCollector",
|
||||
"NewsLiveStreamsCollector",
|
||||
"MediaNewsArchiveCollector",
|
||||
"VesselAISCollector",
|
||||
"AISStreamCollector",
|
||||
"EarthAdmin0BoundaryCollector",
|
||||
"EarthCoastlineCollector",
|
||||
"EarthClaimLinesCollector",
|
||||
"EarthBoundaryTileCollector",
|
||||
]
|
||||
@@ -0,0 +1,578 @@
|
||||
"""Earth boundary source and static tile collector."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.earth_boundary_defaults import EARTH_BOUNDARY_DEFAULT_SOURCES, default_earth_boundary_config
|
||||
from app.models.collected_data import CollectedData
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.custom_datasource_runtime import build_query_params, build_request_headers
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[4]
|
||||
SOURCE_OUTPUT_DIR = REPO_ROOT / "data/earth-boundary-sources"
|
||||
SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json"
|
||||
BOUNDARY_OUTPUT_DIR = REPO_ROOT / "frontend/public/earth/data/boundaries/v1"
|
||||
BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json"
|
||||
PMTILES_ARTIFACT_PATH = REPO_ROOT / "frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"
|
||||
POV_POLICY_PATH = REPO_ROOT / "config/earth-boundary-pov-policy.china-v1.json"
|
||||
BUILD_CONFIG = {
|
||||
"builder": "scripts/build_earth_boundary_china_pov_geojson.py",
|
||||
"format": "geojson-high-precision",
|
||||
"production_target": "geojson-high-precision",
|
||||
}
|
||||
|
||||
EARTH_BOUNDARY_SOURCE_COLLECTORS = {
|
||||
"earth_admin0_boundaries": "admin0-boundaries",
|
||||
"earth_coastline": "coastline",
|
||||
"earth_claim_lines": "claim-lines",
|
||||
}
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
if not path.exists():
|
||||
return {}
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _directory_stats(path: Path) -> dict[str, int]:
|
||||
if not path.exists():
|
||||
return {"file_count": 0, "size_bytes": 0}
|
||||
files = [item for item in path.rglob("*") if item.is_file()]
|
||||
return {
|
||||
"file_count": len(files),
|
||||
"size_bytes": sum(item.stat().st_size for item in files),
|
||||
}
|
||||
|
||||
|
||||
def _stable_json_hash(payload: Any) -> str:
|
||||
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _build_input_hash(source_manifest: dict[str, Any]) -> str:
|
||||
return _stable_json_hash(
|
||||
{
|
||||
"source_manifest_schema": source_manifest.get("schema"),
|
||||
"sources": [
|
||||
{
|
||||
"id": source.get("id"),
|
||||
"sha256": source.get("sha256"),
|
||||
"kind": source.get("kind"),
|
||||
"pov": source.get("pov"),
|
||||
}
|
||||
for source in source_manifest.get("sources", [])
|
||||
],
|
||||
"pov_policy": source_manifest.get("povPolicy"),
|
||||
"build_config": BUILD_CONFIG,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool:
|
||||
if not boundary_manifest:
|
||||
return False
|
||||
if boundary_manifest.get("buildInputHash") != build_input_hash:
|
||||
return False
|
||||
if not BOUNDARY_OUTPUT_DIR.exists():
|
||||
return False
|
||||
if boundary_manifest.get("tileProvider") == "pmtiles-mvt":
|
||||
return PMTILES_ARTIFACT_PATH.exists()
|
||||
return (BOUNDARY_OUTPUT_DIR / "base.geojson").exists() and (
|
||||
BOUNDARY_OUTPUT_DIR / "hover-index.geojson"
|
||||
).exists()
|
||||
|
||||
|
||||
def _sha256_bytes(payload: bytes) -> str:
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def _json_feature_count(payload: Any) -> int:
|
||||
if isinstance(payload, dict) and isinstance(payload.get("features"), list):
|
||||
return len(payload["features"])
|
||||
if isinstance(payload, list):
|
||||
return len(payload)
|
||||
return 1 if payload else 0
|
||||
|
||||
|
||||
def _json_sample_properties(payload: Any) -> dict[str, Any]:
|
||||
feature = None
|
||||
if isinstance(payload, dict) and isinstance(payload.get("features"), list) and payload["features"]:
|
||||
feature = payload["features"][0]
|
||||
elif isinstance(payload, list) and payload:
|
||||
feature = payload[0]
|
||||
elif isinstance(payload, dict):
|
||||
feature = payload
|
||||
if not isinstance(feature, dict):
|
||||
return {}
|
||||
props = feature.get("properties") if isinstance(feature.get("properties"), dict) else feature
|
||||
return {str(key): value for key, value in list(props.items())[:20]}
|
||||
|
||||
|
||||
def _artifact_extension(endpoint: str, content_type: str, payload: bytes) -> str:
|
||||
suffix = Path(endpoint.split("?", 1)[0]).suffix.lower()
|
||||
if suffix in {".json", ".geojson", ".zip", ".pbf"}:
|
||||
return suffix
|
||||
if "geo+json" in content_type or b'"FeatureCollection"' in payload[:4096]:
|
||||
return ".geojson"
|
||||
if "json" in content_type:
|
||||
return ".json"
|
||||
return ".dat"
|
||||
|
||||
|
||||
async def _load_datasource_config(db, name: str) -> DataSourceConfig | None:
|
||||
if db is None:
|
||||
return None
|
||||
result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == name)
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
.order_by(DataSourceConfig.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def _latest_boundary_source_record(db, source_name: str) -> CollectedData | None:
|
||||
result = await db.execute(
|
||||
select(CollectedData)
|
||||
.where(CollectedData.source == source_name)
|
||||
.where(CollectedData.data_type == "earth_boundary_source")
|
||||
.where(CollectedData.is_current.is_(True))
|
||||
.order_by(CollectedData.collected_at.desc().nullslast(), CollectedData.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
class EarthBoundarySourceCollector(BaseCollector):
|
||||
priority = "P1"
|
||||
module = "L3"
|
||||
frequency_hours = 168
|
||||
data_type = "earth_boundary_source"
|
||||
fail_on_empty = True
|
||||
source_kind = "unknown"
|
||||
|
||||
def _default_config(self):
|
||||
source = EARTH_BOUNDARY_DEFAULT_SOURCES.get(self.name)
|
||||
if not source:
|
||||
return None
|
||||
return SimpleNamespace(
|
||||
name=self.name,
|
||||
description=f"内置默认源:{self.name}",
|
||||
endpoint=source["endpoint"],
|
||||
source_type="http",
|
||||
auth_type="none",
|
||||
auth_config={},
|
||||
headers={},
|
||||
config=default_earth_boundary_config(self.name),
|
||||
)
|
||||
|
||||
async def _download_payload(self, config: DataSourceConfig) -> tuple[bytes, str]:
|
||||
request_config = config.config or {}
|
||||
method = str(request_config.get("method") or request_config.get("request_method") or "GET").upper()
|
||||
if method not in {"GET", "POST"}:
|
||||
raise RuntimeError("Earth boundary source collectors support GET and POST only")
|
||||
|
||||
endpoint = str(config.endpoint or "").strip()
|
||||
if not endpoint:
|
||||
raise RuntimeError(
|
||||
f"{self.name} requires an endpoint in Collector Settings before it can collect data"
|
||||
)
|
||||
|
||||
if endpoint.startswith("file://") or Path(endpoint).expanduser().exists():
|
||||
path = Path(endpoint.removeprefix("file://")).expanduser()
|
||||
return path.read_bytes(), "application/octet-stream"
|
||||
|
||||
headers = build_request_headers(config.auth_type, config.auth_config or {}, config.headers or {})
|
||||
params = build_query_params(config.auth_type, config.auth_config or {}, request_config)
|
||||
timeout = float(request_config.get("timeout", 120))
|
||||
json_body = request_config.get("json_body") or request_config.get("body")
|
||||
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
|
||||
response = await client.request(
|
||||
method,
|
||||
endpoint,
|
||||
headers=headers,
|
||||
params=params or None,
|
||||
json=json_body if isinstance(json_body, (dict, list)) else None,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.content, response.headers.get("content-type", "")
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
db = getattr(self, "_db_session", None)
|
||||
config = await _load_datasource_config(db, self.name) or self._default_config()
|
||||
if config is None:
|
||||
raise RuntimeError(
|
||||
f"{self.name} has no active Collector Settings config and no built-in default source."
|
||||
)
|
||||
|
||||
await self.set_phase("fetching_source", message=f"正在下载 {self.source_kind} 源数据")
|
||||
payload, content_type = await self._download_payload(config)
|
||||
sha256 = _sha256_bytes(payload)
|
||||
endpoint = str(config.endpoint or "")
|
||||
extension = _artifact_extension(endpoint, content_type, payload)
|
||||
source_dir = SOURCE_OUTPUT_DIR / self.name
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
artifact_path = source_dir / f"{sha256}{extension}"
|
||||
artifact_path.write_bytes(payload)
|
||||
|
||||
parsed: Any = None
|
||||
if extension in {".json", ".geojson"}:
|
||||
parsed = json.loads(payload.decode("utf-8"))
|
||||
|
||||
feature_count = _json_feature_count(parsed)
|
||||
if feature_count <= 0:
|
||||
raise RuntimeError(f"{self.name} downloaded data but found no JSON/GeoJSON features")
|
||||
|
||||
config_body = config.config or {}
|
||||
target_schema = str(config_body.get("target_schema") or "earth_boundary_source")
|
||||
if target_schema != "earth_boundary_source":
|
||||
raise RuntimeError(f"{self.name} target_schema must be earth_boundary_source")
|
||||
|
||||
await self.update_phase_progress(
|
||||
current=1,
|
||||
total=1,
|
||||
unit="artifact",
|
||||
message=f"已保存 {feature_count} 个 {self.source_kind} feature",
|
||||
progress=100,
|
||||
commit=True,
|
||||
force=True,
|
||||
)
|
||||
|
||||
relative_artifact_path = str(artifact_path.relative_to(REPO_ROOT))
|
||||
return [
|
||||
{
|
||||
"id": f"{self.source_kind}:{sha256}",
|
||||
"name": config.description or self.name,
|
||||
"description": f"Earth boundary source artifact collected from configured endpoint",
|
||||
"source_kind": self.source_kind,
|
||||
"source_id": sha256,
|
||||
"value": feature_count,
|
||||
"unit": "features",
|
||||
"metadata": {
|
||||
"target_schema": target_schema,
|
||||
"source_kind": self.source_kind,
|
||||
"endpoint": endpoint,
|
||||
"method": str(config_body.get("method") or config_body.get("request_method") or "GET").upper(),
|
||||
"artifact_path": relative_artifact_path,
|
||||
"sha256": sha256,
|
||||
"feature_count": feature_count,
|
||||
"size_bytes": len(payload),
|
||||
"content_type": content_type,
|
||||
"license": config_body.get("license"),
|
||||
"mapping_json": config_body.get("mapping_json"),
|
||||
"sample_properties": _json_sample_properties(parsed),
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
class EarthAdmin0BoundaryCollector(EarthBoundarySourceCollector):
|
||||
name = "earth_admin0_boundaries"
|
||||
source_kind = "admin0-boundaries"
|
||||
|
||||
|
||||
class EarthCoastlineCollector(EarthBoundarySourceCollector):
|
||||
name = "earth_coastline"
|
||||
source_kind = "coastline"
|
||||
|
||||
|
||||
class EarthClaimLinesCollector(EarthBoundarySourceCollector):
|
||||
name = "earth_claim_lines"
|
||||
source_kind = "claim-lines"
|
||||
|
||||
|
||||
class EarthBoundaryTileCollector(BaseCollector):
|
||||
name = "earth_boundary_tiles"
|
||||
priority = "P1"
|
||||
module = "L3"
|
||||
frequency_hours = 168
|
||||
data_type = "earth_boundary_tiles"
|
||||
fail_on_empty = False
|
||||
|
||||
async def _run_step(self, args: list[str], *, allow_failure: bool = False) -> dict[str, Any]:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
sys.executable,
|
||||
*args,
|
||||
cwd=REPO_ROOT,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
stdout_bytes, stderr_bytes = await process.communicate()
|
||||
stdout = stdout_bytes.decode("utf-8", errors="replace").strip()
|
||||
stderr = stderr_bytes.decode("utf-8", errors="replace").strip()
|
||||
if process.returncode != 0 and not allow_failure:
|
||||
raise RuntimeError(stderr or stdout or f"command failed: {' '.join(args)}")
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"stdout": stdout,
|
||||
"stderr": stderr,
|
||||
"returncode": process.returncode,
|
||||
}
|
||||
last_line = stdout.splitlines()[-1:] or []
|
||||
if last_line:
|
||||
try:
|
||||
payload["result"] = json.loads(last_line[0])
|
||||
except json.JSONDecodeError:
|
||||
payload["result"] = last_line[0]
|
||||
return payload
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
db = getattr(self, "_db_session", None)
|
||||
if db is None:
|
||||
raise RuntimeError("Earth PMTiles builder requires an active database session")
|
||||
|
||||
await self.set_phase("checking_sources", message="正在检查三类 Earth 边界源")
|
||||
await self.update_phase_progress(
|
||||
current=0,
|
||||
total=3,
|
||||
unit="steps",
|
||||
message="读取 admin0 / coastline / claim-lines 最新采集结果",
|
||||
progress=5,
|
||||
commit=True,
|
||||
force=True,
|
||||
)
|
||||
|
||||
source_records: dict[str, CollectedData] = {}
|
||||
missing_sources: list[str] = []
|
||||
for source_name in EARTH_BOUNDARY_SOURCE_COLLECTORS:
|
||||
record = await _latest_boundary_source_record(db, source_name)
|
||||
if record is None:
|
||||
missing_sources.append(source_name)
|
||||
else:
|
||||
source_records[source_name] = record
|
||||
|
||||
if missing_sources:
|
||||
missing_text = ", ".join(missing_sources)
|
||||
raise RuntimeError(f"未就绪:缺少 {missing_text}。不会更新 Earth 国界。")
|
||||
|
||||
sources = []
|
||||
for source_name, record in source_records.items():
|
||||
metadata = record.extra_data or {}
|
||||
artifact_path = metadata.get("artifact_path")
|
||||
if not artifact_path or not (REPO_ROOT / str(artifact_path)).exists():
|
||||
missing_sources.append(f"{source_name}: artifact missing")
|
||||
continue
|
||||
sources.append(
|
||||
{
|
||||
"id": source_name,
|
||||
"kind": metadata.get("source_kind") or EARTH_BOUNDARY_SOURCE_COLLECTORS[source_name],
|
||||
"path": str(artifact_path),
|
||||
"sha256": metadata.get("sha256"),
|
||||
"featureCount": metadata.get("feature_count"),
|
||||
"license": metadata.get("license"),
|
||||
}
|
||||
)
|
||||
|
||||
if missing_sources:
|
||||
missing_text = ", ".join(missing_sources)
|
||||
raise RuntimeError(f"未就绪:{missing_text}。不会更新 Earth 国界。")
|
||||
|
||||
source_manifest = {
|
||||
"schema": "planet-earth-boundary-sources/v2",
|
||||
"sources": sources,
|
||||
"povPolicy": _read_json(POV_POLICY_PATH),
|
||||
}
|
||||
SOURCE_OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
with SOURCE_MANIFEST_PATH.open("w", encoding="utf-8") as f:
|
||||
json.dump(source_manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
build_input_hash = _build_input_hash(source_manifest)
|
||||
await self.update_phase_progress(
|
||||
current=1,
|
||||
total=3,
|
||||
unit="steps",
|
||||
message="三类边界源已就绪",
|
||||
progress=35,
|
||||
commit=True,
|
||||
force=True,
|
||||
)
|
||||
|
||||
await self.set_phase("checking_readiness", message="正在检查 Earth 国界构建就绪状态")
|
||||
missing_tools = [tool for tool in ("tippecanoe", "pmtiles") if shutil.which(tool) is None]
|
||||
readiness_result = {
|
||||
"returncode": 0,
|
||||
"result": {
|
||||
"ready": True,
|
||||
"failures": [f"external tool not found in PATH: {tool}" for tool in missing_tools],
|
||||
"sources": sources,
|
||||
"artifact": str(PMTILES_ARTIFACT_PATH.relative_to(REPO_ROOT)),
|
||||
"fallback_builder": "geojson-high-precision" if missing_tools else None,
|
||||
},
|
||||
}
|
||||
|
||||
await self.set_phase("building_tiles", message="正在检查 Earth 国界瓦片产物")
|
||||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||||
build_skipped = _has_current_artifacts(boundary_manifest, build_input_hash)
|
||||
if build_skipped:
|
||||
build_result = {
|
||||
"result": {
|
||||
"status": "unchanged",
|
||||
"reason": "source manifest and build config hash unchanged",
|
||||
"buildInputHash": build_input_hash,
|
||||
}
|
||||
}
|
||||
elif shutil.which("tippecanoe") and shutil.which("pmtiles"):
|
||||
admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries")
|
||||
coastline = next(source for source in sources if source["kind"] == "coastline")
|
||||
claim_lines = next(source for source in sources if source["kind"] == "claim-lines")
|
||||
build_result = await self._run_step(
|
||||
[
|
||||
"scripts/build_earth_boundary_pmtiles.py",
|
||||
"--admin0-source",
|
||||
admin0["path"],
|
||||
"--coastline-source",
|
||||
coastline["path"],
|
||||
"--claims-source",
|
||||
claim_lines["path"],
|
||||
"--output",
|
||||
str(PMTILES_ARTIFACT_PATH.relative_to(REPO_ROOT)),
|
||||
"--manifest",
|
||||
str(BOUNDARY_MANIFEST_PATH.relative_to(REPO_ROOT)),
|
||||
"--build-input-hash",
|
||||
build_input_hash,
|
||||
"--pov-policy",
|
||||
str(POV_POLICY_PATH.relative_to(REPO_ROOT)),
|
||||
]
|
||||
)
|
||||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||||
else:
|
||||
admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries")
|
||||
coastline = next(source for source in sources if source["kind"] == "coastline")
|
||||
claim_lines = next(source for source in sources if source["kind"] == "claim-lines")
|
||||
build_result = await self._run_step(
|
||||
[
|
||||
"scripts/build_earth_boundary_china_pov_geojson.py",
|
||||
"--admin0-source",
|
||||
admin0["path"],
|
||||
"--coastline-source",
|
||||
coastline["path"],
|
||||
"--claims-source",
|
||||
claim_lines["path"],
|
||||
"--output-dir",
|
||||
str(BOUNDARY_OUTPUT_DIR.relative_to(REPO_ROOT)),
|
||||
"--build-input-hash",
|
||||
build_input_hash,
|
||||
]
|
||||
)
|
||||
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
|
||||
boundary_stats = _directory_stats(BOUNDARY_OUTPUT_DIR)
|
||||
pmtiles_exists = PMTILES_ARTIFACT_PATH.exists()
|
||||
pmtiles_size = PMTILES_ARTIFACT_PATH.stat().st_size if pmtiles_exists else 0
|
||||
await self.update_phase_progress(
|
||||
current=2,
|
||||
total=3,
|
||||
unit="steps",
|
||||
message=(
|
||||
"边界源未变化,已跳过瓦片重建"
|
||||
if build_skipped
|
||||
else f"已生成 {boundary_manifest.get('tileProvider') or 'boundary'} 国界产物"
|
||||
),
|
||||
progress=80,
|
||||
commit=True,
|
||||
force=True,
|
||||
)
|
||||
|
||||
await self.set_phase("indexing_artifacts", message="正在登记边界瓦片产物")
|
||||
tile_counts = boundary_manifest.get("tiles", {}).get("countsByZoom", {})
|
||||
records = [
|
||||
{
|
||||
"id": "source-manifest",
|
||||
"name": "Earth boundary source manifest",
|
||||
"description": "Offline source collection manifest for Earth boundary tiles",
|
||||
"value": len(source_manifest.get("sources", [])),
|
||||
"unit": "sources",
|
||||
"metadata": {
|
||||
"manifest_path": str(SOURCE_MANIFEST_PATH.relative_to(REPO_ROOT)),
|
||||
"manifest": source_manifest,
|
||||
"collector_result": {
|
||||
"status": "loaded_from_collected_data",
|
||||
"sources": [source["id"] for source in sources],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "production-readiness",
|
||||
"name": "Earth boundary production readiness",
|
||||
"description": "Checks whether all source artifacts and boundary build tooling are available",
|
||||
"value": 1 if readiness_result.get("returncode") == 0 else 0,
|
||||
"unit": "ready",
|
||||
"metadata": {
|
||||
"result": readiness_result.get("result"),
|
||||
"returncode": readiness_result.get("returncode"),
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "boundary-manifest",
|
||||
"name": "Earth boundary tile manifest",
|
||||
"description": "Versioned static vector tile manifest for Earth country boundaries",
|
||||
"value": boundary_stats["file_count"],
|
||||
"unit": "files",
|
||||
"metadata": {
|
||||
"manifest_path": str(BOUNDARY_MANIFEST_PATH.relative_to(REPO_ROOT)),
|
||||
"output_dir": str(BOUNDARY_OUTPUT_DIR.relative_to(REPO_ROOT)),
|
||||
"size_bytes": boundary_stats["size_bytes"],
|
||||
"manifest": boundary_manifest,
|
||||
"collector_result": build_result.get("result"),
|
||||
"build_skipped": build_skipped,
|
||||
"production_target": BUILD_CONFIG["production_target"],
|
||||
"pmtiles_artifact": str(PMTILES_ARTIFACT_PATH.relative_to(REPO_ROOT)),
|
||||
"pmtiles_exists": pmtiles_exists,
|
||||
},
|
||||
},
|
||||
]
|
||||
if pmtiles_exists:
|
||||
records.append(
|
||||
{
|
||||
"id": "pmtiles-artifact",
|
||||
"name": "Earth boundary PMTiles artifact",
|
||||
"description": "Single-file PMTiles/MVT artifact for Earth boundaries",
|
||||
"value": pmtiles_size,
|
||||
"unit": "bytes",
|
||||
"metadata": {
|
||||
"path": str(PMTILES_ARTIFACT_PATH.relative_to(REPO_ROOT)),
|
||||
"exists": pmtiles_exists,
|
||||
"provider": "pmtiles-mvt",
|
||||
},
|
||||
}
|
||||
)
|
||||
for zoom, count in sorted(tile_counts.items(), key=lambda item: int(item[0])):
|
||||
records.append(
|
||||
{
|
||||
"id": f"tile-z{zoom}",
|
||||
"name": f"Earth boundary tiles z{zoom}",
|
||||
"description": f"Generated Earth boundary tile count for zoom {zoom}",
|
||||
"value": int(count),
|
||||
"unit": "tiles",
|
||||
"metadata": {
|
||||
"zoom": int(zoom),
|
||||
"tile_count": int(count),
|
||||
"output_dir": str((BOUNDARY_OUTPUT_DIR / str(zoom)).relative_to(REPO_ROOT)),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
await self.update_phase_progress(
|
||||
current=3,
|
||||
total=3,
|
||||
unit="steps",
|
||||
message="边界瓦片产物已登记",
|
||||
progress=100,
|
||||
commit=True,
|
||||
force=True,
|
||||
)
|
||||
return records
|
||||
@@ -0,0 +1,57 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.collectors.base import BaseCollector
|
||||
from app.services.earth_news_store import list_all_earth_news_records
|
||||
|
||||
|
||||
class MediaNewsArchiveCollector(BaseCollector):
|
||||
name = "media_news_archive"
|
||||
priority = "P2"
|
||||
module = "L4"
|
||||
frequency_hours = 12
|
||||
data_type = "news_item"
|
||||
fail_on_empty = False
|
||||
|
||||
async def fetch(self) -> list[dict[str, Any]]:
|
||||
if not self._db_session:
|
||||
return []
|
||||
|
||||
records = await list_all_earth_news_records(self._db_session)
|
||||
items: list[dict[str, Any]] = []
|
||||
for record in records:
|
||||
location_meta = dict(record.location_meta or {})
|
||||
target = location_meta.get("target") if isinstance(location_meta.get("target"), dict) else {}
|
||||
country = target.get("country")
|
||||
city = target.get("city")
|
||||
items.append(
|
||||
{
|
||||
"id": record.id,
|
||||
"source_id": record.id,
|
||||
"name": record.title,
|
||||
"title": record.title,
|
||||
"description": record.summary,
|
||||
"country": country,
|
||||
"city": city,
|
||||
"latitude": record.latitude,
|
||||
"longitude": record.longitude,
|
||||
"reference_date": record.published_at,
|
||||
"metadata": {
|
||||
"url": record.url,
|
||||
"source": record.source,
|
||||
"feed_name": record.feed_name,
|
||||
"region": record.region,
|
||||
"homepage_url": record.homepage_url,
|
||||
"published_at": record.published_at.isoformat() if record.published_at else None,
|
||||
"location_label": record.location_label,
|
||||
"location_source": record.location_source,
|
||||
"verified": record.verified,
|
||||
"location_meta": location_meta,
|
||||
"first_seen_at": record.first_seen_at.isoformat() if record.first_seen_at else None,
|
||||
"last_seen_at": record.last_seen_at.isoformat() if record.last_seen_at else None,
|
||||
"resolved_at": record.resolved_at.isoformat() if record.resolved_at else None,
|
||||
},
|
||||
}
|
||||
)
|
||||
return items
|
||||
@@ -8,6 +8,7 @@ import re
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.target_schema_registry import TargetSchema, get_target_schema
|
||||
@@ -254,6 +255,12 @@ def _best_field_match(field_name: str, candidates: list[str]) -> str | None:
|
||||
"lat": ("lat", "latitude", "y"),
|
||||
"lon": ("lon", "lng", "longitude", "x"),
|
||||
"mmsi": ("mmsi",),
|
||||
"geometry": ("geometry", "geom"),
|
||||
"properties": ("properties", "props"),
|
||||
"source_kind": ("source_kind", "kind", "type"),
|
||||
"feature_count": ("feature_count", "features_count", "count"),
|
||||
"artifact_path": ("artifact_path", "path", "file"),
|
||||
"sha256": ("sha256", "hash", "checksum"),
|
||||
"sog": ("sog", "speed", "speedOverGround"),
|
||||
"cog": ("cog", "course", "courseOverGround"),
|
||||
"received_at": ("received_at", "timestamp", "time", "updated_at"),
|
||||
@@ -294,6 +301,52 @@ async def persist_mapped_records(
|
||||
transport: str | None = None,
|
||||
) -> int:
|
||||
"""Persist validated mapped records to the destination for a target schema."""
|
||||
if target_schema == "earth_boundary_source":
|
||||
from app.models.collected_data import CollectedData
|
||||
|
||||
now = datetime.now(UTC)
|
||||
written_count = 0
|
||||
for index, record in enumerate(records):
|
||||
source_id = record.get("source_id") or record.get("sha256") or str(index)
|
||||
entity_key = f"{datasource_name}:{source_id}"
|
||||
previous_result = await db.execute(
|
||||
select(CollectedData)
|
||||
.where(CollectedData.source == datasource_name)
|
||||
.where(CollectedData.entity_key == entity_key)
|
||||
.where(CollectedData.is_current.is_(True))
|
||||
.order_by(CollectedData.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
previous = previous_result.scalar_one_or_none()
|
||||
if previous is not None:
|
||||
previous.is_current = False
|
||||
db.add(
|
||||
CollectedData(
|
||||
source=datasource_name,
|
||||
source_id=str(source_id),
|
||||
entity_key=entity_key,
|
||||
data_type=target_schema,
|
||||
name=record.get("name") or str(source_id),
|
||||
description=f"Earth boundary source artifact: {record.get('source_kind')}",
|
||||
extra_data={
|
||||
**record,
|
||||
"datasource_config_id": datasource_config_id,
|
||||
"mapping_version": mapping_version,
|
||||
"delivery_mode": delivery_mode or "polling",
|
||||
"transport": transport or "http",
|
||||
},
|
||||
collected_at=now,
|
||||
is_valid=1,
|
||||
is_current=True,
|
||||
previous_record_id=previous.id if previous else None,
|
||||
change_type="updated" if previous else "created",
|
||||
change_summary={},
|
||||
)
|
||||
)
|
||||
written_count += 1
|
||||
await db.commit()
|
||||
return written_count
|
||||
|
||||
if target_schema == "vessel_ais":
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
|
||||
@@ -6,6 +6,8 @@ from datetime import UTC, datetime
|
||||
from email.utils import parsedate_to_datetime
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
@@ -13,6 +15,12 @@ import xml.etree.ElementTree as ET
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.countries import COUNTRY_VARIANTS_MAP, get_country_centroid, normalize_country
|
||||
from app.schemas.ai import SituationalAnalysisRequest
|
||||
from app.services.ai_client import AIProviderClient
|
||||
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
|
||||
|
||||
|
||||
USER_AGENT = "PlanetEarthNewsBoard/1.0 (+https://planet.local)"
|
||||
@@ -20,6 +28,9 @@ REQUEST_TIMEOUT = 12.0
|
||||
MAX_ITEMS_PER_SOURCE = 6
|
||||
MAX_ITEMS_TOTAL = 12
|
||||
STALE_CACHE_MAX_AGE_SECONDS = 60 * 45
|
||||
RSS_SUPPLEMENT_MAX_AGE_SECONDS = STALE_CACHE_MAX_AGE_SECONDS
|
||||
MAX_TARGET_INFERENCE_CONCURRENCY = 3
|
||||
TARGET_INFERENCE_TIMEOUT_SECONDS = 6.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,6 +60,17 @@ class NewsFeedSource:
|
||||
priority: int = 100
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NewsTargetLocation:
|
||||
latitude: float
|
||||
longitude: float
|
||||
label: str
|
||||
source: str
|
||||
confidence: float | None = None
|
||||
country: str | None = None
|
||||
city: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedNewsItem:
|
||||
id: str
|
||||
@@ -60,6 +82,13 @@ class ParsedNewsItem:
|
||||
feed_region: str
|
||||
homepage_url: str
|
||||
published_at: datetime | None
|
||||
target_location: NewsTargetLocation | None = None
|
||||
target_resolution_stage: str = "unresolved"
|
||||
target_ai_attempted: bool = False
|
||||
target_ai_status: str = "not_attempted"
|
||||
target_ai_error: str | None = None
|
||||
target_debug_note: str | None = None
|
||||
location_patch: dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -236,6 +265,17 @@ NEWS_FEED_SOURCES: tuple[NewsFeedSource, ...] = (
|
||||
|
||||
|
||||
_REGION_CACHE: dict[str, CachedRegionFeed] = {}
|
||||
_news_target_geocode = build_default_nominatim_geocoder(user_agent=USER_AGENT)
|
||||
_CITY_HINTS: tuple[dict[str, str | None], ...] = (
|
||||
{"name": "Beijing", "country": "中国"},
|
||||
{"name": "Havana", "country": "古巴"},
|
||||
{"name": "Kyiv", "country": "乌克兰"},
|
||||
{"name": "Bangkok", "country": "泰国"},
|
||||
{"name": "Tehran", "country": "伊朗"},
|
||||
{"name": "Moscow", "country": "俄罗斯"},
|
||||
{"name": "Taipei", "country": "中国(台湾)"},
|
||||
{"name": "Hong Kong", "country": "中国(香港)"},
|
||||
)
|
||||
|
||||
|
||||
def determine_focus_region(lat: float | None, lon: float | None) -> str:
|
||||
@@ -258,6 +298,341 @@ def get_region_anchor(region: str) -> RegionAnchor:
|
||||
return REGION_ANCHORS.get(region, REGION_ANCHORS["global"])
|
||||
|
||||
|
||||
def _coerce_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
value = str(value)
|
||||
cleaned = re.sub(r"\s+", " ", value).strip()
|
||||
return cleaned or None
|
||||
|
||||
|
||||
def _contains_location_alias(text: str, alias: str) -> bool:
|
||||
normalized_alias = _coerce_str(alias)
|
||||
if not normalized_alias:
|
||||
return False
|
||||
if re.search(r"[A-Za-z]", normalized_alias):
|
||||
pattern = r"(?<![A-Za-z])" + re.escape(normalized_alias) + r"(?![A-Za-z])"
|
||||
return re.search(pattern, text, flags=re.IGNORECASE) is not None
|
||||
return normalized_alias in text
|
||||
|
||||
|
||||
def _iter_searchable_country_variants(
|
||||
canonical: str,
|
||||
variants: list[str],
|
||||
) -> tuple[str, ...]:
|
||||
searchable: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for variant in (canonical, *variants):
|
||||
normalized = _coerce_str(variant)
|
||||
if not normalized:
|
||||
continue
|
||||
if re.fullmatch(r"[A-Z]{2,3}", normalized):
|
||||
continue
|
||||
if len(normalized) <= 2:
|
||||
continue
|
||||
key = normalized.casefold()
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
searchable.append(normalized)
|
||||
return tuple(searchable)
|
||||
|
||||
|
||||
def _coerce_float(value: Any) -> float | None:
|
||||
try:
|
||||
parsed = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if not math.isfinite(parsed):
|
||||
return None
|
||||
return parsed
|
||||
|
||||
|
||||
def _first_json_object(text: str) -> dict[str, Any] | None:
|
||||
if not text:
|
||||
return None
|
||||
decoder = json.JSONDecoder()
|
||||
for index, char in enumerate(text):
|
||||
if char != "{":
|
||||
continue
|
||||
try:
|
||||
payload, _ = decoder.raw_decode(text[index:])
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(payload, dict):
|
||||
return payload
|
||||
return None
|
||||
|
||||
|
||||
async def _geocode_target_location(query: str) -> dict[str, Any] | None:
|
||||
return await asyncio.to_thread(_news_target_geocode, query)
|
||||
|
||||
|
||||
async def _build_target_location_from_payload(
|
||||
payload: dict[str, Any],
|
||||
) -> NewsTargetLocation | None:
|
||||
country = normalize_country(payload.get("country"))
|
||||
city = _coerce_str(payload.get("city"))
|
||||
matched_location_name = _coerce_str(payload.get("matched_location_name"))
|
||||
confidence = _coerce_float(payload.get("confidence"))
|
||||
if confidence is not None:
|
||||
confidence = max(0.0, min(confidence, 1.0))
|
||||
|
||||
latitude = _coerce_float(payload.get("latitude"))
|
||||
longitude = _coerce_float(payload.get("longitude"))
|
||||
if latitude not in (None, 0.0) and longitude not in (None, 0.0):
|
||||
label = matched_location_name or ", ".join(part for part in (city, country) if part) or "关联位置"
|
||||
return NewsTargetLocation(
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
label=label,
|
||||
source="ai_inferred_target",
|
||||
confidence=confidence,
|
||||
country=country,
|
||||
city=city,
|
||||
)
|
||||
|
||||
geocode_queries: list[str] = []
|
||||
for value in (
|
||||
", ".join(part for part in (city, country) if part),
|
||||
matched_location_name,
|
||||
city,
|
||||
country,
|
||||
):
|
||||
normalized = _coerce_str(value)
|
||||
if normalized and normalized not in geocode_queries:
|
||||
geocode_queries.append(normalized)
|
||||
|
||||
for query in geocode_queries:
|
||||
try:
|
||||
result = await _geocode_target_location(query)
|
||||
except Exception:
|
||||
continue
|
||||
if not isinstance(result, dict):
|
||||
continue
|
||||
latitude = _coerce_float(result.get("lat"))
|
||||
longitude = _coerce_float(result.get("lon"))
|
||||
if latitude in (None, 0.0) or longitude in (None, 0.0):
|
||||
continue
|
||||
label = (
|
||||
_coerce_str(result.get("display_name"))
|
||||
or matched_location_name
|
||||
or ", ".join(part for part in (city, country) if part)
|
||||
or query
|
||||
)
|
||||
return NewsTargetLocation(
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
label=label,
|
||||
source="ai_inferred_target",
|
||||
confidence=confidence,
|
||||
country=country,
|
||||
city=city,
|
||||
)
|
||||
|
||||
centroid = get_country_centroid(country)
|
||||
if centroid:
|
||||
label = matched_location_name or city or country or "关联位置"
|
||||
return NewsTargetLocation(
|
||||
latitude=centroid["latitude"],
|
||||
longitude=centroid["longitude"],
|
||||
label=label,
|
||||
source="ai_inferred_target",
|
||||
confidence=confidence,
|
||||
country=country,
|
||||
city=city,
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def _extract_target_location_from_text(item: ParsedNewsItem) -> NewsTargetLocation | None:
|
||||
combined_text = " ".join(part for part in (item.title, item.summary) if part).strip()
|
||||
if not combined_text:
|
||||
return None
|
||||
|
||||
for hint in _CITY_HINTS:
|
||||
city_name = _coerce_str(hint.get("name"))
|
||||
if not city_name or not _contains_location_alias(combined_text, city_name):
|
||||
continue
|
||||
country = normalize_country(hint.get("country"))
|
||||
geocode_query = ", ".join(part for part in (city_name, country) if part)
|
||||
try:
|
||||
result = await _geocode_target_location(geocode_query)
|
||||
except Exception:
|
||||
result = None
|
||||
if isinstance(result, dict):
|
||||
latitude = _coerce_float(result.get("lat"))
|
||||
longitude = _coerce_float(result.get("lon"))
|
||||
if latitude not in (None, 0.0) and longitude not in (None, 0.0):
|
||||
return NewsTargetLocation(
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
label=_coerce_str(result.get("display_name")) or geocode_query,
|
||||
source="headline_location_hint",
|
||||
confidence=0.78,
|
||||
country=country,
|
||||
city=city_name,
|
||||
)
|
||||
centroid = get_country_centroid(country)
|
||||
if centroid:
|
||||
return NewsTargetLocation(
|
||||
latitude=centroid["latitude"],
|
||||
longitude=centroid["longitude"],
|
||||
label=geocode_query,
|
||||
source="headline_location_hint",
|
||||
confidence=0.68,
|
||||
country=country,
|
||||
city=city_name,
|
||||
)
|
||||
|
||||
for canonical, variants in COUNTRY_VARIANTS_MAP.items():
|
||||
if not get_country_centroid(canonical):
|
||||
continue
|
||||
searchable_variants = _iter_searchable_country_variants(canonical, variants)
|
||||
if not any(_contains_location_alias(combined_text, variant) for variant in searchable_variants):
|
||||
continue
|
||||
centroid = get_country_centroid(canonical)
|
||||
if not centroid:
|
||||
continue
|
||||
return NewsTargetLocation(
|
||||
latitude=centroid["latitude"],
|
||||
longitude=centroid["longitude"],
|
||||
label=canonical,
|
||||
source="headline_country_hint",
|
||||
confidence=0.62,
|
||||
country=canonical,
|
||||
city=None,
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def _infer_news_target_location(
|
||||
item: ParsedNewsItem,
|
||||
*,
|
||||
provider_client: AIProviderClient | None,
|
||||
) -> NewsTargetLocation | None:
|
||||
text_hint = await _extract_target_location_from_text(item)
|
||||
if text_hint is not None and text_hint.city:
|
||||
item.target_resolution_stage = text_hint.source
|
||||
item.target_ai_attempted = False
|
||||
item.target_ai_status = "skipped_text_hint"
|
||||
item.target_ai_error = None
|
||||
item.target_debug_note = f"text hint matched {text_hint.label}"
|
||||
return text_hint
|
||||
|
||||
if provider_client is None:
|
||||
item.target_resolution_stage = text_hint.source if text_hint is not None else "unresolved"
|
||||
item.target_ai_attempted = False
|
||||
item.target_ai_status = "unavailable"
|
||||
item.target_ai_error = "AI provider is not configured or unavailable for earth-feed."
|
||||
item.target_debug_note = (
|
||||
f"text hint matched {text_hint.label}" if text_hint is not None else "no text location hint matched"
|
||||
)
|
||||
return text_hint
|
||||
|
||||
item.target_ai_attempted = True
|
||||
item.target_ai_status = "attempted"
|
||||
item.target_ai_error = None
|
||||
item.target_debug_note = (
|
||||
f"text hint matched {text_hint.label}" if text_hint is not None else "no text location hint matched"
|
||||
)
|
||||
|
||||
request = SituationalAnalysisRequest(
|
||||
title="Infer likely event location for Earth news cruise",
|
||||
objective=(
|
||||
"Return exactly one strict JSON object for the most likely physical "
|
||||
"location the news event is about. Prefer the host city when a state "
|
||||
"visit, summit, meeting, attack, or disaster is clearly centered in a "
|
||||
"known city. Fall back to the best-supported country only when a city "
|
||||
"cannot be inferred."
|
||||
),
|
||||
context={
|
||||
"news_item": {
|
||||
"title": item.title,
|
||||
"summary": item.summary,
|
||||
"source": item.source,
|
||||
"feed_name": item.feed_name,
|
||||
"feed_region": item.feed_region,
|
||||
"url": item.url,
|
||||
"published_at": (
|
||||
item.published_at.isoformat().replace("+00:00", "Z")
|
||||
if item.published_at
|
||||
else None
|
||||
),
|
||||
},
|
||||
"required_json_schema": {
|
||||
"country": "string|null",
|
||||
"city": "string|null",
|
||||
"matched_location_name": "string|null",
|
||||
"latitude": "number|null",
|
||||
"longitude": "number|null",
|
||||
"confidence": "number from 0 to 1",
|
||||
"reasoning_summary": "short string",
|
||||
},
|
||||
},
|
||||
constraints=[
|
||||
"Return only strict JSON. Do not wrap it in markdown.",
|
||||
"Prefer the event location, not the newsroom or publisher headquarters.",
|
||||
"When a country visit or summit is the clear topic but the city is omitted, use the most likely host city only if it is broadly public knowledge.",
|
||||
"Use null for unknown fields instead of inventing details.",
|
||||
"Calibrate confidence conservatively: 0.75+ only when the city is strongly supported, 0.55-0.74 for country-level or likely city inference, below 0.55 when weak.",
|
||||
],
|
||||
)
|
||||
try:
|
||||
response = await provider_client.analyze(request)
|
||||
except Exception as exc:
|
||||
item.target_resolution_stage = text_hint.source if text_hint is not None else "unresolved"
|
||||
item.target_ai_status = "provider_error"
|
||||
item.target_ai_error = str(exc)
|
||||
return text_hint
|
||||
|
||||
payload = _first_json_object(response.content)
|
||||
if not isinstance(payload, dict):
|
||||
item.target_resolution_stage = text_hint.source if text_hint is not None else "unresolved"
|
||||
item.target_ai_status = "parse_error"
|
||||
item.target_ai_error = "AI response did not contain a parseable JSON object."
|
||||
return text_hint
|
||||
|
||||
target = await _build_target_location_from_payload(payload)
|
||||
if target is None:
|
||||
item.target_resolution_stage = text_hint.source if text_hint is not None else "unresolved"
|
||||
item.target_ai_status = "no_result"
|
||||
item.target_ai_error = "AI returned no usable target coordinates or geocodeable location."
|
||||
return text_hint
|
||||
if target.confidence is not None and target.confidence < 0.45:
|
||||
item.target_resolution_stage = text_hint.source if text_hint is not None else "unresolved"
|
||||
item.target_ai_status = "low_confidence"
|
||||
item.target_ai_error = f"AI target confidence too low: {target.confidence:.2f}"
|
||||
return text_hint
|
||||
item.target_resolution_stage = target.source
|
||||
item.target_ai_status = "success"
|
||||
item.target_ai_error = None
|
||||
item.target_debug_note = f"ai inferred {target.label}"
|
||||
return target
|
||||
|
||||
|
||||
async def _enrich_items_with_target_locations(
|
||||
items: list[ParsedNewsItem],
|
||||
*,
|
||||
provider_client: AIProviderClient | None,
|
||||
) -> list[ParsedNewsItem]:
|
||||
if not items:
|
||||
return items
|
||||
|
||||
semaphore = asyncio.Semaphore(MAX_TARGET_INFERENCE_CONCURRENCY)
|
||||
|
||||
async def enrich(item: ParsedNewsItem) -> ParsedNewsItem:
|
||||
async with semaphore:
|
||||
target = await _infer_news_target_location(item, provider_client=provider_client)
|
||||
item.target_location = target
|
||||
return item
|
||||
|
||||
return list(await asyncio.gather(*(enrich(item) for item in items)))
|
||||
|
||||
|
||||
def get_sources_for_region(region: str) -> list[NewsFeedSource]:
|
||||
return sorted(
|
||||
[source for source in NEWS_FEED_SOURCES if source.region in {"global", region}],
|
||||
@@ -385,9 +760,117 @@ def _serialize_sources(sources: list[NewsFeedSource]) -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _serialize_anchor(anchor: RegionAnchor) -> dict[str, Any]:
|
||||
return {
|
||||
"region": anchor.region,
|
||||
"label": anchor.label,
|
||||
"latitude": anchor.latitude,
|
||||
"longitude": anchor.longitude,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_target(target: NewsTargetLocation | None) -> dict[str, Any] | None:
|
||||
if target is None:
|
||||
return None
|
||||
return {
|
||||
"latitude": target.latitude,
|
||||
"longitude": target.longitude,
|
||||
"label": target.label,
|
||||
"source": target.source,
|
||||
"confidence": target.confidence,
|
||||
"country": target.country,
|
||||
"city": target.city,
|
||||
}
|
||||
|
||||
|
||||
def build_anchor_location_patch(
|
||||
item: ParsedNewsItem,
|
||||
*,
|
||||
queued: bool = False,
|
||||
queue_available: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
anchor = get_region_anchor(item.feed_region)
|
||||
if queued:
|
||||
resolution_stage = "queued"
|
||||
ai_status = "queued"
|
||||
debug_note = "queued for async target location inference"
|
||||
else:
|
||||
resolution_stage = item.target_resolution_stage
|
||||
ai_status = item.target_ai_status
|
||||
debug_note = item.target_debug_note
|
||||
return {
|
||||
"latitude": anchor.latitude,
|
||||
"longitude": anchor.longitude,
|
||||
"location_label": anchor.label,
|
||||
"location_source": "region_anchor",
|
||||
"verified": False,
|
||||
"location_meta": {
|
||||
"resolution_stage": resolution_stage,
|
||||
"ai_attempted": item.target_ai_attempted,
|
||||
"ai_status": ai_status,
|
||||
"ai_error": item.target_ai_error,
|
||||
"debug_note": debug_note,
|
||||
"queue_available": queue_available,
|
||||
"target": None,
|
||||
"anchor": _serialize_anchor(anchor),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_target_location_patch(item: ParsedNewsItem, target: NewsTargetLocation | None) -> dict[str, Any]:
|
||||
if target is None:
|
||||
return build_anchor_location_patch(item)
|
||||
anchor = get_region_anchor(item.feed_region)
|
||||
return {
|
||||
"latitude": target.latitude,
|
||||
"longitude": target.longitude,
|
||||
"location_label": target.label,
|
||||
"location_source": target.source,
|
||||
"verified": True,
|
||||
"location_meta": {
|
||||
"resolution_stage": item.target_resolution_stage,
|
||||
"ai_attempted": item.target_ai_attempted,
|
||||
"ai_status": item.target_ai_status,
|
||||
"ai_error": item.target_ai_error,
|
||||
"debug_note": item.target_debug_note,
|
||||
"target": _serialize_target(target),
|
||||
"anchor": _serialize_anchor(anchor),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_target_location_job_payload(item: ParsedNewsItem) -> dict[str, Any]:
|
||||
published_at = item.published_at
|
||||
return {
|
||||
"id": item.id,
|
||||
"title": item.title,
|
||||
"summary": item.summary,
|
||||
"url": item.url,
|
||||
"source": item.source,
|
||||
"feed_name": item.feed_name,
|
||||
"feed_region": item.feed_region,
|
||||
"homepage_url": item.homepage_url,
|
||||
"published_at": published_at.isoformat().replace("+00:00", "Z") if published_at else None,
|
||||
}
|
||||
|
||||
|
||||
def parsed_news_item_from_job_payload(payload: dict[str, Any]) -> ParsedNewsItem:
|
||||
return ParsedNewsItem(
|
||||
id=str(payload.get("id") or ""),
|
||||
title=str(payload.get("title") or ""),
|
||||
summary=str(payload.get("summary") or ""),
|
||||
url=str(payload.get("url") or ""),
|
||||
source=str(payload.get("source") or ""),
|
||||
feed_name=str(payload.get("feed_name") or ""),
|
||||
feed_region=str(payload.get("feed_region") or "global"),
|
||||
homepage_url=str(payload.get("homepage_url") or ""),
|
||||
published_at=_parse_datetime(_coerce_str(payload.get("published_at"))),
|
||||
)
|
||||
|
||||
|
||||
def _serialize_item(item: ParsedNewsItem, *, active_region: str) -> dict[str, Any]:
|
||||
published_at = item.published_at
|
||||
anchor = get_region_anchor(item.feed_region)
|
||||
location_patch = item.location_patch or build_target_location_patch(item, item.target_location)
|
||||
return {
|
||||
"id": item.id,
|
||||
"title": item.title,
|
||||
@@ -398,10 +881,12 @@ def _serialize_item(item: ParsedNewsItem, *, active_region: str) -> dict[str, An
|
||||
"region": item.feed_region,
|
||||
"homepage_url": item.homepage_url,
|
||||
"published_at": published_at.isoformat().replace("+00:00", "Z") if published_at else None,
|
||||
"latitude": anchor.latitude,
|
||||
"longitude": anchor.longitude,
|
||||
"location_label": anchor.label,
|
||||
"location_inferred": True,
|
||||
"latitude": location_patch["latitude"],
|
||||
"longitude": location_patch["longitude"],
|
||||
"location_label": location_patch["location_label"],
|
||||
"location_source": location_patch["location_source"],
|
||||
"verified": location_patch["verified"],
|
||||
"location_meta": location_patch["location_meta"],
|
||||
"is_focus_match": item.feed_region == active_region,
|
||||
}
|
||||
|
||||
@@ -472,6 +957,47 @@ def _store_region_cache(region: str, *, items: list[ParsedNewsItem], sources: li
|
||||
)
|
||||
|
||||
|
||||
async def _apply_cached_locations_and_enqueue(items: list[ParsedNewsItem]) -> list[ParsedNewsItem]:
|
||||
if not items:
|
||||
return items
|
||||
|
||||
from app.services.earth_news_queue import (
|
||||
enqueue_target_location_job,
|
||||
get_cached_target_location_patch,
|
||||
)
|
||||
|
||||
async def apply_location(item: ParsedNewsItem) -> ParsedNewsItem:
|
||||
cached_patch = await get_cached_target_location_patch(item.id)
|
||||
if cached_patch:
|
||||
item.location_patch = cached_patch
|
||||
return item
|
||||
|
||||
queued = await enqueue_target_location_job(build_target_location_job_payload(item))
|
||||
item.location_patch = build_anchor_location_patch(
|
||||
item,
|
||||
queued=queued,
|
||||
queue_available=queued,
|
||||
)
|
||||
return item
|
||||
|
||||
return list(await asyncio.gather(*(apply_location(item) for item in items)))
|
||||
|
||||
|
||||
async def _enqueue_unverified_locations(items: list[ParsedNewsItem]) -> None:
|
||||
if not items:
|
||||
return
|
||||
|
||||
from app.services.earth_news_queue import enqueue_target_location_job
|
||||
|
||||
await asyncio.gather(
|
||||
*(
|
||||
enqueue_target_location_job(build_target_location_job_payload(item))
|
||||
for item in items
|
||||
if item.location_patch is None or item.location_patch.get("verified") is False
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def _fetch_source(
|
||||
client: httpx.AsyncClient,
|
||||
source: NewsFeedSource,
|
||||
@@ -484,11 +1010,10 @@ async def _fetch_source(
|
||||
return source, [], str(exc)
|
||||
|
||||
|
||||
async def get_earth_news_payload(lat: float | None = None, lon: float | None = None) -> dict[str, Any]:
|
||||
active_region = determine_focus_region(lat, lon)
|
||||
sources = get_sources_for_region(active_region)
|
||||
async def _fetch_rss_items_for_sources(
|
||||
sources: list[NewsFeedSource],
|
||||
) -> tuple[list[ParsedNewsItem], list[str]]:
|
||||
errors: list[str] = []
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
follow_redirects=True,
|
||||
@@ -502,9 +1027,29 @@ async def get_earth_news_payload(lat: float | None = None, lon: float | None = N
|
||||
errors.append(f"{source.name}: {error}")
|
||||
continue
|
||||
fetched_items.extend(items)
|
||||
return fetched_items, errors
|
||||
|
||||
|
||||
def _needs_rss_supplement(*, item_count: int, newest_at: datetime | None) -> bool:
|
||||
if item_count < MAX_ITEMS_TOTAL:
|
||||
return True
|
||||
if newest_at is None:
|
||||
return True
|
||||
age_seconds = (datetime.now(UTC) - newest_at).total_seconds()
|
||||
return age_seconds > RSS_SUPPLEMENT_MAX_AGE_SECONDS
|
||||
|
||||
|
||||
async def _get_earth_news_payload_from_rss_only(
|
||||
*,
|
||||
lat: float | None,
|
||||
lon: float | None,
|
||||
active_region: str,
|
||||
sources: list[NewsFeedSource],
|
||||
) -> dict[str, Any]:
|
||||
fetched_items, errors = await _fetch_rss_items_for_sources(sources)
|
||||
ranked_items = _rank_and_trim_items(fetched_items, active_region=active_region)
|
||||
if ranked_items:
|
||||
ranked_items = await _apply_cached_locations_and_enqueue(ranked_items)
|
||||
_store_region_cache(active_region, items=ranked_items, sources=sources)
|
||||
return _build_payload(
|
||||
lat=lat,
|
||||
@@ -518,6 +1063,7 @@ async def get_earth_news_payload(lat: float | None = None, lon: float | None = N
|
||||
|
||||
cached = _get_cached_region_feed(active_region)
|
||||
if cached:
|
||||
cached.items = await _apply_cached_locations_and_enqueue(cached.items)
|
||||
return _build_payload(
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
@@ -538,3 +1084,55 @@ async def get_earth_news_payload(lat: float | None = None, lon: float | None = N
|
||||
errors=errors,
|
||||
stale=False,
|
||||
)
|
||||
|
||||
|
||||
async def get_earth_news_payload(
|
||||
lat: float | None = None,
|
||||
lon: float | None = None,
|
||||
*,
|
||||
provider_client: AIProviderClient | None = None,
|
||||
db: AsyncSession | None = None,
|
||||
) -> dict[str, Any]:
|
||||
del provider_client
|
||||
active_region = determine_focus_region(lat, lon)
|
||||
sources = get_sources_for_region(active_region)
|
||||
|
||||
if db is None:
|
||||
return await _get_earth_news_payload_from_rss_only(
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
active_region=active_region,
|
||||
sources=sources,
|
||||
)
|
||||
|
||||
from app.services.earth_news_store import (
|
||||
get_earth_news_freshness,
|
||||
list_earth_news_items,
|
||||
upsert_earth_news_items,
|
||||
)
|
||||
|
||||
errors: list[str] = []
|
||||
item_count, newest_at = await get_earth_news_freshness(db, active_region=active_region)
|
||||
should_supplement = _needs_rss_supplement(item_count=item_count, newest_at=newest_at)
|
||||
if should_supplement:
|
||||
fetched_items, errors = await _fetch_rss_items_for_sources(sources)
|
||||
ranked_fetched_items = _rank_and_trim_items(fetched_items, active_region=active_region)
|
||||
await upsert_earth_news_items(db, ranked_fetched_items)
|
||||
|
||||
items = await list_earth_news_items(
|
||||
db,
|
||||
active_region=active_region,
|
||||
limit=MAX_ITEMS_TOTAL,
|
||||
)
|
||||
await _enqueue_unverified_locations(items)
|
||||
stale = bool(errors and items)
|
||||
|
||||
return _build_payload(
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
active_region=active_region,
|
||||
items=items,
|
||||
sources=sources,
|
||||
errors=errors,
|
||||
stale=stale,
|
||||
)
|
||||
@@ -0,0 +1,232 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from typing import Any, Protocol
|
||||
|
||||
import redis.asyncio as redis
|
||||
from redis.exceptions import ResponseError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.logging import get_logger
|
||||
|
||||
|
||||
logger = get_logger(__name__, service="earth_news")
|
||||
|
||||
TARGET_LOCATION_STREAM = "earth_news:target_location:jobs"
|
||||
TARGET_LOCATION_GROUP = "earth_news_target_location"
|
||||
TARGET_LOCATION_DEAD_LETTER_STREAM = "earth_news:target_location:dead"
|
||||
TARGET_LOCATION_RESULT_TTL_SECONDS = 60 * 60 * 12
|
||||
TARGET_LOCATION_JOB_DEDUP_TTL_SECONDS = 60 * 60 * 6
|
||||
TARGET_LOCATION_MAX_ATTEMPTS = 3
|
||||
|
||||
_redis_client: redis.Redis | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NewsTargetLocationMessage:
|
||||
message_id: str
|
||||
item_id: str
|
||||
payload: dict[str, Any]
|
||||
attempts: int = 0
|
||||
|
||||
|
||||
class NewsTargetLocationQueue(Protocol):
|
||||
async def enqueue(self, *, item_id: str, payload: dict[str, Any]) -> bool:
|
||||
...
|
||||
|
||||
async def consume_batch(
|
||||
self,
|
||||
*,
|
||||
consumer_name: str,
|
||||
count: int,
|
||||
block_ms: int,
|
||||
) -> list[NewsTargetLocationMessage]:
|
||||
...
|
||||
|
||||
async def ack(self, message_id: str) -> None:
|
||||
...
|
||||
|
||||
async def retry_or_dead_letter(
|
||||
self,
|
||||
message: NewsTargetLocationMessage,
|
||||
*,
|
||||
error: str,
|
||||
) -> None:
|
||||
...
|
||||
|
||||
|
||||
def _get_redis_client() -> redis.Redis:
|
||||
global _redis_client
|
||||
if _redis_client is None:
|
||||
_redis_client = redis.from_url(settings.REDIS_URL, decode_responses=True)
|
||||
return _redis_client
|
||||
|
||||
|
||||
def _result_key(item_id: str) -> str:
|
||||
return f"earth_news:target_location:result:{item_id}"
|
||||
|
||||
|
||||
def _queued_key(item_id: str) -> str:
|
||||
return f"earth_news:target_location:queued:{item_id}"
|
||||
|
||||
|
||||
class RedisStreamsNewsTargetLocationQueue:
|
||||
def __init__(self, client: redis.Redis | None = None) -> None:
|
||||
self.client = client or _get_redis_client()
|
||||
self._group_ready = False
|
||||
|
||||
async def _ensure_group(self) -> None:
|
||||
if self._group_ready:
|
||||
return
|
||||
try:
|
||||
await self.client.xgroup_create(
|
||||
TARGET_LOCATION_STREAM,
|
||||
TARGET_LOCATION_GROUP,
|
||||
id="0",
|
||||
mkstream=True,
|
||||
)
|
||||
except ResponseError as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
self._group_ready = True
|
||||
|
||||
async def enqueue(self, *, item_id: str, payload: dict[str, Any]) -> bool:
|
||||
await self._ensure_group()
|
||||
if await self.client.exists(_result_key(item_id)):
|
||||
return False
|
||||
queued = await self.client.set(
|
||||
_queued_key(item_id),
|
||||
"1",
|
||||
nx=True,
|
||||
ex=TARGET_LOCATION_JOB_DEDUP_TTL_SECONDS,
|
||||
)
|
||||
if not queued:
|
||||
return bool(await self.client.exists(_queued_key(item_id)))
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_STREAM,
|
||||
{
|
||||
"item_id": item_id,
|
||||
"attempts": "0",
|
||||
"payload": json.dumps(payload, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
return True
|
||||
|
||||
async def consume_batch(
|
||||
self,
|
||||
*,
|
||||
consumer_name: str,
|
||||
count: int,
|
||||
block_ms: int,
|
||||
) -> list[NewsTargetLocationMessage]:
|
||||
await self._ensure_group()
|
||||
streams = await self.client.xreadgroup(
|
||||
TARGET_LOCATION_GROUP,
|
||||
consumer_name,
|
||||
{TARGET_LOCATION_STREAM: ">"},
|
||||
count=count,
|
||||
block=block_ms,
|
||||
)
|
||||
messages: list[NewsTargetLocationMessage] = []
|
||||
for _stream_name, stream_messages in streams:
|
||||
for message_id, fields in stream_messages:
|
||||
raw_payload = fields.get("payload")
|
||||
item_id = fields.get("item_id")
|
||||
if not raw_payload or not item_id:
|
||||
await self.ack(message_id)
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(raw_payload)
|
||||
except json.JSONDecodeError:
|
||||
await self.ack(message_id)
|
||||
continue
|
||||
attempts = int(fields.get("attempts") or 0)
|
||||
messages.append(
|
||||
NewsTargetLocationMessage(
|
||||
message_id=message_id,
|
||||
item_id=item_id,
|
||||
payload=payload,
|
||||
attempts=attempts,
|
||||
)
|
||||
)
|
||||
return messages
|
||||
|
||||
async def ack(self, message_id: str) -> None:
|
||||
await self.client.xack(TARGET_LOCATION_STREAM, TARGET_LOCATION_GROUP, message_id)
|
||||
|
||||
async def retry_or_dead_letter(
|
||||
self,
|
||||
message: NewsTargetLocationMessage,
|
||||
*,
|
||||
error: str,
|
||||
) -> None:
|
||||
await self.ack(message.message_id)
|
||||
if message.attempts + 1 >= TARGET_LOCATION_MAX_ATTEMPTS:
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_DEAD_LETTER_STREAM,
|
||||
{
|
||||
"item_id": message.item_id,
|
||||
"attempts": str(message.attempts + 1),
|
||||
"error": error,
|
||||
"payload": json.dumps(message.payload, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
return
|
||||
await self.client.xadd(
|
||||
TARGET_LOCATION_STREAM,
|
||||
{
|
||||
"item_id": message.item_id,
|
||||
"attempts": str(message.attempts + 1),
|
||||
"payload": json.dumps(message.payload, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_news_target_location_queue() -> NewsTargetLocationQueue:
|
||||
return RedisStreamsNewsTargetLocationQueue()
|
||||
|
||||
|
||||
async def enqueue_target_location_job(payload: dict[str, Any]) -> bool:
|
||||
item_id = str(payload.get("id") or "")
|
||||
if not item_id:
|
||||
return False
|
||||
try:
|
||||
queue = get_news_target_location_queue()
|
||||
return await queue.enqueue(item_id=item_id, payload=payload)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to enqueue Earth news target location job",
|
||||
event="earth_news.target_location.enqueue_failed",
|
||||
context={"item_id": item_id, "error": str(exc)},
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
async def get_cached_target_location_patch(item_id: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
raw_value = await _get_redis_client().get(_result_key(item_id))
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to read Earth news target location cache",
|
||||
event="earth_news.target_location.cache_read_failed",
|
||||
context={"item_id": item_id, "error": str(exc)},
|
||||
)
|
||||
return None
|
||||
if not raw_value:
|
||||
return None
|
||||
try:
|
||||
value = json.loads(raw_value)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return value if isinstance(value, dict) else None
|
||||
|
||||
|
||||
async def save_target_location_patch(item_id: str, patch: dict[str, Any]) -> None:
|
||||
client = _get_redis_client()
|
||||
await client.setex(
|
||||
_result_key(item_id),
|
||||
TARGET_LOCATION_RESULT_TTL_SECONDS,
|
||||
json.dumps(patch, ensure_ascii=False),
|
||||
)
|
||||
await client.delete(_queued_key(item_id))
|
||||
@@ -0,0 +1,188 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.earth_news import EarthNewsItem
|
||||
from app.services.earth_news import (
|
||||
ParsedNewsItem,
|
||||
build_anchor_location_patch,
|
||||
)
|
||||
|
||||
|
||||
def _coerce_datetime(value: datetime | None) -> datetime | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=UTC)
|
||||
return value.astimezone(UTC)
|
||||
|
||||
|
||||
def _location_patch_from_record(record: EarthNewsItem) -> dict[str, Any]:
|
||||
return {
|
||||
"latitude": record.latitude,
|
||||
"longitude": record.longitude,
|
||||
"location_label": record.location_label,
|
||||
"location_source": record.location_source,
|
||||
"verified": record.verified,
|
||||
"location_meta": dict(record.location_meta or {}),
|
||||
}
|
||||
|
||||
|
||||
def record_to_parsed_news_item(record: EarthNewsItem) -> ParsedNewsItem:
|
||||
return ParsedNewsItem(
|
||||
id=record.id,
|
||||
title=record.title,
|
||||
summary=record.summary or "",
|
||||
url=record.url,
|
||||
source=record.source or "",
|
||||
feed_name=record.feed_name or "",
|
||||
feed_region=record.region or "global",
|
||||
homepage_url=record.homepage_url or "",
|
||||
published_at=_coerce_datetime(record.published_at),
|
||||
location_patch=_location_patch_from_record(record),
|
||||
)
|
||||
|
||||
|
||||
def _query_sort_key(active_region: str):
|
||||
return (
|
||||
EarthNewsItem.region != active_region,
|
||||
EarthNewsItem.published_at.is_(None),
|
||||
EarthNewsItem.published_at.desc().nullslast(),
|
||||
EarthNewsItem.feed_name.asc(),
|
||||
)
|
||||
|
||||
|
||||
async def list_earth_news_items(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
active_region: str,
|
||||
limit: int,
|
||||
) -> list[ParsedNewsItem]:
|
||||
regions = {"global", active_region}
|
||||
result = await db.execute(
|
||||
select(EarthNewsItem)
|
||||
.where(EarthNewsItem.region.in_(regions))
|
||||
.order_by(*_query_sort_key(active_region))
|
||||
.limit(limit)
|
||||
)
|
||||
return [record_to_parsed_news_item(record) for record in result.scalars().all()]
|
||||
|
||||
|
||||
async def get_earth_news_freshness(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
active_region: str,
|
||||
) -> tuple[int, datetime | None]:
|
||||
regions = {"global", active_region}
|
||||
result = await db.execute(
|
||||
select(
|
||||
func.count(EarthNewsItem.id),
|
||||
func.max(func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)),
|
||||
).where(EarthNewsItem.region.in_(regions))
|
||||
)
|
||||
count, newest = result.one()
|
||||
item_count = int(count or 0)
|
||||
if item_count == 0:
|
||||
return 0, None
|
||||
return item_count, _coerce_datetime(newest)
|
||||
|
||||
|
||||
async def upsert_earth_news_items(db: AsyncSession, items: list[ParsedNewsItem]) -> int:
|
||||
if not items:
|
||||
return 0
|
||||
now = datetime.now(UTC)
|
||||
existing_result = await db.execute(
|
||||
select(EarthNewsItem).where(EarthNewsItem.id.in_([item.id for item in items]))
|
||||
)
|
||||
existing = {record.id: record for record in existing_result.scalars().all()}
|
||||
changed = 0
|
||||
for item in items:
|
||||
record = existing.get(item.id)
|
||||
if record is None:
|
||||
patch = build_anchor_location_patch(item)
|
||||
record = EarthNewsItem(
|
||||
id=item.id,
|
||||
title=item.title,
|
||||
summary=item.summary,
|
||||
url=item.url,
|
||||
source=item.source,
|
||||
feed_name=item.feed_name,
|
||||
region=item.feed_region,
|
||||
homepage_url=item.homepage_url,
|
||||
published_at=item.published_at,
|
||||
latitude=patch["latitude"],
|
||||
longitude=patch["longitude"],
|
||||
location_label=patch["location_label"],
|
||||
location_source=patch["location_source"],
|
||||
verified=patch["verified"],
|
||||
location_meta=patch["location_meta"],
|
||||
first_seen_at=now,
|
||||
last_seen_at=now,
|
||||
)
|
||||
db.add(record)
|
||||
changed += 1
|
||||
continue
|
||||
|
||||
record.title = item.title
|
||||
record.summary = item.summary
|
||||
record.url = item.url
|
||||
record.source = item.source
|
||||
record.feed_name = item.feed_name
|
||||
record.region = item.feed_region
|
||||
record.homepage_url = item.homepage_url
|
||||
record.published_at = item.published_at
|
||||
record.last_seen_at = now
|
||||
changed += 1
|
||||
await db.flush()
|
||||
return changed
|
||||
|
||||
|
||||
async def update_earth_news_item_location(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
item_id: str,
|
||||
patch: dict[str, Any],
|
||||
) -> bool:
|
||||
record = await db.get(EarthNewsItem, item_id)
|
||||
if record is None:
|
||||
return False
|
||||
record.latitude = float(patch["latitude"])
|
||||
record.longitude = float(patch["longitude"])
|
||||
record.location_label = str(patch["location_label"])
|
||||
record.location_source = str(patch["location_source"])
|
||||
record.verified = bool(patch["verified"])
|
||||
record.location_meta = dict(patch.get("location_meta") or {})
|
||||
record.resolved_at = datetime.now(UTC) if record.verified else None
|
||||
await db.flush()
|
||||
return True
|
||||
|
||||
|
||||
async def list_unverified_earth_news_items(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
active_region: str,
|
||||
limit: int,
|
||||
) -> list[ParsedNewsItem]:
|
||||
regions = {"global", active_region}
|
||||
result = await db.execute(
|
||||
select(EarthNewsItem)
|
||||
.where(EarthNewsItem.region.in_(regions))
|
||||
.where(EarthNewsItem.verified.is_(False))
|
||||
.order_by(*_query_sort_key(active_region))
|
||||
.limit(limit)
|
||||
)
|
||||
return [record_to_parsed_news_item(record) for record in result.scalars().all()]
|
||||
|
||||
|
||||
async def list_all_earth_news_records(db: AsyncSession) -> list[EarthNewsItem]:
|
||||
result = await db.execute(
|
||||
select(EarthNewsItem).order_by(
|
||||
EarthNewsItem.published_at.desc().nullslast(),
|
||||
EarthNewsItem.last_seen_at.desc(),
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
@@ -0,0 +1,133 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import suppress
|
||||
from socket import gethostname
|
||||
from typing import Any
|
||||
|
||||
from app.core.logging import get_logger
|
||||
from app.core.websocket.broadcaster import broadcaster
|
||||
from app.db.session import async_session_factory
|
||||
from app.services.ai_client import AIProviderClient
|
||||
from app.services.earth_news import (
|
||||
_infer_news_target_location,
|
||||
build_target_location_patch,
|
||||
parsed_news_item_from_job_payload,
|
||||
)
|
||||
from app.services.earth_news_queue import (
|
||||
NewsTargetLocationMessage,
|
||||
get_news_target_location_queue,
|
||||
save_target_location_patch,
|
||||
)
|
||||
from app.services.earth_news_store import update_earth_news_item_location
|
||||
|
||||
|
||||
logger = get_logger(__name__, service="earth_news")
|
||||
|
||||
WORKER_BATCH_SIZE = 4
|
||||
WORKER_BLOCK_MS = 5000
|
||||
WORKER_BACKOFF_SECONDS = 5.0
|
||||
|
||||
_worker_task: asyncio.Task | None = None
|
||||
|
||||
|
||||
async def _build_provider_client() -> AIProviderClient | None:
|
||||
try:
|
||||
from app.api.v1.settings import get_runtime_ai_provider_config
|
||||
|
||||
async with async_session_factory() as session:
|
||||
runtime_config = await get_runtime_ai_provider_config(session)
|
||||
return AIProviderClient(
|
||||
service_url=runtime_config["service_url"],
|
||||
service_token=runtime_config["service_token"],
|
||||
timeout=runtime_config["timeout_seconds"],
|
||||
retry_attempts=runtime_config["retry_attempts"],
|
||||
llm_config=runtime_config.get("llm_config") or {},
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Failed to build Earth news AI provider client",
|
||||
event="earth_news.target_location.provider_unavailable",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def process_target_location_message(
|
||||
message: NewsTargetLocationMessage,
|
||||
*,
|
||||
provider_client: AIProviderClient | None,
|
||||
) -> dict[str, Any]:
|
||||
item = parsed_news_item_from_job_payload(message.payload)
|
||||
target = await _infer_news_target_location(item, provider_client=provider_client)
|
||||
item.target_location = target
|
||||
patch = build_target_location_patch(item, target)
|
||||
await save_target_location_patch(item.id, patch)
|
||||
async with async_session_factory() as session:
|
||||
await update_earth_news_item_location(session, item_id=item.id, patch=patch)
|
||||
await session.commit()
|
||||
await broadcaster.broadcast_custom(
|
||||
"earth_news",
|
||||
{
|
||||
"item_id": item.id,
|
||||
"patch": patch,
|
||||
},
|
||||
)
|
||||
return patch
|
||||
|
||||
|
||||
async def _run_target_location_worker() -> None:
|
||||
consumer_name = f"{gethostname()}:{id(asyncio.current_task())}"
|
||||
queue = get_news_target_location_queue()
|
||||
while True:
|
||||
try:
|
||||
messages = await queue.consume_batch(
|
||||
consumer_name=consumer_name,
|
||||
count=WORKER_BATCH_SIZE,
|
||||
block_ms=WORKER_BLOCK_MS,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Earth news target location worker queue read failed",
|
||||
event="earth_news.target_location.worker_read_failed",
|
||||
context={"error": str(exc)},
|
||||
)
|
||||
await asyncio.sleep(WORKER_BACKOFF_SECONDS)
|
||||
continue
|
||||
|
||||
if not messages:
|
||||
continue
|
||||
provider_client = await _build_provider_client()
|
||||
for message in messages:
|
||||
try:
|
||||
await process_target_location_message(message, provider_client=provider_client)
|
||||
await queue.ack(message.message_id)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.warning_event(
|
||||
"Earth news target location worker job failed",
|
||||
event="earth_news.target_location.worker_job_failed",
|
||||
context={"item_id": message.item_id, "error": str(exc)},
|
||||
)
|
||||
with suppress(Exception):
|
||||
await queue.retry_or_dead_letter(message, error=str(exc))
|
||||
|
||||
|
||||
def start_earth_news_target_worker() -> None:
|
||||
global _worker_task
|
||||
if _worker_task is None or _worker_task.done():
|
||||
_worker_task = asyncio.create_task(_run_target_location_worker())
|
||||
|
||||
|
||||
async def stop_earth_news_target_worker() -> None:
|
||||
global _worker_task
|
||||
task = _worker_task
|
||||
if task is None:
|
||||
return
|
||||
task.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await task
|
||||
_worker_task = None
|
||||
@@ -175,19 +175,29 @@ async def run_collector_task(collector_name: str):
|
||||
)
|
||||
|
||||
try:
|
||||
collector._datasource_id = datasource.id
|
||||
datasource_id = datasource.id
|
||||
datasource_source = datasource.source
|
||||
collector._datasource_id = datasource_id
|
||||
logger.info_event(
|
||||
"Running collector",
|
||||
event="collector.run.started",
|
||||
context={"collector_name": collector_name, "datasource_id": datasource.id},
|
||||
context={"collector_name": collector_name, "datasource_id": datasource_id},
|
||||
)
|
||||
task_result = await collector.run(db)
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
if datasource is None:
|
||||
logger.error_event(
|
||||
"Datasource disappeared after collector run",
|
||||
event="collector.run.datasource_missing_after_run",
|
||||
context={"collector_name": collector_name, "datasource_id": datasource_id},
|
||||
)
|
||||
return
|
||||
datasource.last_run_at = datetime.now(UTC)
|
||||
datasource.last_status = task_result.get("status")
|
||||
if datasource.last_status == "success":
|
||||
effective_candidate = await get_builtin_effective_candidate(db, datasource.source)
|
||||
effective_candidate = await get_builtin_effective_candidate(db, datasource_source)
|
||||
checksum, _credential_context = await build_builtin_connectivity_checksum(
|
||||
datasource.source,
|
||||
datasource_source,
|
||||
effective_candidate["endpoint"],
|
||||
effective_candidate["auth_type"],
|
||||
effective_candidate["headers"],
|
||||
@@ -196,7 +206,7 @@ async def run_collector_task(collector_name: str):
|
||||
)
|
||||
await save_connectivity_success(
|
||||
db,
|
||||
datasource.source,
|
||||
datasource_source,
|
||||
checksum,
|
||||
{"status_code": None},
|
||||
connected_by="collection",
|
||||
@@ -205,9 +215,11 @@ async def run_collector_task(collector_name: str):
|
||||
logger.info_event(
|
||||
"Collector completed",
|
||||
event="collector.run.completed",
|
||||
context={"collector_name": collector_name, "datasource_id": datasource.id, "result": task_result},
|
||||
context={"collector_name": collector_name, "datasource_id": datasource_id, "result": task_result},
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
await db.rollback()
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
datasource.last_run_at = datetime.now(UTC)
|
||||
datasource.last_status = "cancelled"
|
||||
await db.commit()
|
||||
@@ -218,6 +230,8 @@ async def run_collector_task(collector_name: str):
|
||||
)
|
||||
raise
|
||||
except Exception as exc:
|
||||
await db.rollback()
|
||||
datasource = await db.get(DataSource, datasource_id)
|
||||
datasource.last_run_at = datetime.now(UTC)
|
||||
datasource.last_status = "failed"
|
||||
await db.commit()
|
||||
|
||||
@@ -1,6 +1,20 @@
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.earth_news import ParsedNewsItem, _serialize_item
|
||||
import pytest
|
||||
|
||||
from app.services.earth_news import (
|
||||
NewsFeedSource,
|
||||
NewsTargetLocation,
|
||||
ParsedNewsItem,
|
||||
_enrich_items_with_target_locations,
|
||||
_extract_target_location_from_text,
|
||||
_serialize_item,
|
||||
get_earth_news_payload,
|
||||
)
|
||||
from app.services.earth_news_queue import NewsTargetLocationMessage
|
||||
from app.services.earth_news_worker import process_target_location_message
|
||||
from app.services.collectors.media_news_archive import MediaNewsArchiveCollector
|
||||
|
||||
|
||||
def test_serialize_item_includes_region_anchor_for_cruise():
|
||||
@@ -21,7 +35,10 @@ def test_serialize_item_includes_region_anchor_for_cruise():
|
||||
assert payload["latitude"] == 1.3521
|
||||
assert payload["longitude"] == 103.8198
|
||||
assert payload["location_label"] == "亚太"
|
||||
assert payload["location_inferred"] is True
|
||||
assert payload["location_source"] == "region_anchor"
|
||||
assert payload["verified"] is False
|
||||
assert payload["location_meta"]["target"] is None
|
||||
assert payload["location_meta"]["anchor"]["region"] == "asia-pacific"
|
||||
assert payload["is_focus_match"] is True
|
||||
assert payload["published_at"] == "2026-04-23T02:30:00Z"
|
||||
|
||||
@@ -44,6 +61,561 @@ def test_serialize_item_falls_back_to_global_anchor():
|
||||
assert payload["latitude"] == 20.0
|
||||
assert payload["longitude"] == 0.0
|
||||
assert payload["location_label"] == "全球"
|
||||
assert payload["location_inferred"] is True
|
||||
assert payload["location_source"] == "region_anchor"
|
||||
assert payload["verified"] is False
|
||||
assert payload["location_meta"]["anchor"]["region"] == "global"
|
||||
assert payload["is_focus_match"] is False
|
||||
assert payload["published_at"] is None
|
||||
|
||||
|
||||
def test_serialize_item_includes_inferred_target_location():
|
||||
item = ParsedNewsItem(
|
||||
id="bbc-world:f55310fb667b",
|
||||
title="Watch: What happened on day one of Trump's China visit?",
|
||||
summary=(
|
||||
"China welcomed US President Donald Trump with cheering children "
|
||||
"and a troop parade."
|
||||
),
|
||||
url="https://example.com/china-visit",
|
||||
source="BBC World",
|
||||
feed_name="BBC World",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 14, 7, 13, 24, tzinfo=UTC),
|
||||
target_location=NewsTargetLocation(
|
||||
latitude=39.9042,
|
||||
longitude=116.4074,
|
||||
label="Beijing, China",
|
||||
source="ai_inferred_target",
|
||||
confidence=0.88,
|
||||
country="中国",
|
||||
city="Beijing",
|
||||
),
|
||||
)
|
||||
|
||||
payload = _serialize_item(item, active_region="global")
|
||||
|
||||
assert payload["latitude"] == 39.9042
|
||||
assert payload["longitude"] == 116.4074
|
||||
assert payload["location_label"] == "Beijing, China"
|
||||
assert payload["location_source"] == "ai_inferred_target"
|
||||
assert payload["verified"] is True
|
||||
assert payload["location_meta"]["target"]["confidence"] == 0.88
|
||||
assert payload["location_meta"]["target"]["country"] == "中国"
|
||||
assert payload["location_meta"]["target"]["city"] == "Beijing"
|
||||
assert payload["location_meta"]["resolution_stage"] == "unresolved"
|
||||
assert payload["location_meta"]["ai_attempted"] is False
|
||||
assert payload["location_meta"]["ai_status"] == "not_attempted"
|
||||
assert payload["location_meta"]["ai_error"] is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enrich_items_with_target_locations_uses_ai_and_geocode(monkeypatch):
|
||||
item = ParsedNewsItem(
|
||||
id="bbc-world:f55310fb667b",
|
||||
title="Watch: What happened on day one of Trump's China visit?",
|
||||
summary="China welcomed US President Donald Trump before a long meeting with Xi Jinping.",
|
||||
url="https://example.com/china-visit",
|
||||
source="BBC World",
|
||||
feed_name="BBC World",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 14, 7, 13, 24, tzinfo=UTC),
|
||||
)
|
||||
|
||||
async def fake_geocode(_query: str):
|
||||
return {
|
||||
"lat": "39.9042",
|
||||
"lon": "116.4074",
|
||||
"display_name": "Beijing, China",
|
||||
}
|
||||
|
||||
class FakeProviderClient:
|
||||
async def analyze(self, _request):
|
||||
class Response:
|
||||
content = (
|
||||
'{"country":"China","city":"Beijing","matched_location_name":"Beijing, China",'
|
||||
'"latitude":null,"longitude":null,"confidence":0.88}'
|
||||
)
|
||||
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news._geocode_target_location", fake_geocode)
|
||||
|
||||
enriched = await _enrich_items_with_target_locations(
|
||||
[item],
|
||||
provider_client=FakeProviderClient(),
|
||||
)
|
||||
|
||||
assert len(enriched) == 1
|
||||
assert enriched[0].target_location is not None
|
||||
assert enriched[0].target_location.latitude == 39.9042
|
||||
assert enriched[0].target_location.longitude == 116.4074
|
||||
assert enriched[0].target_location.label == "Beijing, China"
|
||||
assert enriched[0].target_resolution_stage == "ai_inferred_target"
|
||||
assert enriched[0].target_ai_attempted is True
|
||||
assert enriched[0].target_ai_status == "success"
|
||||
assert enriched[0].target_ai_error is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_extract_target_location_from_text_uses_country_hint(monkeypatch):
|
||||
item = ParsedNewsItem(
|
||||
id="bbc-world:country-hint",
|
||||
title="Giant new dinosaur identified from fossils in Thailand",
|
||||
summary="The nagatitan is the largest dinosaur found in South-East Asia.",
|
||||
url="https://example.com/thailand-dinosaur",
|
||||
source="BBC World",
|
||||
feed_name="BBC World",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 14, 17, 28, 56, tzinfo=UTC),
|
||||
)
|
||||
|
||||
target = await _extract_target_location_from_text(item)
|
||||
|
||||
assert target is not None
|
||||
assert target.country == "泰国"
|
||||
assert target.latitude == 15.87
|
||||
assert target.longitude == 100.9925
|
||||
assert target.source == "headline_country_hint"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enrich_items_with_target_locations_records_ai_provider_error():
|
||||
item = ParsedNewsItem(
|
||||
id="global-scan:no-hint",
|
||||
title="The New Geopolitics of Power: Whoever Controls Electrons Wins the Decade",
|
||||
summary="A broad analysis of industrial policy and energy systems.",
|
||||
url="https://example.com/geopolitics-power",
|
||||
source="Example Source",
|
||||
feed_name="Global Monitor / World",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 14, 17, 3, 10, tzinfo=UTC),
|
||||
)
|
||||
|
||||
class FailingProviderClient:
|
||||
async def analyze(self, _request):
|
||||
raise RuntimeError("upstream ai timeout")
|
||||
|
||||
enriched = await _enrich_items_with_target_locations(
|
||||
[item],
|
||||
provider_client=FailingProviderClient(),
|
||||
)
|
||||
|
||||
assert len(enriched) == 1
|
||||
assert enriched[0].target_location is None
|
||||
assert enriched[0].target_resolution_stage == "unresolved"
|
||||
assert enriched[0].target_ai_attempted is True
|
||||
assert enriched[0].target_ai_status == "provider_error"
|
||||
assert enriched[0].target_ai_error == "upstream ai timeout"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_news_payload_returns_anchor_items_and_enqueues_location_job(monkeypatch):
|
||||
source = NewsFeedSource(
|
||||
id="test-feed",
|
||||
name="Test Feed",
|
||||
region="global",
|
||||
homepage_url="https://example.com",
|
||||
feed_url="https://example.com/rss.xml",
|
||||
)
|
||||
item = ParsedNewsItem(
|
||||
id="test-feed:timeout",
|
||||
title="Example story",
|
||||
summary="Example summary",
|
||||
url="https://example.com/story",
|
||||
source="Test Feed",
|
||||
feed_name="Test Feed",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
)
|
||||
|
||||
async def fake_fetch_source(_client, feed_source):
|
||||
return feed_source, [item], None
|
||||
|
||||
async def fake_get_cached_target_location_patch(_item_id):
|
||||
return None
|
||||
|
||||
enqueued_payloads = []
|
||||
|
||||
async def fake_enqueue_target_location_job(payload):
|
||||
enqueued_payloads.append(payload)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news.get_sources_for_region", lambda _region: [source])
|
||||
monkeypatch.setattr("app.services.earth_news._fetch_source", fake_fetch_source)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_queue.get_cached_target_location_patch",
|
||||
fake_get_cached_target_location_patch,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_queue.enqueue_target_location_job",
|
||||
fake_enqueue_target_location_job,
|
||||
)
|
||||
|
||||
payload = await get_earth_news_payload(provider_client=None)
|
||||
|
||||
assert len(payload["items"]) == 1
|
||||
assert payload["items"][0]["id"] == "test-feed:timeout"
|
||||
assert payload["items"][0]["latitude"] == 20.0
|
||||
assert payload["items"][0]["longitude"] == 0.0
|
||||
assert payload["items"][0]["location_source"] == "region_anchor"
|
||||
assert payload["items"][0]["verified"] is False
|
||||
assert payload["items"][0]["location_meta"]["ai_status"] == "queued"
|
||||
assert enqueued_payloads[0]["id"] == "test-feed:timeout"
|
||||
assert payload["errors"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_news_payload_uses_fresh_database_items_without_rss(monkeypatch):
|
||||
db = object()
|
||||
item = ParsedNewsItem(
|
||||
id="db:fresh",
|
||||
title="Fresh database story",
|
||||
summary="Stored summary",
|
||||
url="https://example.com/fresh",
|
||||
source="Stored Source",
|
||||
feed_name="Stored Feed",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
)
|
||||
item.location_patch = {
|
||||
"latitude": 39.9057136,
|
||||
"longitude": 116.3912972,
|
||||
"location_label": "北京市, 中国",
|
||||
"location_source": "headline_location_hint",
|
||||
"verified": True,
|
||||
"location_meta": {"target": {"city": "Beijing"}, "anchor": {"region": "global"}},
|
||||
}
|
||||
|
||||
async def fake_get_earth_news_freshness(_db, *, active_region):
|
||||
return 12, datetime.now(UTC)
|
||||
|
||||
async def fake_list_earth_news_items(_db, *, active_region, limit):
|
||||
assert limit == 12
|
||||
return [item]
|
||||
|
||||
async def fail_fetch(_sources):
|
||||
raise AssertionError("fresh database items should not fetch RSS")
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news_store.get_earth_news_freshness", fake_get_earth_news_freshness)
|
||||
monkeypatch.setattr("app.services.earth_news_store.list_earth_news_items", fake_list_earth_news_items)
|
||||
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fail_fetch)
|
||||
|
||||
payload = await get_earth_news_payload(db=db)
|
||||
|
||||
assert payload["items"][0]["id"] == "db:fresh"
|
||||
assert payload["items"][0]["verified"] is True
|
||||
assert payload["items"][0]["latitude"] == 39.9057136
|
||||
assert payload["stale"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_news_payload_initializes_empty_database_from_rss(monkeypatch):
|
||||
db = object()
|
||||
source = NewsFeedSource(
|
||||
id="test-feed",
|
||||
name="Test Feed",
|
||||
region="global",
|
||||
homepage_url="https://example.com",
|
||||
feed_url="https://example.com/rss.xml",
|
||||
)
|
||||
item = ParsedNewsItem(
|
||||
id="test-feed:init",
|
||||
title="Initial RSS story",
|
||||
summary="Initial summary",
|
||||
url="https://example.com/init",
|
||||
source="Test Feed",
|
||||
feed_name="Test Feed",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
)
|
||||
item.location_patch = {
|
||||
"latitude": 20.0,
|
||||
"longitude": 0.0,
|
||||
"location_label": "全球",
|
||||
"location_source": "region_anchor",
|
||||
"verified": False,
|
||||
"location_meta": {"target": None, "anchor": {"region": "global"}},
|
||||
}
|
||||
upserted = []
|
||||
enqueued = []
|
||||
|
||||
async def fake_get_earth_news_freshness(_db, *, active_region):
|
||||
return 0, None
|
||||
|
||||
async def fake_fetch_rss_items_for_sources(_sources):
|
||||
return [item], []
|
||||
|
||||
async def fake_upsert_earth_news_items(_db, items):
|
||||
upserted.extend(items)
|
||||
return len(items)
|
||||
|
||||
async def fake_list_earth_news_items(_db, *, active_region, limit):
|
||||
return [item]
|
||||
|
||||
async def fake_enqueue_target_location_job(payload):
|
||||
enqueued.append(payload)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news.get_sources_for_region", lambda _region: [source])
|
||||
monkeypatch.setattr("app.services.earth_news_store.get_earth_news_freshness", fake_get_earth_news_freshness)
|
||||
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch_rss_items_for_sources)
|
||||
monkeypatch.setattr("app.services.earth_news_store.upsert_earth_news_items", fake_upsert_earth_news_items)
|
||||
monkeypatch.setattr("app.services.earth_news_store.list_earth_news_items", fake_list_earth_news_items)
|
||||
monkeypatch.setattr("app.services.earth_news_queue.enqueue_target_location_job", fake_enqueue_target_location_job)
|
||||
|
||||
payload = await get_earth_news_payload(db=db)
|
||||
|
||||
assert upserted[0].id == "test-feed:init"
|
||||
assert payload["items"][0]["id"] == "test-feed:init"
|
||||
assert payload["items"][0]["verified"] is False
|
||||
assert enqueued[0]["id"] == "test-feed:init"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_news_payload_supplements_stale_database_items(monkeypatch):
|
||||
db = object()
|
||||
old_item = ParsedNewsItem(
|
||||
id="db:old",
|
||||
title="Old story",
|
||||
summary="Old summary",
|
||||
url="https://example.com/old",
|
||||
source="Stored Source",
|
||||
feed_name="Stored Feed",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 14, 3, 0, tzinfo=UTC),
|
||||
)
|
||||
old_item.location_patch = {
|
||||
"latitude": 20.0,
|
||||
"longitude": 0.0,
|
||||
"location_label": "全球",
|
||||
"location_source": "region_anchor",
|
||||
"verified": False,
|
||||
"location_meta": {"target": None, "anchor": {"region": "global"}},
|
||||
}
|
||||
fetched = []
|
||||
|
||||
async def fake_get_earth_news_freshness(_db, *, active_region):
|
||||
return 12, datetime(2026, 5, 14, 3, 0, tzinfo=UTC)
|
||||
|
||||
async def fake_fetch_rss_items_for_sources(_sources):
|
||||
fetched.append(True)
|
||||
return [old_item], []
|
||||
|
||||
async def fake_upsert_earth_news_items(_db, items):
|
||||
return len(items)
|
||||
|
||||
async def fake_list_earth_news_items(_db, *, active_region, limit):
|
||||
return [old_item]
|
||||
|
||||
async def fake_enqueue_target_location_job(_payload):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news_store.get_earth_news_freshness", fake_get_earth_news_freshness)
|
||||
monkeypatch.setattr("app.services.earth_news._fetch_rss_items_for_sources", fake_fetch_rss_items_for_sources)
|
||||
monkeypatch.setattr("app.services.earth_news_store.upsert_earth_news_items", fake_upsert_earth_news_items)
|
||||
monkeypatch.setattr("app.services.earth_news_store.list_earth_news_items", fake_list_earth_news_items)
|
||||
monkeypatch.setattr("app.services.earth_news_queue.enqueue_target_location_job", fake_enqueue_target_location_job)
|
||||
|
||||
payload = await get_earth_news_payload(db=db)
|
||||
|
||||
assert fetched == [True]
|
||||
assert payload["items"][0]["id"] == "db:old"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_earth_news_payload_merges_cached_location_patch(monkeypatch):
|
||||
source = NewsFeedSource(
|
||||
id="test-feed",
|
||||
name="Test Feed",
|
||||
region="global",
|
||||
homepage_url="https://example.com",
|
||||
feed_url="https://example.com/rss.xml",
|
||||
)
|
||||
item = ParsedNewsItem(
|
||||
id="test-feed:cached",
|
||||
title="Cached story",
|
||||
summary="Cached summary",
|
||||
url="https://example.com/cached",
|
||||
source="Test Feed",
|
||||
feed_name="Test Feed",
|
||||
feed_region="global",
|
||||
homepage_url="https://example.com",
|
||||
published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
)
|
||||
cached_patch = {
|
||||
"latitude": 39.9057136,
|
||||
"longitude": 116.3912972,
|
||||
"location_label": "北京市, 中国",
|
||||
"location_source": "headline_location_hint",
|
||||
"verified": True,
|
||||
"location_meta": {
|
||||
"resolution_stage": "headline_location_hint",
|
||||
"ai_attempted": False,
|
||||
"ai_status": "skipped_text_hint",
|
||||
"ai_error": None,
|
||||
"debug_note": "text hint matched 北京市, 中国",
|
||||
"target": {"city": "Beijing"},
|
||||
"anchor": {"region": "global"},
|
||||
},
|
||||
}
|
||||
|
||||
async def fake_fetch_source(_client, feed_source):
|
||||
return feed_source, [item], None
|
||||
|
||||
async def fake_get_cached_target_location_patch(_item_id):
|
||||
return cached_patch
|
||||
|
||||
async def fake_enqueue_target_location_job(_payload):
|
||||
raise AssertionError("cached items should not be enqueued")
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news.get_sources_for_region", lambda _region: [source])
|
||||
monkeypatch.setattr("app.services.earth_news._fetch_source", fake_fetch_source)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_queue.get_cached_target_location_patch",
|
||||
fake_get_cached_target_location_patch,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_queue.enqueue_target_location_job",
|
||||
fake_enqueue_target_location_job,
|
||||
)
|
||||
|
||||
payload = await get_earth_news_payload(provider_client=None)
|
||||
|
||||
assert payload["items"][0]["latitude"] == 39.9057136
|
||||
assert payload["items"][0]["longitude"] == 116.3912972
|
||||
assert payload["items"][0]["verified"] is True
|
||||
assert payload["items"][0]["location_source"] == "headline_location_hint"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_worker_processes_target_location_message_and_returns_patch(monkeypatch):
|
||||
message = NewsTargetLocationMessage(
|
||||
message_id="1-0",
|
||||
item_id="bbc-world:worker",
|
||||
payload={
|
||||
"id": "bbc-world:worker",
|
||||
"title": "Ukraine rescuers pull dead from rubble of Kyiv flats",
|
||||
"summary": "Massive Russian drone and missile attacks in Ukraine's capital.",
|
||||
"url": "https://example.com/kyiv",
|
||||
"source": "BBC World",
|
||||
"feed_name": "BBC World",
|
||||
"feed_region": "global",
|
||||
"homepage_url": "https://www.bbc.com/news/world",
|
||||
"published_at": "2026-05-14T13:16:32Z",
|
||||
},
|
||||
)
|
||||
|
||||
async def fake_geocode(_query: str):
|
||||
return {
|
||||
"lat": "50.4500336",
|
||||
"lon": "30.5241361",
|
||||
"display_name": "Київ, Україна",
|
||||
}
|
||||
|
||||
saved = {}
|
||||
broadcasted = {}
|
||||
|
||||
async def fake_save_target_location_patch(item_id, patch):
|
||||
saved["item_id"] = item_id
|
||||
saved["patch"] = patch
|
||||
|
||||
async def fake_update_earth_news_item_location(_session, *, item_id, patch):
|
||||
saved["db_item_id"] = item_id
|
||||
saved["db_patch"] = patch
|
||||
return True
|
||||
|
||||
async def fake_broadcast_custom(channel, data):
|
||||
broadcasted["channel"] = channel
|
||||
broadcasted["data"] = data
|
||||
|
||||
class FakeSession:
|
||||
async def commit(self):
|
||||
saved["committed"] = True
|
||||
|
||||
class FakeSessionFactory:
|
||||
async def __aenter__(self):
|
||||
return FakeSession()
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("app.services.earth_news._geocode_target_location", fake_geocode)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_worker.save_target_location_patch",
|
||||
fake_save_target_location_patch,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_worker.update_earth_news_item_location",
|
||||
fake_update_earth_news_item_location,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_worker.async_session_factory",
|
||||
lambda: FakeSessionFactory(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.earth_news_worker.broadcaster.broadcast_custom",
|
||||
fake_broadcast_custom,
|
||||
)
|
||||
|
||||
patch = await process_target_location_message(message, provider_client=None)
|
||||
|
||||
assert patch["latitude"] == 50.4500336
|
||||
assert patch["longitude"] == 30.5241361
|
||||
assert patch["location_source"] == "headline_location_hint"
|
||||
assert patch["verified"] is True
|
||||
assert saved["item_id"] == "bbc-world:worker"
|
||||
assert saved["db_item_id"] == "bbc-world:worker"
|
||||
assert saved["committed"] is True
|
||||
assert broadcasted["channel"] == "earth_news"
|
||||
assert broadcasted["data"]["item_id"] == "bbc-world:worker"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_media_news_archive_collector_maps_news_items(monkeypatch):
|
||||
collector = MediaNewsArchiveCollector()
|
||||
collector._db_session = object()
|
||||
record = SimpleNamespace(
|
||||
id="bbc-world:archive",
|
||||
title="Archived news",
|
||||
summary="Archived summary",
|
||||
url="https://example.com/archive",
|
||||
source="BBC World",
|
||||
feed_name="BBC World",
|
||||
region="global",
|
||||
homepage_url="https://www.bbc.com/news/world",
|
||||
published_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
latitude=39.9057136,
|
||||
longitude=116.3912972,
|
||||
location_label="北京市, 中国",
|
||||
location_source="headline_location_hint",
|
||||
verified=True,
|
||||
location_meta={"target": {"country": "中国", "city": "Beijing"}},
|
||||
first_seen_at=datetime(2026, 5, 15, 2, 0, tzinfo=UTC),
|
||||
last_seen_at=datetime(2026, 5, 15, 3, 0, tzinfo=UTC),
|
||||
resolved_at=datetime(2026, 5, 15, 3, 5, tzinfo=UTC),
|
||||
)
|
||||
|
||||
async def fake_list_all_earth_news_records(_db):
|
||||
return [record]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.collectors.media_news_archive.list_all_earth_news_records",
|
||||
fake_list_all_earth_news_records,
|
||||
)
|
||||
|
||||
items = await collector.fetch()
|
||||
|
||||
assert items[0]["source_id"] == "bbc-world:archive"
|
||||
assert collector.data_type == "news_item"
|
||||
assert items[0]["country"] == "中国"
|
||||
assert items[0]["city"] == "Beijing"
|
||||
assert items[0]["latitude"] == 39.9057136
|
||||
assert items[0]["metadata"]["verified"] is True
|
||||
@@ -0,0 +1,12 @@
|
||||
from app.api.v1.settings import _is_secret_placeholder
|
||||
|
||||
|
||||
def test_secret_placeholder_treats_masked_values_as_placeholder():
|
||||
assert _is_secret_placeholder("••••••••", "••••1234") is True
|
||||
assert _is_secret_placeholder("********", "") is True
|
||||
assert _is_secret_placeholder(" * * * ", "") is True
|
||||
|
||||
|
||||
def test_secret_placeholder_preserves_real_keys_with_asterisks():
|
||||
assert _is_secret_placeholder("sk-live-*real-key*", "") is False
|
||||
assert _is_secret_placeholder("token_with*embedded*star", "") is False
|
||||
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"schema": "planet-earth-boundary-pov-policy/v1",
|
||||
"profile": "china-pov-v1",
|
||||
"description": "Product boundary policy for the China POV Earth boundary build. This file declares intent only; geometry must come from audited source packages and be applied offline before PMTiles/MVT generation.",
|
||||
"defaultCountryHandling": "source-admin0-with-reviewed-overrides",
|
||||
"rules": [
|
||||
{
|
||||
"id": "china-zangnan",
|
||||
"name": "Zangnan / South Tibet",
|
||||
"action": "union_to_country",
|
||||
"targetIsoA3": "CHN",
|
||||
"subtractFromIsoA3": ["IND"],
|
||||
"hoverIsoA3": "CHN",
|
||||
"labelPolicy": "show_country_only"
|
||||
},
|
||||
{
|
||||
"id": "china-aksai-chin",
|
||||
"name": "Aksai Chin",
|
||||
"action": "union_to_country",
|
||||
"targetIsoA3": "CHN",
|
||||
"subtractFromIsoA3": ["IND"],
|
||||
"hoverIsoA3": "CHN",
|
||||
"labelPolicy": "show_country_only"
|
||||
},
|
||||
{
|
||||
"id": "china-taiwan-penghu",
|
||||
"name": "Taiwan and Penghu",
|
||||
"action": "union_to_country",
|
||||
"targetIsoA3": "CHN",
|
||||
"hoverIsoA3": "CHN",
|
||||
"labelPolicy": "show_country_only"
|
||||
},
|
||||
{
|
||||
"id": "china-diaoyu-chiwei",
|
||||
"name": "Diaoyu Dao, affiliated islands, and Chiwei Yu",
|
||||
"action": "union_to_country",
|
||||
"targetIsoA3": "CHN",
|
||||
"hoverIsoA3": "CHN",
|
||||
"labelPolicy": "show_country_only"
|
||||
},
|
||||
{
|
||||
"id": "china-south-china-sea-islands",
|
||||
"name": "Dongsha, Xisha, Zhongsha, Nansha, Huangyan Dao, Zengmu Ansha and related islands/reefs",
|
||||
"action": "union_to_country",
|
||||
"targetIsoA3": "CHN",
|
||||
"hoverIsoA3": "CHN",
|
||||
"labelPolicy": "show_country_only"
|
||||
},
|
||||
{
|
||||
"id": "china-maritime-claim-line",
|
||||
"name": "South China Sea dashed maritime claim line",
|
||||
"action": "render_claim_line",
|
||||
"targetIsoA3": "CHN",
|
||||
"geometryRole": "claim_line_only",
|
||||
"landPolygonEffect": "none"
|
||||
},
|
||||
{
|
||||
"id": "kosovo",
|
||||
"name": "Kosovo",
|
||||
"action": "render_as_disputed_with_parent",
|
||||
"parentIsoA3": "SRB",
|
||||
"hoverIsoA3": "SRB",
|
||||
"boundaryStyle": "disputed_internal",
|
||||
"labelPolicy": "show_parent_country"
|
||||
},
|
||||
{
|
||||
"id": "gaza",
|
||||
"name": "Gaza Strip",
|
||||
"action": "render_as_region_of_country",
|
||||
"targetIsoA3": "PSE",
|
||||
"hoverIsoA3": "PSE",
|
||||
"boundaryStyle": "admin_or_disputed",
|
||||
"labelPolicy": "show_country_only"
|
||||
}
|
||||
],
|
||||
"sourceRequirements": {
|
||||
"geometryMustBeAudited": true,
|
||||
"noHandDrawnClaimLines": true,
|
||||
"noFrontendRuntimePovPatch": true,
|
||||
"artifactIsolation": "one PMTiles/MVT artifact per POV profile"
|
||||
},
|
||||
"officialPositionNotes": [
|
||||
{
|
||||
"id": "kosovo",
|
||||
"note": "China has emphasized respect for Serbia's sovereignty and territorial integrity and the framework of UNSC Resolution 1244."
|
||||
},
|
||||
{
|
||||
"id": "gaza",
|
||||
"note": "China supports the two-state solution and an independent State of Palestine based on the 1967 borders with East Jerusalem as its capital; Gaza governance should follow Palestinians governing Palestine."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
{
|
||||
"policy": {
|
||||
"runtimeFetch": false,
|
||||
"profile": "china-pov-v1",
|
||||
"povPolicyPath": "config/earth-boundary-pov-policy.china-v1.json",
|
||||
"productionTileFormat": "pmtiles+mvt",
|
||||
"debugTileFormat": "geojson-directory",
|
||||
"description": "Example Collector Settings payloads for audited Earth boundary source ingestion. Replace every endpoint, license, and checksum note before production."
|
||||
},
|
||||
"collectorConfigs": {
|
||||
"earth_admin0_boundaries": {
|
||||
"displayName": "Earth Admin-0 国界源",
|
||||
"sourceKind": "admin0-boundaries",
|
||||
"endpoint": "https://example.com/admin0-boundaries.geojson",
|
||||
"method": "GET",
|
||||
"headers": {},
|
||||
"auth_type": "none",
|
||||
"target_schema": "earth_boundary_source",
|
||||
"license": "REPLACE_WITH_SOURCE_LICENSE",
|
||||
"mapping_json": {
|
||||
"source": {
|
||||
"items_path": "$.features[*]"
|
||||
},
|
||||
"fields": {
|
||||
"source_id": {
|
||||
"path": "$.properties.id",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"path": "$.properties.name",
|
||||
"type": "string"
|
||||
},
|
||||
"geometry": {
|
||||
"path": "$.geometry",
|
||||
"type": "object"
|
||||
},
|
||||
"properties": {
|
||||
"path": "$.properties",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"earth_coastline": {
|
||||
"displayName": "Earth 海岸线源",
|
||||
"sourceKind": "coastline",
|
||||
"endpoint": "https://example.com/coastline.geojson",
|
||||
"method": "GET",
|
||||
"headers": {},
|
||||
"auth_type": "none",
|
||||
"target_schema": "earth_boundary_source",
|
||||
"license": "REPLACE_WITH_SOURCE_LICENSE",
|
||||
"mapping_json": {
|
||||
"source": {
|
||||
"items_path": "$.features[*]"
|
||||
},
|
||||
"fields": {
|
||||
"source_id": {
|
||||
"path": "$.properties.id",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"path": "$.properties.name",
|
||||
"type": "string"
|
||||
},
|
||||
"geometry": {
|
||||
"path": "$.geometry",
|
||||
"type": "object"
|
||||
},
|
||||
"properties": {
|
||||
"path": "$.properties",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"earth_claim_lines": {
|
||||
"displayName": "Earth 主张线源",
|
||||
"sourceKind": "claim-lines",
|
||||
"endpoint": "https://example.com/claim-lines.geojson",
|
||||
"method": "GET",
|
||||
"headers": {},
|
||||
"auth_type": "none",
|
||||
"target_schema": "earth_boundary_source",
|
||||
"license": "REPLACE_WITH_SOURCE_LICENSE",
|
||||
"mapping_json": {
|
||||
"source": {
|
||||
"items_path": "$.features[*]"
|
||||
},
|
||||
"fields": {
|
||||
"source_id": {
|
||||
"path": "$.properties.id",
|
||||
"type": "string"
|
||||
},
|
||||
"name": {
|
||||
"path": "$.properties.name",
|
||||
"type": "string"
|
||||
},
|
||||
"geometry": {
|
||||
"path": "$.geometry",
|
||||
"type": "object"
|
||||
},
|
||||
"properties": {
|
||||
"path": "$.properties",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"notes": [
|
||||
"Use the actual Collector Settings page as the source of truth for runtime endpoints.",
|
||||
"The repository seed GeoJSON may be used only for smoke tests and cannot satisfy production high precision."
|
||||
]
|
||||
}
|
||||
@@ -8,6 +8,87 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [0.58.0] — 2026-05-15
|
||||
|
||||
Released: 2026-05-15
|
||||
|
||||
### Highlights
|
||||
- 新增 Earth 高精度国界 PMTiles/MVT 前端链路,移除旧低精度 GeoJSON 国界兜底,国界缺失时显式报错。
|
||||
- 将 Earth 边界数据拆成 Admin-0、coastline、claim-lines 三个标准源采集器,并把 `earth_boundary_tiles` 收口为下游 PMTiles 构建器。
|
||||
- 修复 Earth 远距缩放下海陆基座与高清贴图 z-fighting 导致的雪花/黑块闪烁,并记录地表多层 shell 的深度间距规则。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 `earth_boundary_source` 目标 schema、China POV policy 配置、PMTiles readiness/build 脚本和 collector artifact 登记流程。
|
||||
- Earth 新闻巡航改为优先使用可缓存的目标地点解析队列,并补充媒体新闻归档采集器与回归测试。
|
||||
- 调整数据源列表任务状态展示,让 Earth 采集器失败/未就绪状态可见,不再表现为“未执行”。
|
||||
- 更新中英文采集器、数据源设置、Earth 图层顺序、运维 runbook、FAQ、规则和计划文档。
|
||||
|
||||
---
|
||||
|
||||
## [0.57.0] — 2026-05-14
|
||||
|
||||
Released: 2026-05-14
|
||||
|
||||
### Highlights
|
||||
- 新增 WSL `--allow-lan` 临时 Windows relay,保持本机 `localhost:3000` / `localhost:8000` 不变,同时用 Windows 局域网 IP 暴露相同端口。
|
||||
- 启动脚本会检测旧 `netsh interface portproxy` 冲突并请求管理员 PowerShell 清理,避免 `svchost.exe / iphlpsvc` 持久占用 3000/8000。
|
||||
- 修复 Vite CJS Node API deprecated warning,将前端配置迁移到 ESM,并让脚本按实际后端端口注入代理目标。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 [scripts/windows-lan-relay.ps1](/home/ray/dev/linkong/planet/scripts/windows-lan-relay.ps1),在 Windows 侧启动随 WSL 服务健康状态自动退出的 TCP relay。
|
||||
- `planet.sh --allow-lan` 仅在 WSL + PowerShell 可用时启用 Windows relay,并自动检查 Windows 防火墙规则;非 WSL 环境保持原有路径。
|
||||
- 更新中英文 README、FAQ 和运维文档,说明旧 portproxy 清理、UAC 防火墙授权、同端口 localhost/LAN 访问和故障恢复方式。
|
||||
|
||||
---
|
||||
|
||||
## [0.56.0] — 2026-05-13
|
||||
|
||||
Released: 2026-05-13
|
||||
|
||||
### Highlights
|
||||
- 修复 Earth 卫星 SGP4 坐标口径,当前点/短尾迹使用地固坐标,锁定预测轨道使用固定地球姿态下的闭合惯性轨道。
|
||||
- 优化真实高度压缩显示上限,将高轨显示控制在地球半径外约四分之一,保持 GEO/MEO/LEO 分层同时避免轨迹过远。
|
||||
- 统一 BGP 光晕与图标色调,并更新超算中心建筑图标和 Earth 新闻/HUD 面板体验。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 修正卫星详情卡近地点/远地点高度计算,避免把轨道半径误显示为离地高度。
|
||||
- 调整 BGP event / collector halo 的浅色派生规则,使红色事件、橙色活跃观测站和蓝色 idle 观测站保持各自色相。
|
||||
- 补充中英文用户手册、FAQ、Earth frontend context、render order、layer style reference 和相关计划文档。
|
||||
|
||||
---
|
||||
|
||||
## [0.55.0] — 2026-05-13
|
||||
|
||||
Released: 2026-05-13
|
||||
|
||||
### Highlights
|
||||
- 新增 Earth 卫星真实高度显示开关,默认按 TLE/SGP4 真实轨道高度压缩分层,关闭后恢复旧版同层球面。
|
||||
- 将卫星轨迹显示保留在设置面板,并让轨迹、预测轨道和锁定视觉跟随真实高度开关即时刷新。
|
||||
- 修复 Earth 设置面板 switch 圆点垂直居中问题,并同步更新用户手册、FAQ 和 Earth 开发者文档。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 `satelliteRealAltitudeEnabled` 本地偏好和真实高度压缩参数,保留 TLE 缺失/传播失败时的 fallback 固定高度。
|
||||
- 更新卫星渲染高度、轨迹、预测轨道和设置持久化链路,避免同一轨迹混入两套高度模型。
|
||||
- 补充中英文 manual、quickstart、FAQ、Earth frontend context、render order 和 layer style reference。
|
||||
|
||||
---
|
||||
|
||||
## [0.54.0] — 2026-05-13
|
||||
|
||||
Released: 2026-05-13
|
||||
|
||||
### Highlights
|
||||
- 新增 Earth 轨迹显示设置,将卫星轨迹从图层列表迁移到桌面与移动设置面板,便于独立控制轨迹线显示。
|
||||
- 优化卫星静止呼吸与低缩放圆点闪烁参数,让卫星态势视觉节奏更柔和、层次更清晰。
|
||||
- 更新算力中心图标资产,统一 Earth 交互图标在高分辨率显示下的视觉规格。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增轨迹显示偏好持久化,并在卫星图层不可用时同步禁用轨迹设置入口。
|
||||
- 调整卫星呼吸、透明度和 twinkle 参数,降低闪烁频率并增强可读性。
|
||||
- 将轨迹控制状态同步到桌面设置、移动设置和图层卡片刷新流程。
|
||||
|
||||
---
|
||||
|
||||
## [0.53.0] — 2026-05-13
|
||||
|
||||
Released: 2026-05-13
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
- [earth-mobile-drawer-ui-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-mobile-drawer-ui-plan.md)
|
||||
- [earth-compute-center-bgp-style-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-compute-center-bgp-style-plan.md)
|
||||
- [earth-renderer-architecture-separation-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-renderer-architecture-separation-plan.md)
|
||||
- [earth-country-boundary-overlay-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-country-boundary-overlay-plan.md)
|
||||
- [Earth 高精度国界静态瓦片计划](/home/ray/dev/linkong/planet/docs/plans/earth-high-precision-boundary-tiles-plan.md)
|
||||
- [earth-predicted-orbit-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-predicted-orbit-plan.md)
|
||||
- [earth-webgl-instancing-satellites-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-webgl-instancing-satellites-plan.md)
|
||||
- [earth-real-terrain-plan.md](/home/ray/dev/linkong/planet/docs/plans/earth-real-terrain-plan.md)
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
| 采集时是否调用 LLM | 不调用;采集链路必须确定性、可审计、可复现 |
|
||||
| 自定义数据如何进入 Earth | 必须映射到已支持的目标 schema,或先进入通用数据沉淀 |
|
||||
| 外部凭证放置位置 | Settings / 外部集成统一管理 provider token;DataSources 引用 provider profile |
|
||||
| TimescaleDB | 放入 TODO;高频时序数据稳定后再评估迁移 |
|
||||
| TimescaleDB | 高频时序数据稳定后再评估迁移 |
|
||||
|
||||
---
|
||||
|
||||
@@ -57,7 +57,7 @@ flowchart LR
|
||||
| schema | 用途 | Earth 可视化 |
|
||||
|-------|------|-------------|
|
||||
| `vessel_ais` | 船只 AIS 位置、航速、航向、MMSI 等 | 进入船舶图层 |
|
||||
| `geo_points` | 通用点位数据,包含经纬度、名称、类型、时间 | 进入通用 geo layer(TODO) |
|
||||
| `geo_points` | 通用点位数据,包含经纬度、名称、类型、时间 | 未来进入通用 geo layer |
|
||||
| `news_events` | 新闻/事件类数据,带时间、地点、摘要、来源 | 复用新闻/事件链路 |
|
||||
| `compute_centers` | 算力中心、机房、数据中心数据 | 复用算力中心图层 |
|
||||
| `generic_records` | 未知结构化数据沉淀 | 不直接展示 |
|
||||
@@ -294,7 +294,7 @@ PostgreSQL 可以承载当前规模的采集、关系查询、JSONB 沉淀和基
|
||||
- 查询模式还没稳定。
|
||||
- 需要快速迭代 schema 与 mapping。
|
||||
|
||||
### TODO:TimescaleDB
|
||||
### TimescaleDB 后续评估
|
||||
|
||||
以下条件满足后,再评估 TimescaleDB:
|
||||
|
||||
@@ -324,7 +324,7 @@ PostgreSQL 可以承载当前规模的采集、关系查询、JSONB 沉淀和基
|
||||
- Settings 中保存 provider credentials。
|
||||
- API 返回配置时必须 mask secret。
|
||||
- LLM prompt 只能包含脱敏 sample 和 schema 说明。
|
||||
- 后续 TODO:引入字段级加密或 KMS。
|
||||
- 后续可引入字段级加密或 KMS。
|
||||
|
||||
### Mapping 治理
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Earth High Precision Boundary PMTiles Plan
|
||||
|
||||
## Status
|
||||
|
||||
Current implementation:
|
||||
|
||||
- Three standard source collectors now handle real source ingestion: `earth_admin0_boundaries`, `earth_coastline`, and `earth_claim_lines`.
|
||||
- Each source collector reads endpoint / headers / auth / `target_schema=earth_boundary_source` from Collector Settings, downloads the configured payload, stores the full artifact under `data/earth-boundary-sources/<collector>/<sha256>.*`, and writes a hash / feature-count / artifact-path record to `CollectedData`.
|
||||
- The backend `earth_boundary_tiles` item is now a downstream PMTiles builder. It refuses to run until the three source records exist, then skips rebuilds when source / POV policy / build config are unchanged.
|
||||
- The frontend boundary layer now requires the production `pmtiles-mvt` provider and no longer falls back to legacy low-precision GeoJSON.
|
||||
- Generated loose boundary data is ignored by Git and is not the production deployment format.
|
||||
- Production PMTiles builds require external `tippecanoe` and `pmtiles` CLIs; missing tools fail the builder clearly instead of registering fake tile records.
|
||||
|
||||
Still required before claiming true one-to-one high precision:
|
||||
|
||||
- Replace the repository seed GeoJSON with audited high-precision admin boundary, coastline, and claim-line source packages.
|
||||
- Run a real geometry preparation step that applies the China POV policy through union / subtract / validity repair before PMTiles creation.
|
||||
- Build and publish `earth-boundaries-china-pov-v1.pmtiles` plus its manifest.
|
||||
|
||||
## Summary
|
||||
|
||||
The Earth boundary layer should use one static PMTiles archive containing MVT tiles instead of thousands of loose GeoJSON files. The artifact is POV-specific: `earth-boundaries-china-pov-v1.pmtiles` has China POV baked in during offline source preparation, and the browser never patches political boundaries at runtime.
|
||||
|
||||
Production must serve a single PMTiles artifact through static hosting and HTTP range requests. Missing PMTiles is a hard boundary-layer error, not a silent low-precision fallback.
|
||||
|
||||
## Key Implementation Rules
|
||||
|
||||
- Source inputs must be auditable. OSM admin boundaries, coastline packages, and claim-line endpoints are configured through Collector Settings using the `earth_boundary_source` target schema; `config/earth-boundary-sources.example.json` remains the versioned example template.
|
||||
- China POV geometry is applied before tiling:
|
||||
- Zangnan and Aksai Chin are unioned into China and subtracted from India.
|
||||
- Taiwan/Penghu, Diaoyu Dao and affiliated islands, Chiwei Yu, and South China Sea islands are China hover/country features.
|
||||
- The South China Sea dashed line is a claim-line layer only; it never consumes Malaysian, Philippine, Vietnamese, or other land polygons.
|
||||
- Kosovo is not an independent country surface in this profile; Gaza is a Palestine region.
|
||||
- PMTiles/MVT layer names are fixed for the frontend:
|
||||
- `boundary_admin0`
|
||||
- `boundary_disputed_internal`
|
||||
- `coastline`
|
||||
- `claim_line`
|
||||
- The frontend provider is selected from the boundary manifest:
|
||||
- `tileProvider: "pmtiles-mvt"` reads the PMTiles artifact.
|
||||
- Any other provider, missing manifest, or missing PMTiles artifact is treated as an error.
|
||||
- Redis is not part of v1. Static PMTiles plus browser/CDN range caching is the default performance model.
|
||||
|
||||
## Cleanup And Documentation
|
||||
|
||||
- Do not commit generated loose tiles under `frontend/public/earth/data/boundaries/` or source downloads under `data/earth-boundary-sources/`.
|
||||
- Remove stale generated debug data before production builds; regenerate it only when smoke testing the debug path.
|
||||
- Keep the high-level plan, backend collector docs, layer style docs, and ops runbook aligned whenever the provider contract changes.
|
||||
- After implementation changes, provide user-facing operation steps covering source configuration, source collection, artifact build/deploy, page verification, and fallback troubleshooting.
|
||||
|
||||
## Verification
|
||||
|
||||
- The PMTiles builder fails as not ready when any of `earth_admin0_boundaries`, `earth_coastline`, or `earth_claim_lines` has not produced a current artifact record.
|
||||
- The PMTiles builder fails as not ready when source artifacts exist but `tippecanoe` / `pmtiles` are missing.
|
||||
- Running the PMTiles builder twice returns `unchanged` on the second run when inputs are stable.
|
||||
- `git add . --dry-run` does not include generated loose boundary tiles or source downloads.
|
||||
- `/home/ray/.bun/bin/bun run build` passes in `frontend`.
|
||||
- Manual Earth checks confirm:
|
||||
- PMTiles range requests are issued only for visible tiles.
|
||||
- Boundary toggle, hover tooltip, and country highlight still work.
|
||||
- PMTiles failure reports a boundary-layer error; the frontend must not draw low-precision legacy boundaries.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- "One-to-one" means source-faithful to the selected audited vector source, not hand-tuned to a screenshot.
|
||||
- The China POV artifact is static and versioned; no runtime region-based POV switching is planned.
|
||||
- The removed repository seed file cannot be used as a runtime fallback for country boundaries.
|
||||
@@ -0,0 +1,118 @@
|
||||
# Earth High Resolution Basemap Tiles Plan
|
||||
|
||||
## Summary
|
||||
|
||||
High-precision borders now expose a separate visual problem: the vector coastline and border data are more accurate than the current raster Earth texture. The next step is a high-resolution basemap tile layer that aligns visually with the high-precision coastline instead of replacing the globe with one huge static image.
|
||||
|
||||
Do not solve this by committing a larger single world texture. A single 16K/32K raster still wastes memory, loads slowly, and becomes blurry or misaligned when zooming into coastal detail. The target architecture is viewport-based raster tiles with cache control, similar to terrain tiles.
|
||||
|
||||
## Goals
|
||||
|
||||
- Render a high-resolution Earth imagery basemap that visually matches the high-precision coastline and country boundary layer.
|
||||
- Load imagery by visible bbox / tile key instead of loading a whole-world giant texture.
|
||||
- Keep the current global texture only as a low-zoom background, not as the source of truth for coastlines at inspection zoom.
|
||||
- Let imagery failures degrade only the imagery layer; high-precision borders and hover must continue working.
|
||||
- Keep generated imagery cache out of Git.
|
||||
|
||||
## Data Sources
|
||||
|
||||
Candidate sources, in recommended order:
|
||||
|
||||
- NASA GIBS / Blue Marble / VIIRS style imagery for permissive global coverage and stable tile service behavior.
|
||||
- Sentinel-2 cloudless style public imagery if licensing and tile access are acceptable.
|
||||
- A self-hosted raster pyramid generated offline from audited global imagery if third-party online tile terms are unsuitable.
|
||||
|
||||
The selected source must document:
|
||||
|
||||
- license / attribution
|
||||
- max zoom and native resolution
|
||||
- tile matrix / projection
|
||||
- cache policy
|
||||
- whether commercial or public deployment is allowed
|
||||
|
||||
## Architecture
|
||||
|
||||
```text
|
||||
global low-zoom texture
|
||||
→ visible Earth bbox from camera raycast
|
||||
→ Web Mercator tile keys by zoom
|
||||
→ raster tile fetch/cache
|
||||
→ project tile image patches onto Earth surface
|
||||
→ high-precision coastline / border layer remains above imagery
|
||||
```
|
||||
|
||||
Implementation should mirror the existing terrain tile discipline:
|
||||
|
||||
- dedupe in-flight requests
|
||||
- LRU cache for decoded images / textures
|
||||
- debounce camera movement
|
||||
- cancel or ignore stale viewport requests
|
||||
- cap max tiles per frame / per view
|
||||
- expose loading/error diagnostics
|
||||
|
||||
## Rendering Rules
|
||||
|
||||
- The high-resolution imagery layer is visual only. It must not define country hover, coastline, or border geometry.
|
||||
- The high-precision coastline remains the visual alignment reference.
|
||||
- The border layer render order stays above the basemap imagery.
|
||||
- Low zoom may use the current global texture for speed.
|
||||
- Mid/high zoom overlays imagery tiles only for the visible region plus a small prefetch ring.
|
||||
- Do not draw decorative gradients or fake coastlines to hide mismatch.
|
||||
|
||||
## Frontend Work
|
||||
|
||||
- Add a new `basemap-imagery.js` module instead of expanding `country-boundaries.js`.
|
||||
- Add config in `constants.js`:
|
||||
- source URL template
|
||||
- attribution
|
||||
- min/max zoom
|
||||
- tile cache limit
|
||||
- debounce interval
|
||||
- opacity
|
||||
- enable/disable setting
|
||||
- Add Earth settings control:
|
||||
- `高清底图`: off / auto / on
|
||||
- default `auto`
|
||||
- Add debug counters for:
|
||||
- active tile count
|
||||
- cached tile count
|
||||
- failed tile count
|
||||
- current imagery zoom
|
||||
|
||||
## Backend / Ops Work
|
||||
|
||||
- If using a third-party tile service directly, document attribution and rate-limit behavior.
|
||||
- If proxying tiles, add backend cache with request coalescing and timeout limits.
|
||||
- If self-hosting, add an offline builder that writes ignored tile artifacts under a dedicated data directory.
|
||||
- Update Nginx static serving if self-hosted raster tiles are used.
|
||||
|
||||
## Performance Budget
|
||||
|
||||
- Desktop target: keep visible imagery tiles under a configurable cap, initially 64.
|
||||
- Mobile target: lower max zoom and tile cap by default.
|
||||
- Decode and upload textures incrementally; avoid blocking Earth startup on high-resolution imagery.
|
||||
- First Earth paint must still use the existing lightweight global texture.
|
||||
|
||||
## Verification
|
||||
|
||||
- Compare high-precision coastline against imagery in coastal areas such as southeast China, Taiwan, Hainan, the Korean peninsula, Japan, and island chains in the South China Sea.
|
||||
- Verify zooming / panning does not create visible tile thrash or long blank periods.
|
||||
- Verify failed imagery requests do not hide borders or break hover.
|
||||
- Verify memory stabilizes after repeated pan/zoom due to LRU eviction.
|
||||
- Run `/home/ray/.bun/bin/bun run build`.
|
||||
|
||||
## User Operation Steps
|
||||
|
||||
After implementation, the user should be able to:
|
||||
|
||||
1. Open Earth settings.
|
||||
2. Set `高清底图` to `auto` or `on`.
|
||||
3. Open Earth and zoom into a coastline.
|
||||
4. See imagery tiles refine under the high-precision boundary/coastline layer.
|
||||
5. Use diagnostics to confirm which imagery zoom and tile source are active.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- The existing high-precision vector coastline is the alignment reference.
|
||||
- This plan improves visual texture fidelity; it does not replace the boundary data pipeline.
|
||||
- A single larger static Earth texture is rejected as the primary solution.
|
||||
@@ -273,7 +273,7 @@ hover / locked 使用少量 overlay:
|
||||
|
||||
- 算力中心保留现有业务 icon,但接入统一 hover / locked / glow。(已完成)
|
||||
- 登陆点曾接入同一套 `Points` 渲染,但 pin 类 SVG 在地球边缘会被深度测试裁切;当前保留专用 `THREE.Sprite`,并使用 canvas 生成黄色扁平球,贴到海缆层级。
|
||||
- TODO:登陆点暂不迁移到完整 Interactable。后续若要统一交互接口,优先考虑 Sprite-backed adapter,只对齐 `getMarkers()`、`getPointerIntersections()`、`setMarkerState()`、`updateVisualState()` 等外观协议,不强行复用 `THREE.Points`、atlas 和跨图层避让。
|
||||
- 登陆点暂不迁移到完整 Interactable。后续若要统一交互接口,优先考虑 Sprite-backed adapter,只对齐 `getMarkers()`、`getPointerIntersections()`、`setMarkerState()`、`updateVisualState()` 等外观协议,不强行复用 `THREE.Points`、atlas 和跨图层避让。
|
||||
- 检查图例、搜索和 info-card 是否只依赖业务 payload,而不是依赖渲染对象类型。
|
||||
|
||||
### Phase 4:形成 Earth 图标层规范
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
## Non-goals
|
||||
|
||||
- 不改变桌面端 hover 交互。
|
||||
- 不替换 `countries-admin0.min.geojson` 数据源。
|
||||
- 不引入旧低精度国界兜底;移动端中心国家能力必须复用生产 PMTiles/MVT 国界源。
|
||||
- 不新增后端 API。
|
||||
- 不把国家面填充做成新的 selected country 面状 shader。
|
||||
- 不为移动端增加永久准星 UI,除非后续产品明确需要视觉准星。
|
||||
@@ -249,4 +249,3 @@ mobileCenterHoverGlowOpacity
|
||||
3. 性能保护:加入节流、经纬度阈值和禁用态清理。
|
||||
4. 验证:本地构建通过,移动端 viewport 手动检查通过。
|
||||
5. 调优:根据截图或真机体验微调阻塞条件和节流阈值。
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Earth Surface Hover Info Plan
|
||||
|
||||
Status: Implemented.
|
||||
|
||||
## Goal
|
||||
|
||||
为 Earth 桌面和 compact 鼠标地表 hover 增加可配置的提示内容,让用户可以选择只看国家信息、只看位置数据,或同时查看国家和经纬海拔。
|
||||
|
||||
当前地表 hover 已经具备两类信息:
|
||||
|
||||
- 命中国家时显示国家、ISO、大洲,并高亮国界。
|
||||
- 未命中国家时显示纬度、经度、海拔。
|
||||
|
||||
新方案把这两类信息合并成一个清晰的设置项:`悬停提示`。
|
||||
|
||||
## User-facing behavior
|
||||
|
||||
设置项放在桌面设置和移动端设置的 `视图` 区,使用分段控件:
|
||||
|
||||
- `国家`:陆地命中国家时显示国家名、ISO、大洲;太平洋等海洋区域不显示地表 tooltip。
|
||||
- `位置`:陆地和海洋都显示纬度、经度、海拔;不触发国家 tooltip 和国家边界 hover 高亮。
|
||||
- `完整`:陆地命中国家时显示国家信息和纬度、经度、海拔;海洋区域显示纬度、经度、海拔。
|
||||
|
||||
默认值为 `完整`,因为它保留现有国家识别价值,同时满足 hover 时查看经纬海拔的需求。
|
||||
|
||||
海洋在 `国家` 模式下保持沉默,而不是显示大洋名称。原因是当前项目没有海域/大洋边界数据源;用经纬度粗判太平洋、大西洋等范围容易产生误导。如果用户需要海洋位置,使用 `位置` 或 `完整`。
|
||||
|
||||
## Implementation plan
|
||||
|
||||
### Settings state
|
||||
|
||||
在 `frontend/public/earth/js/constants.js` 增加:
|
||||
|
||||
```js
|
||||
export const SURFACE_HOVER_INFO_MODES = {
|
||||
COUNTRY: "country",
|
||||
POSITION: "position",
|
||||
FULL: "full",
|
||||
};
|
||||
|
||||
export const DEFAULT_SURFACE_HOVER_INFO_MODE =
|
||||
SURFACE_HOVER_INFO_MODES.FULL;
|
||||
```
|
||||
|
||||
在 `frontend/public/earth/js/controls.js`:
|
||||
|
||||
- 将 `EARTH_SETTINGS_VERSION` 从 `10` 升到 `11`。
|
||||
- 在 shared settings 中新增 `surfaceHoverInfoMode`。
|
||||
- 新增导出:
|
||||
- `getSurfaceHoverInfoMode()`
|
||||
- `setSurfaceHoverInfoMode(mode, { persist, suppressStatus })`
|
||||
- normalize 时只接受 `country | position | full`,否则回退到 `full`。
|
||||
- reset settings 后恢复为 `full`。
|
||||
|
||||
### Settings UI
|
||||
|
||||
在桌面设置 `视图` 区和移动端设置 `视图` 区加入同一组按钮:
|
||||
|
||||
```html
|
||||
<button data-surface-hover-info-mode="country">国家</button>
|
||||
<button data-surface-hover-info-mode="position">位置</button>
|
||||
<button data-surface-hover-info-mode="full">完整</button>
|
||||
```
|
||||
|
||||
控件同步规则沿用现有卫星显示风格和巡航模块的模式:
|
||||
|
||||
- 当前模式按钮添加 `is-active`。
|
||||
- 当前模式按钮设置 `aria-pressed="true"`。
|
||||
- 切换后保存到 Earth settings localStorage。
|
||||
|
||||
### Hover tooltip logic
|
||||
|
||||
在 `frontend/public/earth/js/main.js` 的地表 hover 分支中读取 `getSurfaceHoverInfoMode()`,统一构造 tooltip。
|
||||
|
||||
行为规则:
|
||||
|
||||
- 如果没有命中地球:清除国家 hover 并隐藏 tooltip。
|
||||
- `position`:
|
||||
- 调用 `clearCountryBoundaryHover()`。
|
||||
- 显示 `纬度 / 经度 / 海拔`。
|
||||
- `country`:
|
||||
- 仅当国界图层开启并命中国家时显示国家 tooltip 和国界 hover。
|
||||
- 海洋、国界图层关闭、未加载国界数据时隐藏地表 tooltip。
|
||||
- `full`:
|
||||
- 国界图层开启且命中国家时显示国家信息加位置信息。
|
||||
- 未命中国家或国界图层关闭时显示位置信息。
|
||||
|
||||
海拔继续使用 `sampleElevationAt(lat, lon)`。暂无采样时显示 `—`,不因 hover 主动加载地形瓦片。
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
1. `完整` 模式下,hover 陆地显示国家信息和经纬海拔,hover 海洋显示经纬海拔。
|
||||
2. `国家` 模式下,hover 陆地显示国家信息,hover 太平洋等海洋不显示地表 tooltip。
|
||||
3. `位置` 模式下,hover 陆地和海洋都显示经纬海拔,国家边界不高亮。
|
||||
4. 关闭国界图层后,`完整` 模式回退为只显示位置。
|
||||
5. 船只、BGP、算力中心、海缆等对象 hover tooltip 优先级不变。
|
||||
6. 移动端中心国家高亮不受这个鼠标 hover 设置影响。
|
||||
7. 设置刷新后保持,重置后恢复为 `完整`。
|
||||
|
||||
## Verification
|
||||
|
||||
- 在 `frontend` 下运行 `/home/ray/.bun/bin/bun run build`。
|
||||
- 手动验证三种模式的陆地和海洋 hover 行为。
|
||||
- 验证设置持久化和重置。
|
||||
- 验证对象 hover 仍优先于地表 hover。
|
||||
@@ -1,14 +1,14 @@
|
||||
# 实时船只监控系统 — 实施计划
|
||||
|
||||
**状态**:规划中
|
||||
**状态**:历史计划;实时 AIS 与聚合接口已由 [AIS 多源采集、冲突记录与聚合接口计划](/home/ray/dev/linkong/planet/docs/plans/earth-vessel-ais-aggregation-plan.md) 接管
|
||||
**创建日期**:2026-04-27
|
||||
**优先数据源**:BarentsWatch AIS(免费但需要 OAuth client credentials)→ AISHub / MarineTraffic(TODO,付费)
|
||||
**优先数据源**:BarentsWatch AIS(免费但需要 OAuth client credentials)→ AISStream realtime;AISHub / MarineTraffic 保留为付费备选
|
||||
|
||||
## 已确认决策
|
||||
|
||||
| 项目 | 决策 |
|
||||
|-----|------|
|
||||
| 数据源 | BarentsWatch 先行;AISHub / MarineTraffic TODO |
|
||||
| 数据源 | BarentsWatch 先行;AISStream realtime 已成为全球实时补充;AISHub / MarineTraffic 保留为付费备选 |
|
||||
| 船只规模 | BarentsWatch 阶段全部显示;全球数据接入后按需加船型过滤(默认 Cargo + Tanker + Passenger) |
|
||||
| 更新频率 | 准实时:前端 5 分钟轮询,后端 Collector 每分钟拉取写库 |
|
||||
| 历史轨迹 | 保留(`vessel_position` 表保留 24h,后期按需扩展) |
|
||||
@@ -23,9 +23,9 @@
|
||||
| 来源类型 | 典型服务 | 覆盖范围 | 成本 | 状态 |
|
||||
|---------|---------|---------|------|------|
|
||||
| **BarentsWatch AIS API** | live.ais.barentswatch.no | 挪威海域实时 | 免费,需要 AIS API client credentials | **当前使用** |
|
||||
| **AISHub** | aishub.net | 全球实时 | 免费/小额 | TODO:付费接入 |
|
||||
| **MarineTraffic API** | marinetraffic.com | 全球实时 | $50–$500/月 | TODO:评估 tier |
|
||||
| **VesselFinder API** | vesselfinder.com | 全球实时 | $50–$300/月 | TODO:备选 |
|
||||
| **AISHub** | aishub.net | 全球实时 | 免费/小额 | 付费备选 |
|
||||
| **MarineTraffic API** | marinetraffic.com | 全球实时 | $50–$500/月 | 待评估 tier |
|
||||
| **VesselFinder API** | vesselfinder.com | 全球实时 | $50–$300/月 | 备选 |
|
||||
| **自建 SDR 接收** | RTL-SDR + AIS-catcher | 仅本地 30–50km | 硬件 $30 | 不考虑 |
|
||||
| **NOAA 历史数据** | Marine Cadastre | 美国近海历史 | 免费 | 可用于冷启动 |
|
||||
|
||||
@@ -36,16 +36,9 @@
|
||||
- 字段:mmsi, lat, lon, sog, cog, heading, nav_status, name, vessel_type, flag
|
||||
- 刷新频率:数据约 30–60s 更新一次,可随意轮询
|
||||
|
||||
### TODO:多源 AIS 与实时流接入
|
||||
### 多源 AIS 与实时流接入历史
|
||||
|
||||
- [ ] 接入 AISStream WebSocket 采集器,作为 BarentsWatch 覆盖不足的实时补充
|
||||
- [ ] 将 BarentsWatch、AISStream、自定义 `vessel_ais` 映射源统一写入原始观测层
|
||||
- [ ] 通过聚合接口做去重、字段合并、冲突记录和默认来源选择
|
||||
- [ ] 开放字段级聚合策略配置,让用户决定不同字段优先信任哪个来源
|
||||
- [ ] 评估 AISHub 订阅(全球覆盖,约 $30/月),接入全球实时流
|
||||
- [ ] 评估 MarineTraffic API tier,对比 AISHub 数据质量与成本
|
||||
- [ ] 实现多数据源适配器,通过 `datasource_config` 切换
|
||||
- [ ] 真实高频 AIS 稳定接入后,评估将 `vessel_position` 迁移为 TimescaleDB hypertable(保留 Postgres 原生分区作为备选)
|
||||
AISStream WebSocket collector、`/api/v1/vessels/snapshot` 和 `/ws` vessels channel 已在后续计划中落地。仍有价值的后续项集中维护在根目录 [TODO](/home/ray/dev/linkong/planet/TODO.md) 的 AIS / Vessels 小节。
|
||||
|
||||
多源 AIS 的详细设计见 [AIS 多源采集、冲突记录与聚合接口计划](/home/ray/dev/linkong/planet/docs/plans/earth-vessel-ais-aggregation-plan.md)。
|
||||
|
||||
@@ -252,7 +245,7 @@ IMO 9811000
|
||||
### Phase 4 — 性能与生产化(2–3 天)
|
||||
|
||||
- `vessel_position` 按天分区,7 天自动清理
|
||||
- TODO:真实数据量达到百万级/日后,将 `vessel_position` 升级为 TimescaleDB hypertable,配置 retention policy 与压缩策略
|
||||
- 真实数据量达到百万级/日后,再评估是否将船只时序数据升级为 TimescaleDB hypertable,并配置 retention policy 与压缩策略
|
||||
- GeoJSON endpoint 用 Redis 缓存 15s
|
||||
- 若需 bbox 精确查询,引入 PostGIS `geography` + `ST_DWithin`
|
||||
- InstancedMesh + frustum culling,目标 5 万船只 60fps
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# EarthFeed 新闻坐标与异步精修计划
|
||||
|
||||
## 目标
|
||||
|
||||
EarthFeed 的每条新闻都直接携带巡航可用坐标。初始响应使用新闻所属大区的锚点坐标,后台通过消息队列异步推理更精确的目标地址,完成后用实时补丁替换原新闻坐标,实现前端无感更新。
|
||||
|
||||
## 返回结构
|
||||
|
||||
`GET /api/v1/news/earth-feed` 返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"generated_at": "2026-05-15T03:16:43Z",
|
||||
"focus": {
|
||||
"lat": null,
|
||||
"lon": null,
|
||||
"region": "global",
|
||||
"label": "全球焦点",
|
||||
"accent": "#d6e6ff"
|
||||
},
|
||||
"sources": [
|
||||
{
|
||||
"id": "bbc-world",
|
||||
"name": "BBC World",
|
||||
"region": "global",
|
||||
"homepage_url": "https://www.bbc.com/news/world"
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "bbc-world:af01519ba7dd",
|
||||
"title": "Flattery and fanfare as Trump welcomed to China - but thorny issues remain",
|
||||
"summary": "The leaders of the world's two superpowers were all smiles...",
|
||||
"url": "https://www.bbc.com/news/articles/cdxpypg9dgeo",
|
||||
"source": "BBC World",
|
||||
"feed_name": "BBC World",
|
||||
"region": "global",
|
||||
"homepage_url": "https://www.bbc.com/news/world",
|
||||
"published_at": "2026-05-14T13:02:13Z",
|
||||
"latitude": 39.9057136,
|
||||
"longitude": 116.3912972,
|
||||
"location_label": "北京市, 中国",
|
||||
"location_source": "headline_location_hint",
|
||||
"verified": true,
|
||||
"location_meta": {
|
||||
"resolution_stage": "headline_location_hint",
|
||||
"ai_attempted": false,
|
||||
"ai_status": "skipped_text_hint",
|
||||
"ai_error": null,
|
||||
"debug_note": "text hint matched 北京市, 中国",
|
||||
"target": {
|
||||
"latitude": 39.9057136,
|
||||
"longitude": 116.3912972,
|
||||
"label": "北京市, 中国",
|
||||
"source": "headline_location_hint",
|
||||
"confidence": 0.78,
|
||||
"country": "中国",
|
||||
"city": "Beijing"
|
||||
},
|
||||
"anchor": {
|
||||
"region": "global",
|
||||
"label": "全球",
|
||||
"latitude": 20.0,
|
||||
"longitude": 0.0
|
||||
}
|
||||
},
|
||||
"is_focus_match": true
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"stale": false
|
||||
}
|
||||
```
|
||||
|
||||
字段规则:
|
||||
|
||||
- `latitude` / `longitude`:前端巡航唯一读取的坐标。
|
||||
- `location_label`:当前坐标展示名。
|
||||
- `location_source`:`region_anchor`、`headline_location_hint`、`headline_country_hint`、`ai_inferred_target` 等。
|
||||
- `verified`:`false` 表示仍是大区锚点;`true` 表示已经由标题规则、国家规则或 AI 得到目标地址。
|
||||
- `location_meta`:调试、诊断、AI 状态、目标地址和锚点详情都放这里,不再展开成 `t_*` 主字段。
|
||||
|
||||
## 后台队列
|
||||
|
||||
当前使用 Redis Streams:
|
||||
|
||||
- stream:`earth_news:target_location:jobs`
|
||||
- consumer group:`earth_news_target_location`
|
||||
- result cache:`earth_news:target_location:result:{item_id}`
|
||||
- dedupe key:`earth_news:target_location:queued:{item_id}`
|
||||
|
||||
请求流程:
|
||||
|
||||
1. RSS 拉取并排序。
|
||||
2. 每条新闻先生成大区锚点坐标,`verified=false`。
|
||||
3. 若 Redis 已有该新闻的精修结果,则合并结果返回。
|
||||
4. 若没有精修结果,则把新闻 job 入队,接口立即返回。
|
||||
|
||||
Worker 流程:
|
||||
|
||||
1. 从队列消费新闻 job。
|
||||
2. 先跑标题/国家规则,再视情况调用 AI。
|
||||
3. 写入 result cache。
|
||||
4. 广播 WebSocket 补丁:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "data_frame",
|
||||
"channel": "earth_news",
|
||||
"timestamp": "2026-05-15T03:17:00Z",
|
||||
"payload": {
|
||||
"item_id": "bbc-world:af01519ba7dd",
|
||||
"patch": {
|
||||
"latitude": 39.9057136,
|
||||
"longitude": 116.3912972,
|
||||
"location_label": "北京市, 中国",
|
||||
"location_source": "headline_location_hint",
|
||||
"verified": true,
|
||||
"location_meta": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 可迁移性
|
||||
|
||||
业务代码只调用队列接口,不直接依赖 Redis Streams 细节。以后迁移 Kafka 时新增 Kafka adapter,保持 job payload、result patch 和 worker 推理逻辑不变。
|
||||
|
||||
## 前端规则
|
||||
|
||||
新闻面板和巡航都只读取新闻项内的 `latitude` / `longitude`。实时补丁到达后按 `item_id` 合并到现有 `payload.items`,重新渲染并触发 `earth:news-payload-updated`,巡航下一轮自然使用精修坐标。
|
||||
@@ -86,9 +86,17 @@ async def run(self, db):
|
||||
| TeleGeography | submarine_cable | Submarine cable information | 7 days |
|
||||
| BarentsWatch AIS | vessel | AIS vessel positions, speed, heading, MMSI, and related fields | Collector settings |
|
||||
| AISStream Vessels | vessel_ais | AIS WebSocket realtime stream, written to the raw observation layer and displayed through aggregation | Collector settings |
|
||||
| Earth Admin-0 Boundaries | earth_admin0_boundaries | Downloads the configured country-boundary source, saves an artifact, and writes an `earth_boundary_source` manifest record | Collector settings |
|
||||
| Earth Coastline | earth_coastline | Downloads the configured coastline source, saves an artifact, and writes an `earth_boundary_source` manifest record | Collector settings |
|
||||
| Earth Claim Lines | earth_claim_lines | Downloads the configured claim-line source, saves an artifact, and writes an `earth_boundary_source` manifest record | Collector settings |
|
||||
| Earth PMTiles Builder | earth_boundary_tiles | Reads the three Earth boundary source records and builds / registers the PMTiles artifact | Collector settings |
|
||||
|
||||
AIS vessel collectors use a different persistence path from regular `CollectedData` collectors. BarentsWatch, AISStream, and custom `vessel_ais` sources write into the AIS raw observation layer first, then the aggregation service merges those observations into the GeoJSON and detail payloads used by the Earth vessel layer. This preserves source, transport, field conflicts, and observation time instead of letting one realtime source overwrite the final display table.
|
||||
|
||||
Earth boundaries are now split into three real source collectors plus one downstream builder. `earth_admin0_boundaries`, `earth_coastline`, and `earth_claim_lines` read endpoint, headers, auth, and `config.target_schema=earth_boundary_source` from Collector Settings. Triggering them requests the configured endpoint, writes the full response to `data/earth-boundary-sources/<collector>/<sha256>.*`, and stores sha256, feature count, license, artifact path, sample properties, and mapping metadata in `CollectedData`.
|
||||
|
||||
`earth_boundary_tiles` no longer means source-data collection. It reads the latest successful records from those three source collectors; if any source is missing, the task fails as "not ready" and does not register "4 high-precision tile" records. Once all sources exist, it uses `tippecanoe` / `pmtiles` to build `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles`; if those tools are missing, the task fails with the missing-tool message. There is no legacy low-precision fallback for country boundaries.
|
||||
|
||||
TOP500 and Epoch AI compute sources do not always provide usable coordinates. The unified Earth compute-center endpoint uses only valid source-provided coordinates or `compute_center_locations` dimension-table coordinates during the main map startup path; records without coordinates are returned as `unresolved` instead of being rendered from a local registry, country centroid, or guessed city. When users manually collect candidates, the backend queries ROR and Nominatim/OpenStreetMap from source fields; accepted candidates are saved into `compute_center_locations` and rendered from that table on the next layer refresh.
|
||||
|
||||
## IV. Data Format (stored in CollectedData table)
|
||||
@@ -219,7 +227,8 @@ backend/app/services/collectors/
|
||||
├── peeringdb.py # PeeringDB collector
|
||||
├── telegeraphy.py # TeleGeography submarine cable collector
|
||||
├── vessel_ais.py # BarentsWatch AIS vessel collector
|
||||
└── aisstream.py # AISStream WebSocket vessel collector
|
||||
├── aisstream.py # AISStream WebSocket vessel collector
|
||||
└── earth_boundaries.py # Earth boundary source verification and static tile artifact collector
|
||||
|
||||
backend/app/services/
|
||||
├── custom_datasource_runtime.py # Custom REST / WebSocket mapping runtime
|
||||
|
||||
@@ -307,6 +307,8 @@ Files:
|
||||
|
||||
Custom sources are supplemental inputs for existing target schemas, not isolated data islands. The most complete target today is `vessel_ais`: a custom REST or WebSocket source is mapped deterministically, written into AIS raw observations, and then pushed to Earth through the `vessels` WebSocket channel.
|
||||
|
||||
Earth high-precision boundaries use the same target-schema mechanism. `earth_boundary_source` receives mapped records for `earth_admin0_boundaries`, `earth_coastline`, and `earth_claim_lines`; full GeoJSON / JSON payloads are stored as artifacts, while the database only keeps source kind, sha256, feature count, license, artifact path, and sample properties so large geometries do not land in a single row.
|
||||
|
||||
### Configuration Semantics
|
||||
|
||||
Important fields:
|
||||
@@ -316,7 +318,7 @@ Important fields:
|
||||
- `auth_type`: `none`, `bearer`, `api_key`, or `basic`.
|
||||
- `headers`: static request headers.
|
||||
- `auth_config`: token, API key, or basic username/password; API keys can be sent by header or query.
|
||||
- `config.target_schema`: for example `vessel_ais`.
|
||||
- `config.target_schema`: for example `vessel_ais` or `earth_boundary_source`.
|
||||
- `config.delivery_mode`: REST defaults to `polling`; WebSocket defaults to `realtime_stream`.
|
||||
- `config.merge_target_source`: records which built-in source this custom source supplements, such as `barentswatch_vessels`.
|
||||
|
||||
|
||||
@@ -157,6 +157,7 @@ Current design:
|
||||
- symbol-driven event cores
|
||||
- outward ring pulses
|
||||
- reduced diffuse glow compared with older Earth builds
|
||||
- event region halos, collector coverage halos, and radar pulses derive a lighter tint from their own icon color instead of using a fixed teal; red high-severity events, orange active collectors, and blue idle collectors keep their hue family while broad halos stay softer than the icon
|
||||
5. The right-side stats now show:
|
||||
- BGP events
|
||||
- collector count
|
||||
|
||||
@@ -122,6 +122,9 @@ Responsibilities:
|
||||
- Globe sphere, cloud layer, atmosphere
|
||||
- Real terrain mesh
|
||||
- Terrain tile fetch, decode, displacement, and shading
|
||||
- Whole-globe land/ocean and border base overlays
|
||||
|
||||
The Earth surface is a stack of near-concentric shells, not a single mesh. The base sphere and HD texture overlay in `earth.js`, plus the land/ocean base in `country-boundaries.js`, need explicit radius separation. At far zoom, GPU depth precision drops; neighboring shells that are too close can z-fight and show black flicker blocks or snow. The current stable spacing is `landAltitudeOffset = 0.32` and `textureOverlayAltitudeOffset = 0.48`. When adding or adjusting whole-globe surface overlays, update [Earth Render Layer Order](/home/ray/dev/linkong/planet/docs/technical/en/earth-render-layer-order.md) and verify at 50% zoom.
|
||||
|
||||
### 7. Layer Modules
|
||||
|
||||
@@ -205,7 +208,13 @@ Terrain should not block startup when it is not the restored visible layer. Afte
|
||||
|
||||
Earth settings are stored in `localStorage`. The key is typically a namespaced string defined in `constants.js`. `controls.js` handles read, write, and reset.
|
||||
|
||||
Settings that affect visual layers (terrain opacity, day/night mode, satellite display style, etc.) are read during initialization and applied immediately.
|
||||
Settings that affect visual layers and surface interaction (terrain opacity, day/night mode, satellite display style, satellite idle breathing, real satellite altitude, track display, hover tooltip mode, etc.) are read during initialization and applied immediately.
|
||||
|
||||
The surface hover tooltip preference is persisted by `controls.js` as `shared.surfaceHoverInfoMode`, while `main.js` composes the actual tooltip in the globe-surface hover branch. `Country` shows country details only when a country polygon is hit and stays silent over ocean; `Position` shows latitude, longitude, and sampled terrain elevation and clears country-boundary hover; `Full` shows country + position on land and position over ocean.
|
||||
|
||||
The real satellite altitude preference is persisted by `controls.js`, while the rendering state lives in `satellites.js`. When enabled, the real radius from SGP4 is compressed logarithmically into the current Earth visual radius range. When disabled, satellite dots, trails, and predicted orbits all return to the legacy same-sphere display. Toggling this setting must refresh satellite positions and clear trail buffers so a trail never mixes both height models. `maxRealAltitudeOffset = 25` is a visual cap tuned for the current camera and `earthRadius = 100`: GEO / MEO remain clearly higher than LEO, but the highest orbits stay within about 25% beyond the globe radius so selection targets, red trails, and the globe do not feel disconnected.
|
||||
|
||||
SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for the whole future orbit, projecting the inertial orbit plane onto the current globe pose; that keeps the line closed and keeps the visual orbit inclination aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.
|
||||
|
||||
## Current Terrain Pipeline
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ This document records the material, color, opacity, line width, radius offset, a
|
||||
| Earth base specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
|
||||
| Earth base shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
|
||||
| Earth base opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
|
||||
| HD texture radius offset | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.1` | Standalone HD texture sphere radius |
|
||||
| HD texture radius offset | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | Standalone HD texture sphere radius; must keep enough depth separation from the land/ocean base and Earth base sphere to avoid far-zoom z-fighting |
|
||||
| HD texture opacity | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | HD texture `MeshPhongMaterial.opacity` |
|
||||
| HD texture renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
|
||||
| HD texture specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | Reduces specular highlight in direct-light areas to avoid blown-out texture |
|
||||
@@ -78,11 +78,18 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
|
||||
|
||||
| Name | Variable | Current Value | Location / Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Country border data path | `COUNTRY_BOUNDARY_CONFIG.dataPath` | `"/earth/data/countries-admin0.min.geojson"` | GeoJSON input |
|
||||
| Boundary tile manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/earth/data/boundaries/v1/manifest.json"` | Required production PMTiles manifest; missing manifest is an error |
|
||||
| Boundary tile provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"pmtiles-mvt"` | Only PMTiles/MVT is accepted for country boundaries |
|
||||
| PMTiles artifact path | `COUNTRY_BOUNDARY_CONFIG.pmtilesPath` | `"/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"` | Production single-file PMTiles/MVT artifact |
|
||||
| MVT layer names | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0 / boundary_disputed_internal / coastline / claim_line` | Fixed layer names decoded by the PMTiles provider |
|
||||
| Boundary tile base path | `COUNTRY_BOUNDARY_CONFIG.tileBasePath` | `"/earth/data/boundaries/v1/"` | PMTiles manifest base path |
|
||||
| Boundary tile zoom thresholds | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `1.6 -> z5`, `2.8 -> z6`, `3.4 -> z7`, `4.0 -> z8`, `4.6 -> z9`, `5.2 -> z10` | Production PMTiles zoom selection |
|
||||
| Boundary tile cache limit | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `150` | Frontend LRU cache entries for loaded tile geometries |
|
||||
| Boundary tile debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | View-change debounce before requesting visible tiles |
|
||||
| Ocean fill color | local `OCEAN_HEX` | `0x010609` | Land/ocean base canvas background |
|
||||
| Land fill color | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | Land/ocean base canvas land |
|
||||
| Land/ocean base opacity | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` |
|
||||
| Land/ocean base radius offset | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.08` | `country-land-ocean` radius |
|
||||
| Land/ocean base radius offset | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.32` | `country-land-ocean` radius; separated from the Earth base sphere to avoid snow / black block flicker at 50% zoom |
|
||||
| Land/ocean base renderOrder | `COUNTRY_BOUNDARY_CONFIG.landRenderOrder` | `0.86` | `country-land-ocean.renderOrder` |
|
||||
| Land/ocean mask size | `landMaskWidth / landMaskHeight` | `2048 / 1024` | Canvas / DataTexture size |
|
||||
| Country tint color | `COUNTRY_BOUNDARY_CONFIG.tintColor` | `0x0b1830` | Tint when HD texture is off |
|
||||
@@ -91,16 +98,16 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
|
||||
| Border line color | `COUNTRY_BOUNDARY_CONFIG.lineColor` | `0x7fc7ff` | Normal border line |
|
||||
| Border line opacity | `COUNTRY_BOUNDARY_CONFIG.lineOpacity` | `0.58` | Normal border line opacity |
|
||||
| Border dimmed opacity on hover | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | Normal border opacity during hover |
|
||||
| Border line radius offset | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | Normal border line radius; slightly above HD texture `0.10` and below terrain base `0.16` to reduce floating |
|
||||
| Border line radius offset | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | Normal border line radius; line layers rely on renderOrder and independent geometry, not whole-globe shell depth spacing |
|
||||
| Border line renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `2.2` | Normal border line level |
|
||||
| Border hover color | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | Neon red-orange |
|
||||
| Border hover opacity | `COUNTRY_BOUNDARY_CONFIG.hoverLineOpacity` | `1.0` | Hover line opacity |
|
||||
| Border hover radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.14` | Hover line radius; close to the surface but above normal border lines |
|
||||
| Border hover radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.115` | Hover line radius; matches the normal border geometry to avoid double-edge ghosting during highlight changes |
|
||||
| Border hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `2.3` | Hover line level |
|
||||
| Border hover glow opacity | `COUNTRY_BOUNDARY_CONFIG.hoverGlowOpacity` | `0.38` | Glow line opacity |
|
||||
| Border hover glow line width | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | Glow `LineBasicMaterial.linewidth` |
|
||||
| Border hover glow level offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | Glow renderOrder = `2.29` |
|
||||
| Border hover glow radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0.04` | Glow radius = hover radius + 0.04 |
|
||||
| Border hover glow radius offset | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0` | Glow uses the same radius as the hover line to avoid coastline detail misalignment |
|
||||
|
||||
## Real Terrain
|
||||
|
||||
@@ -160,10 +167,13 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
|
||||
|
||||
| Name | Variable | Current Value | Location / Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| Satellite display radius offset | `SATELLITE_CONFIG.displayAltitudeOffset` | `8` | Satellite point position |
|
||||
| Satellite fallback radius offset | `SATELLITE_CONFIG.fallbackAltitudeOffset` | `8` | Legacy same-sphere position when real altitude is disabled or TLE propagation fails |
|
||||
| Satellite altitude compression scale | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 altitude compression; larger values soften high-orbit separation |
|
||||
| Satellite real-altitude cap | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | Altitude clamp for the compressed display mapping, covering GEO-range altitude |
|
||||
| Satellite real-altitude display offset range | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | Compressed offset added to `CONFIG.earthRadius`; `25` is about one quarter of the current globe radius `100`, keeping high-orbit separation visible without pushing GEO/MEO trails too far away |
|
||||
| Satellite dot base pixel size | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | Point shader size |
|
||||
| Satellite backdrop dot scale | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | Backdrop dot size |
|
||||
| Satellite dot opacity range | `dotOpacityMin / dotOpacityMax` | `0.7 / 1.0` | Breathing animation |
|
||||
| Satellite dot opacity range | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | Breathing animation |
|
||||
| Satellite dot breathing speed | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | Dot opacity animation |
|
||||
| Satellite backdrop renderOrder | inline | `5` | `satelliteBackdropPoints.renderOrder` |
|
||||
| Satellite dot renderOrder | inline | `6` | `satellitePoints.renderOrder` |
|
||||
@@ -230,7 +240,9 @@ AIS vessel markers use batched `THREE.Points`, not one `THREE.Sprite` per vessel
|
||||
| Medium color | `BGP_CONFIG.severityColors.medium` | `0xffd166` | Medium-severity event |
|
||||
| Low color | `BGP_CONFIG.severityColors.low` | `0x4dabf7` | Low-severity event |
|
||||
| Collector base color | `BGP_CONFIG.collectorColor` | `0x6db7ff` | Default collector color |
|
||||
| Region color | `BGP_CONFIG.regionColor` | `0x2dd4bf` | Region overlay |
|
||||
| BGP halo neutral tint | `BGP_CONFIG.halo.tintNeutralColor` | `0xffffff` | Broad halos derive from the matching event / collector icon color and blend toward this neutral, keeping the same hue family without becoming identical |
|
||||
| BGP halo icon-color blend | `BGP_CONFIG.halo.tintBlend` | `0.72` | Higher values stay closer to the icon color; currently used by event region halos, collector coverage halos, and collector radar pulse |
|
||||
| Region color | `BGP_CONFIG.regionColor` | `0x2dd4bf` | Legacy region baseline; broad BGP halos now prefer colors derived from the event or collector icon |
|
||||
|
||||
## Celestial and Starfield
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ Note: the layer control panel order and the registration / startup load order ar
|
||||
|
||||
| Order type | Current sequence | Notes |
|
||||
| --- | --- | --- |
|
||||
| Control panel order | Cables → Trails → Satellites → Compute Centers → BGP → Terrain → HD Texture → Cloud Layer → Border Lines → Grid | Controlled by `displayOrder`, sorted by operational relevance. |
|
||||
| Registration / startup load order | Grid → Border Lines / Land-Ocean Base → HD Texture → Cloud Layer → Cables → Compute Centers → BGP → Satellites | Controlled by registration order and `startupPriority`, sorted surface-to-sky; the startup queue reads persisted layer visibility first, skips normal layers explicitly saved as hidden, and HD Texture does not download the texture when disabled; Border Lines are the exception: the land-ocean base always preloads, while the persisted state only controls interactive border lines and hover; Trails and Terrain are dependency/optional display layers and do not participate in normal startup data loading. |
|
||||
| Control panel order | Cables → Satellites → Compute Centers → Vessels → BGP → Terrain → HD Texture → Cloud Layer → Border Lines → Grid | Controlled by `displayOrder`, sorted by operational relevance; satellite trails moved to Settings and are no longer a layer-list item. |
|
||||
| Registration / startup load order | Grid → Border Lines / Land-Ocean Base → HD Texture → Cloud Layer → Cables → Compute Centers → Vessels → BGP → Satellites | Controlled by registration order and `startupPriority`, sorted surface-to-sky; the startup queue reads persisted layer visibility first, skips normal layers explicitly saved as hidden, and HD Texture does not download the texture when disabled; Border Lines are the exception: the land-ocean base always preloads, while the persisted state only controls interactive border lines and hover; Trails and Terrain are dependency/optional display layers and do not participate in normal startup data loading. |
|
||||
|
||||
## Surface Layer Stack
|
||||
|
||||
@@ -17,8 +17,8 @@ Note: the layer control panel order and the registration / startup load order ar
|
||||
| -1 | Earth occluder sphere | `earth.js` | Invisible inner sphere | Writes depth buffer | Occludes objects behind the Earth. |
|
||||
| 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. |
|
||||
| 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. |
|
||||
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off. |
|
||||
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset` | Surface picking target when visible | HD texture always overlays the land/ocean base fill. |
|
||||
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. |
|
||||
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. |
|
||||
| 1 | Atmospheric glow and clouds | `earth.js` | Atmosphere / cloud spheres | Not in normal object selection path | Cloud layer controlled by the "Cloud Layer" toggle. |
|
||||
| 1 | Submarine cables | `cables.js` | `CABLE_CONFIG.line.renderOrder` | Cable picking path | Preserves existing cable layer level. |
|
||||
| 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. |
|
||||
@@ -29,9 +29,9 @@ Note: the layer control panel order and the registration / startup load order ar
|
||||
| 3 | Satellite footprint fill / Iridium coverage ring | `satellites.js`, `iridium-footprint-adapter.js` | `GROUND_FOOTPRINT_RENDER_ORDER` | depth-tested; Iridium adapter fill / ring use the same renderOrder | Footprint above land / texture / terrain and country borders, below compute centers and satellites. |
|
||||
| 3-5 | BGP markers and overlays | `bgp.js` | Each marker's own renderOrder | BGP picking path | Preserves existing BGP visual level. |
|
||||
| 4.5 | Compute centers | `compute-centers.js` | `COMPUTE_CENTER_RENDER_ORDER` | Compute center picking path | Surface facilities, below satellites. |
|
||||
| 5 | Satellite background dot | `satellites.js` | Fixed renderOrder | Screen-space satellite picking | Below satellite dots. |
|
||||
| 6 | Satellite dots | `satellites.js` | Fixed renderOrder | Screen-space satellite picking | Satellite dots above footprints and compute centers. |
|
||||
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets | Satellite overlay path | Used for selected/locked satellite emphasis. |
|
||||
| 5 | Satellite background dot | `satellites.js` | Fixed renderOrder; by default TLE/SGP4 altitude is compressed to `CONFIG.earthRadius + 4..25`; with real altitude disabled or propagation failed, uses `fallbackAltitudeOffset = 8` | Screen-space satellite picking | Below satellite dots. |
|
||||
| 6 | Satellite dots | `satellites.js` | Same compressed / fallback height as satellite backdrop dots | Screen-space satellite picking | Satellite dots above footprints and compute centers. |
|
||||
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw a closed inertial orbit; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. |
|
||||
| 98-100 | Sun / moon halo and sprite | `celestial.js` | Fixed renderOrder | Celestial picking disabled | Foreground celestial sprites. |
|
||||
|
||||
## Toggle Behavior
|
||||
@@ -43,6 +43,18 @@ Note: the layer control panel order and the registration / startup load order ar
|
||||
| Terrain on | Displayed above HD texture, but below country border hover, footprints, satellites, and other emphasis layers. |
|
||||
| Cloud layer | Only controls cloud mesh visibility. |
|
||||
| Border Lines off | Hides only interactive border lines and hover, clearing hover state; the land/ocean base fill remains as the Earth base map. |
|
||||
| Real Satellite Altitude off | Satellite dots, trails, and predicted orbits use the legacy same-sphere height; satellites with missing TLE data or failed propagation also use this fallback height. |
|
||||
|
||||
## Depth Spacing Rules
|
||||
|
||||
The Earth surface is not a single mesh. It is a stack of near-concentric shells: base sphere, land/ocean base, HD texture, terrain, clouds, atmosphere, and the occluder. Radius offsets that look harmless at close zoom can collapse into the same depth-buffer pixels at zoomed-out views such as 50%, causing z-fighting that appears as black blocks, snow, or flicker.
|
||||
|
||||
Maintenance rules:
|
||||
|
||||
- Do not reach first for hiding layers at far zoom. Check neighboring shell `altitudeOffset`, `renderOrder`, `depthTest`, and `depthWrite` first.
|
||||
- Whole-globe overlays such as the land/ocean base and HD texture must keep explicit separation from `CONFIG.earthRadius`; the current stable values are `landAltitudeOffset = 0.32` and `textureOverlayAltitudeOffset = 0.48`.
|
||||
- Any new whole-globe or near-whole-globe surface overlay must be screenshot-verified at 50% zoom and at common close zooms, with no black blocks, snow, flicker, or obvious floating.
|
||||
- If these radii change, update this document and the intent around the constants in `frontend/public/earth/js/constants.js`.
|
||||
|
||||
## Interaction Rules
|
||||
|
||||
|
||||
@@ -55,12 +55,12 @@ tasklist /svc /fi "PID eq 4700"
|
||||
For temporary troubleshooting, you can stop IP Helper from Administrator PowerShell:
|
||||
|
||||
```powershell
|
||||
Stop-Service iphlpsvc
|
||||
Stop-Service iphlpsvc -Force
|
||||
```
|
||||
|
||||
This may affect networking, proxying, or forwarding features. Do not disable it long-term unless you know why it is safe. If the Windows forwarding rule must stay, use a different Planet backend port.
|
||||
This may affect networking, proxying, or forwarding features. Do not disable it long-term unless you know why it is safe. `--allow-lan` now binds `3000` / `8000` / `8010` directly, so persistent portproxy is no longer required.
|
||||
|
||||
If the script prints `failed-stop-service` or `failed-stop-process`, the current shell does not have permission to clear the Windows listener. Startup stops immediately instead of launching the backend into the same port conflict.
|
||||
If the script prints `Windows 侧端口 ... 存在监听者`, or Vite reports `Port 3000 is already in use` followed by `Windows listener ... services=iphlpsvc`, an old Windows listener still owns the port. The script requests Administrator PowerShell cleanup for that port. If the automatic cleanup is canceled, inspect `netsh interface portproxy show all`, delete the matching `listenport` rule, confirm the PID and services with `netstat` / `tasklist` if no portproxy rule exists, and temporarily run `Stop-Service iphlpsvc -Force` when appropriate. After old rules are gone, rerun `./planet.sh restart --allow-lan`; LAN devices still use `3000` / `8000` / `8010`.
|
||||
|
||||
### Which startup flags change default ports?
|
||||
|
||||
@@ -87,6 +87,7 @@ Check in this order before changing firewall rules:
|
||||
# In WSL or the shell running Planet
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
Then verify from Windows PowerShell:
|
||||
@@ -94,6 +95,7 @@ Then verify from Windows PowerShell:
|
||||
```powershell
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
If both localhost checks pass but a phone or another computer cannot connect, start with LAN enabled:
|
||||
@@ -108,22 +110,28 @@ The flag must be written as `--allow-lan`. `allowlan` or `--allowlan` is not rec
|
||||
./planet.sh restart -f 3000 --allow-lan
|
||||
```
|
||||
|
||||
If `ss -ltnp` shows the frontend listening on `0.0.0.0:3000`, but `Test-NetConnection <Windows LAN IP> -Port 3000` still fails from Windows PowerShell, the problem is usually Windows-side forwarding or firewall policy rather than Vite or `.zshrc`.
|
||||
If `ss -ltnp` shows the frontend listening on `0.0.0.0:3000`, but `Test-NetConnection <Windows LAN IP> -Port 3000` still fails from Windows PowerShell, the problem is usually Windows-side port ownership, stale `portproxy`, or firewall policy rather than Vite or `.zshrc`.
|
||||
|
||||
For traditional WSL NAT networking, configure portproxy and firewall from Administrator PowerShell:
|
||||
`./planet.sh start --allow-lan` directly exposes `3000` / `8000` / `8010` and checks port availability, stale `portproxy`, and Windows Firewall before startup. If a Windows-side listener owns a port, the script requests Administrator PowerShell cleanup. When inbound allow rules are missing, it also triggers a UAC Administrator PowerShell request to create them. If the automatic request is canceled, clean up manually:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=3000 connectaddress=127.0.0.1 connectport=3000
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8000 connectaddress=127.0.0.1 connectport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=3000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8010
|
||||
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 3000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8010" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8010
|
||||
```
|
||||
|
||||
LAN devices should use the Windows external port, for example `http://<Windows LAN IP>:3000/earth`.
|
||||
|
||||
If `wslinfo --networking-mode` prints `mirrored`, also check Hyper-V firewall. Even when ordinary Windows Firewall rules exist, Hyper-V firewall can still block external devices from reaching WSL. From Administrator PowerShell, allow the required ports:
|
||||
|
||||
```powershell
|
||||
New-NetFirewallHyperVRule -Name "Planet-Frontend-3000" -DisplayName "Planet Frontend 3000" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 3000 -Action Allow
|
||||
New-NetFirewallHyperVRule -Name "Planet-Backend-8000" -DisplayName "Planet Backend 8000" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 8000 -Action Allow
|
||||
New-NetFirewallHyperVRule -Name "Planet-AIProvider-8010" -DisplayName "Planet AI Provider 8010" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 8010 -Action Allow
|
||||
```
|
||||
|
||||
Use these commands to inspect the current Hyper-V firewall state:
|
||||
@@ -321,6 +329,14 @@ Collecting and saving are two separate actions. Candidates can be previewed on E
|
||||
|
||||
Compute-center saves write to `compute_center_locations` and refresh the layer. Records with no candidate stay in the unresolved list; Planet does not fabricate a location from a country center or hard-coded hint.
|
||||
|
||||
### Why are satellites no longer on one sphere?
|
||||
|
||||
Earth enables "Real Satellite Altitude" by default. Satellite positions still come from TLE/SGP4, but altitude is compressed for display: LEO satellites stay close to the globe, while higher-orbit satellites render farther out without leaving the normal view. The maximum display offset is `25`, about one quarter of the current globe radius; this is a readability compromise that separates GEO / MEO / LEO without drawing real kilometers to scale. This setting also affects satellite trails and the predicted orbit shown after locking a satellite.
|
||||
|
||||
Turn off "Real Satellite Altitude" in Earth Settings to restore the legacy same-sphere satellite display. Satellites with missing TLE data or failed propagation still fall back to the legacy fixed height, so they do not disappear just because a real altitude cannot be computed.
|
||||
|
||||
Low-inclination high-orbit satellites should stay near the equator or a fixed longitude band, not form a near north-south ring. Earth converts the SGP4 inertial position to Earth-fixed coordinates for the current dot; the locked predicted orbit fixes the current globe pose and draws one inertial orbit, so it should close and preserve the correct inclination. If a future details card shows inclination near `0°` but the predicted orbit looks polar, check the ECI/TEME-to-ECF conversion and whether the predicted orbit accidentally uses per-sample `gstime`.
|
||||
|
||||
### Why does Motion Debug not show camera video?
|
||||
|
||||
With the Browser Camera source, the debug panel shows the local browser camera preview and draws the skeleton over it. If `Skeleton Only` is enabled, the video preview is hidden and the panel keeps only the dark canvas plus red/green skeleton.
|
||||
|
||||
@@ -229,7 +229,7 @@ A single globe view of: BGP events and observations, satellites and tracks, cabl
|
||||
|
||||
### Layer Control
|
||||
|
||||
The right-side layer panel toggles layers. Common layers: graticule, country boundaries, high-res tiles, atmospheric clouds, cables, compute centers, BGP, satellites, AIS vessels, tracks, terrain.
|
||||
The right-side layer panel toggles layers. Common layers: graticule, country boundaries, high-res tiles, atmospheric clouds, cables, compute centers, BGP, satellites, AIS vessels, terrain. Satellite tracks are no longer listed as a standalone layer; they are controlled from Settings.
|
||||
|
||||
Dependencies:
|
||||
|
||||
@@ -255,7 +255,11 @@ Candidates preview on Earth directly. Saving a compute-center candidate writes t
|
||||
|
||||
### Settings
|
||||
|
||||
The settings panel covers: rotate / cruise / motion mode, cruise modules (BGP/news/compute centers/vessels/cables/satellites), view (satellite display style, day-night mode, panel toggles), motion debug mode / input source / skeleton-only, default globe size, terrain opacity, reset.
|
||||
The settings panel covers: rotate / cruise / motion mode, cruise modules (BGP/news/compute centers/vessels/cables/satellites), view (satellite display style, hover tooltip, satellite idle breathing, real satellite altitude, track display, compact dots, day-night mode, panel toggles), motion debug mode / input source / skeleton-only, default globe size, terrain opacity, reset.
|
||||
|
||||
"Real Satellite Altitude" is enabled by default: satellite positions use a compressed display height based on TLE/SGP4 orbital altitude. LEO satellites remain close to the globe, while high-orbit satellites render farther out without leaving the normal view. The high-orbit display height is capped at about one quarter of the globe radius, so GEO / MEO objects remain visually separated from LEO without spreading trails and selection targets too far apart. Turning it off restores the legacy same-sphere satellite display. "Track Display" controls satellite trail visibility; trails are unavailable while the satellite layer is hidden.
|
||||
|
||||
"Hover Tooltip" controls the tooltip shown when the pointer hovers over the globe surface: `Country` shows country details only when land matches a country, and stays silent over oceans such as the Pacific; `Position` shows latitude, longitude, and elevation over land and ocean; `Full` is the default and shows country + position over land and position over ocean.
|
||||
|
||||
These settings live in browser local storage; switching browsers or clearing site data resets them.
|
||||
|
||||
@@ -310,6 +314,7 @@ Mobile uses a drawer layout: layer control moves into a drawer; search/settings/
|
||||
- **Earth does not open**: confirm the frontend is online; if not on port `3000`, use the port printed by the startup log
|
||||
- **Layers have no data**: open `/datasources` to check source status, collected-record state, and the latest run result; then `/data` or `/bgp` for records
|
||||
- **Satellites / BGP / cables load slowly**: those layers depend on backend APIs and external data sources; the first load waits for startup tasks
|
||||
- **Satellites are not all on one shell**: this is the default compressed real-altitude display. Disable "Real Satellite Altitude" in Settings to return to the legacy same-sphere view
|
||||
|
||||
## Docs Site
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ Frontend startup now has an additional pre-start cleanup retry layer:
|
||||
- `PORT_PRESTART_RETRIES`: defaults to 3 attempts.
|
||||
- `PORT_PRESTART_RETRY_INTERVAL`: defaults to 2 seconds.
|
||||
|
||||
`kill_port_if_requested()` first cleans listener PIDs visible in the current environment. It only checks for Windows-side listeners when the script detects WSL, no local listener PID is visible, and the port still cannot bind. In that WSL-only path it tries to stop the owning Windows service or force-stop the owning process through PowerShell. If permissions are missing, or a system service such as `iphlpsvc` refuses to stop, the script prints the Windows listener details and stops startup immediately instead of launching the service into the same port error. Non-WSL environments do not run the Windows cleanup path. At that point, use Administrator PowerShell to clear the portproxy/service ownership, or choose another port.
|
||||
`kill_port_if_requested()` first cleans listener PIDs visible in the current environment. It only checks for Windows-side listeners when the script detects WSL, no local listener PID is visible, and the port still cannot bind. In that WSL-only path it requests Administrator PowerShell to delete stale `portproxy` rules, stop services that own the port, or force-stop the owning process. If the administrator request is canceled, or a system service such as `iphlpsvc` refuses to stop, the script prints the Windows listener details and Administrator PowerShell recovery commands, then stops startup immediately instead of launching the service into the same port error. If the frontend Vite process only discovers `Port 3000 is already in use` after launch, the script prints the same Windows listener recovery commands. Non-WSL environments do not run the Windows cleanup path. `--allow-lan` now exposes `3000` / `8000` / `8010` directly and no longer starts an extra Windows forwarding process; old persistent portproxy rules should be removed.
|
||||
|
||||
## Issue 4: `restart` Behavior
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ Useful for:
|
||||
- Demoing Earth from a phone or tablet
|
||||
- Other LAN machines reaching the same dev instance
|
||||
|
||||
`--allow-lan` only makes the frontend and backend listen on `0.0.0.0`. When Planet runs in WSL, Windows can usually reach it through `localhost`, but other LAN machines hitting `http://<Windows LAN IP>:3000` still need Windows port forwarding and firewall rules.
|
||||
`--allow-lan` directly exposes the frontend, backend, and AI Provider from the development machine: frontend `3000`, backend `8000`, and AI Provider `8010`. Before startup, the script checks all three ports. If WSL/Linux cannot release a port and a Windows-side listener or stale `portproxy` rule owns it, the script requests Administrator PowerShell cleanup. When Planet runs in WSL, Windows can usually reach it through `localhost`; other LAN machines reaching the Windows LAN IP still need Windows Firewall allow rules.
|
||||
|
||||
Diagnose in this order:
|
||||
|
||||
@@ -128,19 +128,24 @@ Diagnose in this order:
|
||||
# From the shell running Planet
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
ss -ltnp | grep -E ':3000|:8000'
|
||||
curl http://localhost:8010/health
|
||||
ss -ltnp | grep -E ':3000|:8000|:8010'
|
||||
```
|
||||
|
||||
If WSL shows `0.0.0.0:3000` / `0.0.0.0:8000` but the LAN IP still fails, configure Windows from an elevated PowerShell:
|
||||
If the services are running but the LAN IP still fails, first remove stale `portproxy` rules and confirm Windows Firewall allows the ports. The script checks this automatically and requests Administrator PowerShell when needed. Manual fallback commands:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=3000 connectaddress=127.0.0.1 connectport=3000
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8000 connectaddress=127.0.0.1 connectport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=3000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8010
|
||||
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 3000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8010" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8010
|
||||
```
|
||||
|
||||
LAN devices should use the Windows external ports, for example `http://<Windows LAN IP>:3000/earth`, `http://<Windows LAN IP>:8000/health`, and `http://<Windows LAN IP>:8010/health`.
|
||||
|
||||
## AI Provider Environment and Builds
|
||||
|
||||
AI Provider runtime configuration lives in two places:
|
||||
@@ -236,6 +241,16 @@ uv sync
|
||||
uv run pytest backend/tests/test_otp_service.py
|
||||
```
|
||||
|
||||
## Earth Boundary PMTiles Operations
|
||||
|
||||
1. In Collector Settings, configure endpoints, headers/auth, `config.target_schema=earth_boundary_source`, license, and mapping for `Earth Admin-0 Boundaries`, `Earth Coastline`, and `Earth Claim Lines`.
|
||||
2. In the data-source console, collect those three sources first. Each successful source writes the full artifact to `data/earth-boundary-sources/<collector>/<sha256>.*` and stores sha256, feature count, artifact path, and sample properties.
|
||||
3. After all three sources succeed, collect `Earth PMTiles Builder`. If any source is missing, it fails as "not ready" and does not update Earth boundaries.
|
||||
4. The builder requires `tippecanoe` and `pmtiles` on PATH. Missing tools fail the task with a clear message.
|
||||
5. A successful production build outputs `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles` and its manifest.
|
||||
6. After deployment, open Earth, enable "Border Lines", and inspect China's southeast coast, Taiwan, Hainan, the South China Sea, Zangnan, Kosovo, and Gaza for hover behavior and boundary policy.
|
||||
7. If PMTiles loading fails, Earth reports a boundary-layer error and does not draw legacy low-precision borders. Troubleshoot in this order: browser Network range requests for PMTiles, manifest `tileProvider: "pmtiles-mvt"`, Nginx static serving for `.pmtiles`, and artifact path / sha256 consistency with the manifest.
|
||||
|
||||
## Related Docs
|
||||
|
||||
- [planet.sh Startup Mechanism](/home/ray/dev/linkong/planet/docs/technical/en/ops-planet-sh-startup.md)
|
||||
|
||||
@@ -48,7 +48,7 @@ Once in, verify:
|
||||
- Search finds cables, satellites, compute centers, BGP events
|
||||
- Compute-center and BGP collector detail cards can collect coordinate candidates and preview them on Earth
|
||||
- Mouse drag, wheel zoom, and the zoom percentage indicator work
|
||||
- The settings panel can switch rotate / cruise / motion modes
|
||||
- The settings panel can switch rotate / cruise / motion modes; view settings can switch hover tooltip content, and satellite settings can toggle real-altitude layering and track display
|
||||
|
||||
## 5. Recover a Lost Password
|
||||
|
||||
|
||||
@@ -87,9 +87,17 @@ async def run(self, db):
|
||||
| Space-Track TLE | satellite_tle | 卫星轨道 TLE 数据 | 依采集器配置 |
|
||||
| BarentsWatch AIS | vessel | 船只位置、航速、航向、MMSI 等 AIS 数据 | 依采集器配置 |
|
||||
| AISStream Vessels | vessel_ais | AIS WebSocket 实时流,写入原始观测层并由聚合接口展示 | 依采集器配置 |
|
||||
| Earth Admin-0 Boundaries | earth_admin0_boundaries | 从配置 endpoint 下载国家级边界源,保存 artifact 并写入 `earth_boundary_source` manifest 记录 | 依采集器配置 |
|
||||
| Earth Coastline | earth_coastline | 从配置 endpoint 下载海岸线源,保存 artifact 并写入 `earth_boundary_source` manifest 记录 | 依采集器配置 |
|
||||
| Earth Claim Lines | earth_claim_lines | 从配置 endpoint 下载主张线源,保存 artifact 并写入 `earth_boundary_source` manifest 记录 | 依采集器配置 |
|
||||
| Earth PMTiles Builder | earth_boundary_tiles | 读取三类 Earth 边界源采集结果并构建 / 登记 PMTiles 产物 | 依采集器配置 |
|
||||
|
||||
AIS 船只类采集器和其它 `CollectedData` 采集器的落库路径不同。BarentsWatch、AISStream 和自定义 `vessel_ais` 源都会进入 AIS 原始观测层,随后由聚合服务合并成 Earth 船只图层使用的 GeoJSON 和详情数据。这样做可以保留来源、传输方式、字段冲突和观测时间,避免某个实时源直接覆盖最终展示表。
|
||||
|
||||
Earth 边界现在拆成三个真实源采集器和一个下游构建器。`earth_admin0_boundaries`、`earth_coastline`、`earth_claim_lines` 都读取后台 Collector Settings 里的 endpoint、headers、auth 和 `config.target_schema=earth_boundary_source`,点击采集时会真实请求 endpoint,保存完整响应到 `data/earth-boundary-sources/<collector>/<sha256>.*`,并在 `CollectedData` 中写入 sha256、feature count、license、artifact path、sample properties 和 mapping 信息。
|
||||
|
||||
`earth_boundary_tiles` 不再代表源数据采集。它只读取上述三类源的最新成功记录;缺任一源时任务失败并显示“未就绪”,不会登记“4 条高精度瓦片”。三类源齐全后,它会调用 `tippecanoe` / `pmtiles` 生成 `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles`;本机缺少这些工具时任务失败并说明缺失工具。国界不再有旧低精度兜底。
|
||||
|
||||
TOP500 和 Epoch AI 算力数据的公开源不总是提供可用经纬度。Earth 统一算力中心接口在主地图启动链路中只使用源数据自带坐标或 `compute_center_locations` 维表坐标;缺少坐标的记录会进入 `unresolved`,不会通过本地注册表、国家质心或猜测城市自动渲染。用户手动采集候选时,后端会用源字段调用 ROR 组织注册 API 和 Nominatim/OpenStreetMap 在线搜索;候选经前端保存后写入 `compute_center_locations`,后续地图刷新再从维表渲染。
|
||||
|
||||
## 四、数据格式 (统一存储到 CollectedData 表)
|
||||
@@ -244,7 +252,8 @@ backend/app/services/collectors/
|
||||
├── peeringdb.py # PeeringDB采集器
|
||||
├── telegeraphy.py # TeleGeography海底光缆采集器
|
||||
├── vessel_ais.py # BarentsWatch AIS 船只采集器
|
||||
└── aisstream.py # AISStream WebSocket 船只采集器
|
||||
├── aisstream.py # AISStream WebSocket 船只采集器
|
||||
└── earth_boundaries.py # Earth 国界源校验和静态瓦片 artifact 采集器
|
||||
|
||||
backend/app/services/
|
||||
├── custom_datasource_runtime.py # 自定义 REST / WebSocket 映射运行时
|
||||
|
||||
@@ -309,6 +309,8 @@ GET /api/v1/vessels/snapshot?bbox=lon_min,lat_min,lon_max,lat_max&zoom=12&limit=
|
||||
|
||||
自定义源现在不是独立的新数据孤岛,而是作为内置数据源的补充源写入目标 schema。当前最完整的目标是 `vessel_ais`:自定义 REST 或 WebSocket 源经过确定性 mapping 后写入 AIS raw observations,再通过 `vessels` WebSocket channel 推送给 Earth。
|
||||
|
||||
Earth 高精度边界使用同一套目标 schema 机制。`earth_boundary_source` 承接 `earth_admin0_boundaries`、`earth_coastline`、`earth_claim_lines` 三类源的映射结果;完整 GeoJSON / JSON 原文保存为 artifact,数据库只保存 source kind、sha256、feature count、license、artifact path 和 sample properties,避免把大型几何塞进单行记录。
|
||||
|
||||
### 配置语义
|
||||
|
||||
关键字段:
|
||||
@@ -318,7 +320,7 @@ GET /api/v1/vessels/snapshot?bbox=lon_min,lat_min,lon_max,lat_max&zoom=12&limit=
|
||||
- `auth_type`:`none`、`bearer`、`api_key`、`basic`。
|
||||
- `headers`:静态请求头。
|
||||
- `auth_config`:token、API key、basic 用户名密码,API key 支持 header 或 query。
|
||||
- `config.target_schema`:例如 `vessel_ais`。
|
||||
- `config.target_schema`:例如 `vessel_ais` 或 `earth_boundary_source`。
|
||||
- `config.delivery_mode`:REST 默认 `polling`,WebSocket 默认 `realtime_stream`。
|
||||
- `config.merge_target_source`:记录该自定义源补充哪个内置数据,例如 `barentswatch_vessels`。
|
||||
|
||||
|
||||
@@ -157,6 +157,7 @@ BGP 模块正在从一个只展示异常的演示功能,演进为分层观测
|
||||
- 由符号驱动的事件核心
|
||||
- 向外扩散的环形脉冲
|
||||
- 相比旧版 Earth 更少的弥散 glow
|
||||
- 事件区域 halo、collector coverage halo 和雷达 pulse 从各自图标色派生浅色调,而不是使用固定青绿色;红色高危事件、橙色活跃 collector 和蓝色 idle collector 保持各自色相一致,面状光晕则比图标更轻
|
||||
7. 右侧统计现在显示:
|
||||
- BGP events
|
||||
- collector count
|
||||
|
||||
@@ -123,12 +123,16 @@ Browser Camera provider 的手势识别管线在 [motion-browser-provider.js](/h
|
||||
|
||||
- [earth.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/earth.js)
|
||||
- [terrain.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/terrain.js)
|
||||
- [country-boundaries.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/country-boundaries.js)
|
||||
|
||||
职责:
|
||||
|
||||
- 地球球体、云层、大气
|
||||
- 真实地形 mesh
|
||||
- terrain tile 拉取、解码、位移、着色
|
||||
- 海陆基座与国界底图的整球 overlay
|
||||
|
||||
Earth 地表是多层近似同心球,不是单一 mesh。`earth.js` 的基座球、高清材质 overlay、云层/大气,以及 `country-boundaries.js` 的海陆基座都需要明确半径间距。远距视图下 GPU 深度精度会下降,相邻 shell 过近会 z-fighting,表现为黑色闪烁块或雪花。当前稳定策略是让海陆基座使用 `landAltitudeOffset = 0.32`,高清材质使用 `textureOverlayAltitudeOffset = 0.48`;后续新增或调整整球地表 overlay 时,必须同步检查 [Earth 渲染图层顺序](/home/ray/dev/linkong/planet/docs/technical/zh/earth-render-layer-order.md),并在 50% 缩放视图验证。
|
||||
|
||||
### 7. 图层模块
|
||||
|
||||
@@ -419,11 +423,19 @@ Earth 设置面板当前由 [controls.js](/home/ray/dev/linkong/planet/frontend/
|
||||
- 旋转模式
|
||||
- 地球默认大小(作为重置视角、缩放重置和巡航视图的默认 zoom 真源)
|
||||
- HUD 面板显示/隐藏
|
||||
- 图层控制开关:`地形 / 卫星 / 轨迹 / 海缆 / BGP`
|
||||
- 图层控制开关:`地形 / 卫星 / 海缆 / BGP`
|
||||
- 卫星显示偏好:`卫星显示风格 / 卫星呼吸闪烁 / 真实卫星高度 / 轨迹显示`
|
||||
- 地表 hover 提示偏好:`国家 / 位置 / 完整`
|
||||
- 地形透明度
|
||||
|
||||
也就是说,Earth 设置不是一次性 UI 状态了,而是本地设备级偏好。后续如果再加入新的设置项,应优先接入同一条持久化链,而不是各自散着写 `localStorage`。
|
||||
|
||||
地表 hover 提示由 `controls.js` 持久化为 `shared.surfaceHoverInfoMode`,实际 tooltip 在 `main.js` 的地表 hover 分支组合。`国家` 模式只在命中国家时显示国家信息,海洋区域不显示地表 tooltip;`位置` 模式只显示纬度、经度和地形采样海拔,并清除国家边界 hover;`完整` 模式在陆地显示国家 + 位置,在海洋显示位置。
|
||||
|
||||
卫星真实高度开关由 `controls.js` 持久化,实际渲染状态在 `satellites.js`。开启时,SGP4 得到的真实半径会按对数压缩到当前 Earth 视觉半径范围;关闭时,卫星点、轨迹和预测轨道都回到旧版同层球面。切换时必须刷新卫星位置并清理轨迹缓存,避免同一条轨迹混入两个高度模型。`maxRealAltitudeOffset = 25` 是当前相机和 `earthRadius = 100` 下的视觉上限:它让 GEO / MEO 比 LEO 明显更高,但把最高轨道控制在地球半径外约 25%,避免选择点、红色轨迹和主体地球之间出现过大的空场。
|
||||
|
||||
SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来一圈惯性轨道投到当前地球姿态上显示,因此会闭合,并且轨道面倾角应与详情卡一致。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。
|
||||
|
||||
## 当前地形链路
|
||||
|
||||
真实地形首次启用会慢,原因不只是一个:
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
| Earth 基座 specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
|
||||
| Earth 基座 shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
|
||||
| Earth 基座 opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
|
||||
| 高清材质半径偏移 | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.1` | 独立高清材质球半径 |
|
||||
| 高清材质半径偏移 | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | 独立高清材质球半径;必须与海陆基座和地球基座保持足够深度间距,避免远距 z-fighting |
|
||||
| 高清材质透明度 | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | 高清材质 `MeshPhongMaterial.opacity` |
|
||||
| 高清材质 renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
|
||||
| 高清材质 specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | 降低直射区域镜面高光,避免贴图死白 |
|
||||
@@ -84,11 +84,18 @@
|
||||
|
||||
| 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 国界数据路径 | `COUNTRY_BOUNDARY_CONFIG.dataPath` | `"/earth/data/countries-admin0.min.geojson"` | GeoJSON 输入 |
|
||||
| 国界瓦片 manifest | `COUNTRY_BOUNDARY_CONFIG.tileManifestPath` | `"/earth/data/boundaries/v1/manifest.json"` | 必需的生产 PMTiles manifest;缺失即报错 |
|
||||
| 国界瓦片 provider | `COUNTRY_BOUNDARY_CONFIG.tileProvider` | `"pmtiles-mvt"` | 国界只接受 PMTiles/MVT |
|
||||
| PMTiles 产物路径 | `COUNTRY_BOUNDARY_CONFIG.pmtilesPath` | `"/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"` | 生产单文件 PMTiles/MVT artifact |
|
||||
| MVT 图层名 | `COUNTRY_BOUNDARY_CONFIG.mvtLayerNames` | `boundary_admin0 / boundary_disputed_internal / coastline / claim_line` | PMTiles provider 解码时读取的固定 layer 名 |
|
||||
| 国界瓦片基础路径 | `COUNTRY_BOUNDARY_CONFIG.tileBasePath` | `"/earth/data/boundaries/v1/"` | PMTiles manifest 基础路径 |
|
||||
| 国界瓦片缩放阈值 | `COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds` | `1.6 -> z5`, `2.8 -> z6`, `3.4 -> z7`, `4.0 -> z8`, `4.6 -> z9`, `5.2 -> z10` | 生产 PMTiles zoom 选择 |
|
||||
| 国界瓦片缓存上限 | `COUNTRY_BOUNDARY_CONFIG.tileCacheLimit` | `150` | 前端已加载瓦片几何的 LRU 缓存条目数 |
|
||||
| 国界瓦片 debounce | `COUNTRY_BOUNDARY_CONFIG.tileDebounceMs` | `180` | 视野变化后请求可见瓦片前的防抖时间 |
|
||||
| 海洋填充色 | local `OCEAN_HEX` | `0x010609` | 海陆基座 canvas 背景 |
|
||||
| 陆地填充色 | `COUNTRY_BOUNDARY_CONFIG.landColor` | `0x080f1b` | 海陆基座 canvas 陆地 |
|
||||
| 海陆基座透明度 | `COUNTRY_BOUNDARY_CONFIG.landOpacity` | `1.0` | `MeshBasicMaterial.opacity` |
|
||||
| 海陆基座半径偏移 | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.08` | `country-land-ocean` 半径 |
|
||||
| 海陆基座半径偏移 | `COUNTRY_BOUNDARY_CONFIG.landAltitudeOffset` | `0.32` | `country-land-ocean` 半径;与地球基座拉开以避免 50% 缩放时雪花/黑块闪烁 |
|
||||
| 海陆基座 renderOrder | `COUNTRY_BOUNDARY_CONFIG.landRenderOrder` | `0.86` | `country-land-ocean.renderOrder` |
|
||||
| 海陆 mask 尺寸 | `landMaskWidth / landMaskHeight` | `2048 / 1024` | canvas / DataTexture 尺寸 |
|
||||
| 国界 tint 颜色 | `COUNTRY_BOUNDARY_CONFIG.tintColor` | `0x0b1830` | 高清材质关闭时 tint |
|
||||
@@ -97,16 +104,16 @@
|
||||
| 国界线颜色 | `COUNTRY_BOUNDARY_CONFIG.lineColor` | `0x7fc7ff` | 普通国界线 |
|
||||
| 国界线透明度 | `COUNTRY_BOUNDARY_CONFIG.lineOpacity` | `0.58` | 普通国界线 opacity |
|
||||
| 国界线 hover 时压暗透明度 | `COUNTRY_BOUNDARY_CONFIG.dimmedLineOpacity` | `0.18` | hover 时普通国界线 opacity |
|
||||
| 国界线半径偏移 | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | 普通国界线半径;略高于高清材质 `0.10`,低于地形基准 `0.16`,减少悬浮感 |
|
||||
| 国界线半径偏移 | `COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset` | `0.115` | 普通国界线半径;线层靠 renderOrder 和独立 geometry 叠加,不作为整球基座深度间距参考 |
|
||||
| 国界线 renderOrder | `COUNTRY_BOUNDARY_CONFIG.lineRenderOrder` | `2.2` | 普通国界线层级 |
|
||||
| 国界 hover 颜色 | `COUNTRY_BOUNDARY_CONFIG.hoverLineColor` | `0xff3b1f` | 霓虹红橘 |
|
||||
| 国界 hover 透明度 | `COUNTRY_BOUNDARY_CONFIG.hoverLineOpacity` | `1.0` | hover 实线 opacity |
|
||||
| 国界 hover 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.14` | hover 实线半径;贴近地表但高于普通国界线 |
|
||||
| 国界 hover 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset` | `0.115` | hover 实线半径;与普通国界线同源几何对齐,避免高亮切换时出现重影 |
|
||||
| 国界 hover renderOrder | `COUNTRY_BOUNDARY_CONFIG.hoverLineRenderOrder` | `2.3` | hover 实线层级 |
|
||||
| 国界 hover glow 透明度 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowOpacity` | `0.38` | glow 线 opacity |
|
||||
| 国界 hover glow 线宽 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowLineWidth` | `3` | glow `LineBasicMaterial.linewidth` |
|
||||
| 国界 hover glow 层级偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRenderOrderOffset` | `0.01` | glow renderOrder = `2.29` |
|
||||
| 国界 hover glow 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0.04` | glow 半径 = hover 半径 + 0.04 |
|
||||
| 国界 hover glow 半径偏移 | `COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset` | `0` | glow 与 hover 实线共用半径,避免海岸细节处双线错位 |
|
||||
|
||||
## 真实地形
|
||||
|
||||
@@ -166,10 +173,13 @@
|
||||
|
||||
| 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| 卫星显示半径偏移 | `SATELLITE_CONFIG.displayAltitudeOffset` | `8` | 卫星点位置 |
|
||||
| 卫星 fallback 半径偏移 | `SATELLITE_CONFIG.fallbackAltitudeOffset` | `8` | 关闭真实高度或 TLE 传播失败时的旧版同层球面位置 |
|
||||
| 卫星真实高度压缩尺度 | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 高度压缩映射,数值越大高轨差异越温和 |
|
||||
| 卫星真实高度上限 | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | 压缩映射的高度截断,覆盖 GEO 附近高度 |
|
||||
| 卫星真实高度显示偏移范围 | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | 压缩后映射到 `CONFIG.earthRadius + offset`;`25` 约为当前地球半径 `100` 的四分之一,用于保留高轨分层同时避免 GEO/MEO 轨迹离主体过远 |
|
||||
| 卫星点基础像素大小 | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | 点 shader size |
|
||||
| 卫星背景点缩放 | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | 背景点大小 |
|
||||
| 卫星点透明度范围 | `dotOpacityMin / dotOpacityMax` | `0.7 / 1.0` | 呼吸动画 |
|
||||
| 卫星点透明度范围 | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | 呼吸动画 |
|
||||
| 卫星点呼吸速度 | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | 点 opacity 动画 |
|
||||
| 卫星背景点颜色 | inline | `0x0b1626` | backdrop point baseColor |
|
||||
| 卫星背景点透明度 | inline | `0.42` | backdrop point opacity |
|
||||
@@ -249,7 +259,9 @@ AIS 船只普通态使用批量 `THREE.Points`,不是逐船 `THREE.Sprite`。
|
||||
| medium 颜色 | `BGP_CONFIG.severityColors.medium` | `0xffd166` | 中危事件 |
|
||||
| low 颜色 | `BGP_CONFIG.severityColors.low` | `0x4dabf7` | 低危事件 |
|
||||
| collector 基础色 | `BGP_CONFIG.collectorColor` | `0x6db7ff` | collector 默认色 |
|
||||
| region 色 | `BGP_CONFIG.regionColor` | `0x2dd4bf` | 区域覆盖 |
|
||||
| BGP 光晕浅色基准 | `BGP_CONFIG.halo.tintNeutralColor` | `0xffffff` | 面状 halo 先取对应事件/collector 图标色,再向该中性色混合,保持同色调但不完全同色 |
|
||||
| BGP 光晕图标色混合比例 | `BGP_CONFIG.halo.tintBlend` | `0.72` | 值越高越接近图标色;当前用于事件区域 halo、collector coverage halo 和 collector radar pulse |
|
||||
| region 色 | `BGP_CONFIG.regionColor` | `0x2dd4bf` | 区域覆盖旧基准;新的面状 BGP halo 优先从事件或 collector 图标色派生 |
|
||||
| BGP ring 缩放 | `BGP_CONFIG.ring.scaleA / scaleB` | `2.5 / 3.4` | anomaly ring |
|
||||
| BGP ring 透明度 | `BGP_CONFIG.ring.opacity` | `0.5` | anomaly ring |
|
||||
| collector marker renderOrder | local `BGP_COLLECTOR_RENDER_ORDER` | `4.4` | 观测站主图标,与船只同层 |
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
| 顺序类型 | 当前顺序 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 控制面板顺序 | 海缆 → 轨迹 → 卫星 → 算力中心 → 船只 → BGP → 地形 → 高清材质 → 大气云图 → 国界线 → 经纬线 | 由 `displayOrder` 控制,按操作关注度排列。 |
|
||||
| 控制面板顺序 | 海缆 → 卫星 → 算力中心 → 船只 → BGP → 地形 → 高清材质 → 大气云图 → 国界线 → 经纬线 | 由 `displayOrder` 控制,按操作关注度排列;卫星轨迹已迁到设置面板,不再作为图层列表项。 |
|
||||
| 注册 / 启动加载顺序 | 经纬线 → 国界线 / 海陆基座 → 高清材质 → 大气云图 → 海缆 → 算力中心 → 船只 → BGP → 卫星 | 由注册顺序和 `startupPriority` 控制,按地表到天空排列;启动队列会先读取保存的图层可见状态,明确关闭的普通图层不预加载,高清材质关闭时不下载贴图;国界线图层例外,海陆基座始终预加载,保存状态只控制可交互国界线和 hover;轨迹和地形是依赖/可选显示层,不参与常规启动数据加载。 |
|
||||
|
||||
## 地表图层栈
|
||||
@@ -18,23 +18,23 @@
|
||||
| -1 | Earth 遮挡球 | `earth.js` | 地球内侧不可见球 | 写入深度 | 遮挡地球背面的对象。 |
|
||||
| 0 | Earth 基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 |
|
||||
| 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset` | 禁用 raycast | 高清材质关闭时使用。 |
|
||||
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用。 |
|
||||
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充。 |
|
||||
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 |
|
||||
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 |
|
||||
| 1 | 大气辉光和云图 | `earth.js` | 大气 / 云层球 | 不走普通对象选择路径 | 云图由“大气云图”图层开关控制。 |
|
||||
| 1 | 海缆 / 登陆点 | `cables.js` | 海缆线和登陆点都使用 `renderOrder = 1`;半径偏移都为 `0.2`;登陆点是专用 `THREE.Sprite` 黄色扁平球 | 海缆走海缆拾取路径;登陆点 `depthTest: false` 保持球体完整,并用相机到球心的球体遮挡判断避免背面穿透 | 登陆点和海缆同层贴地,避免地表设施层的凌空感。 |
|
||||
| 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 |
|
||||
| 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 |
|
||||
| 2.2 | 国界线 | `country-boundaries.js` | `lineAltitudeOffset = 0.115` | `depthTest: true`,禁用 raycast | 略高于高清材质 `0.10`,低于地形基准 `0.16`,减少悬浮感;地形 `depthWrite: false`,所以地形开启时仍可见。 |
|
||||
| 2.2 | 国界线 | `country-boundaries.js` | `lineAltitudeOffset = 0.115` | `depthTest: true`,禁用 raycast | 线层使用独立 line geometry 与 `renderOrder` 控制;地形 `depthWrite: false`,所以地形开启时仍可见。 |
|
||||
| 2.29 | 国界 hover 光晕 | `country-boundaries.js` | hover 半径加 glow 偏移 | `depthTest: false`,禁用 raycast | 用 additive 光晕增强交界边和地形开启时的 hover 可见性。 |
|
||||
| 2.3 | 国界 hover 实线 | `country-boundaries.js` | `hoverAltitudeOffset = 0.14` | `depthTest: false`,禁用 raycast | 霓虹红橘 hover 线;中国和中国(台湾)共享高亮组。 |
|
||||
| 2.3 | 国界 hover 实线 | `country-boundaries.js` | `hoverAltitudeOffset = 0.115` | `depthTest: false`,禁用 raycast | 霓虹红橘 hover 线;与普通国界线同源半径对齐,避免重影;中国和中国(台湾)共享高亮组。 |
|
||||
| 3 | 卫星 footprint 填充 / Iridium coverage ring | `satellites.js`, `iridium-footprint-adapter.js` | `GROUND_FOOTPRINT_RENDER_ORDER` | depth-tested;Iridium adapter 的 fill / ring 也使用同一 renderOrder | Footprint 在 land / texture / terrain 和国界线之上,但在算力中心和卫星之下。 |
|
||||
| 3-4.5 | BGP 观测站、事件扩散圈和事件 marker | `bgp.js`, `interactable.js` | BGP 观测站和事件 marker 均使用 `Interactable` 批量 `THREE.Points`;事件 marker 使用 `BGP_EVENT_RENDER_ORDER = 4.5`;观测站主图标使用 `BGP_COLLECTOR_RENDER_ORDER = 4.4` 和 `BGP_CONFIG.collectorAltitudeOffset = 0.2`;事件 overlay 进入 `bgp-event-overlay-layer`;观测站 halo 和覆盖扇形进入 `bgp-collector-radar-layer` | BGP 事件和观测站都通过 `Interactable` 屏幕空间 picking,并参与同坐标避让 | BGP 观测站主图标与船只同层;BGP 事件与算力中心同层;向外扩散圈、观测站雷达/覆盖动画继续由 BGP 业务逻辑驱动。 |
|
||||
| 4.3 | AIS 船只轨迹线 | `vessels.js` | `VESSEL_RENDER_ORDER - 0.1`;`CONFIG.earthRadius + VESSEL_CONFIG.track.altitudeOffset` | 跟随船只显隐,不单独参与拾取 | 选中船只后显示最近轨迹,低于船只 marker。 |
|
||||
| 4.4 | AIS 船只 marker | `vessels.js`, `interactable.js` | `VESSEL_RENDER_ORDER`;业务高度为 `CONFIG.earthRadius + VESSEL_CONFIG.altitudeOffset`;普通 marker 为分桶 `THREE.Points`,hover / locked 为单点 `THREE.Points` overlay | `depthTest: true`;`main.js` 使用屏幕空间 picking,只取正面 marker;参与 Interactable 同坐标避让 | 航行船只用三角点纹理,停泊/低速用圆点;普通态无 glow,交互态叠加同尺寸 glow;低于算力中心 `4.5`。 |
|
||||
| 4.5 | 算力中心 | `compute-centers.js`, `interactable.js` | 使用 `COMPUTE_CENTER_RENDER_ORDER` 并由 `Interactable` 绘制 | 通过 `Interactable` 屏幕空间 picking,参与同坐标避让 | 地表设施层,保持在卫星下方。登陆点已下沉到海缆层。 |
|
||||
| 5 | 卫星背景点 | `satellites.js` | 固定 renderOrder | 屏幕空间卫星拾取 | 位于卫星点下方。 |
|
||||
| 6 | 卫星点 | `satellites.js` | 固定 renderOrder | 屏幕空间卫星拾取 | 卫星点压过 footprint 和算力中心。 |
|
||||
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
|
||||
| 5 | 卫星背景点 | `satellites.js` | 固定 renderOrder;默认按 TLE/SGP4 真实高度压缩到 `CONFIG.earthRadius + 4..25`,关闭真实高度或传播失败时回退到 `fallbackAltitudeOffset = 8` | 屏幕空间卫星拾取 | 位于卫星点下方。 |
|
||||
| 6 | 卫星点 | `satellites.js` | 与卫星背景点使用同一压缩高度 / fallback 高度 | 屏幕空间卫星拾取 | 卫星点压过 footprint 和算力中心。 |
|
||||
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制闭合惯性轨道;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
|
||||
| 98-100 | 太阳 / 月亮 halo 和 sprite | `celestial.js` | 固定 renderOrder | 天体拾取禁用 | 前景天体 sprite。 |
|
||||
|
||||
## 开关联动
|
||||
@@ -46,6 +46,18 @@
|
||||
| 地形 on | 显示在高清材质之上,但低于国界 hover、footprint、卫星等强调层。 |
|
||||
| 大气云图 | 只控制云图 mesh 显隐。 |
|
||||
| 国界线 off | 只隐藏可交互国界线和 hover,高亮状态会清除;海陆基座填充仍作为 Earth 底图保留。 |
|
||||
| 真实卫星高度 off | 卫星点、轨迹和预测轨道都使用旧版同层球面;缺失 TLE 或传播失败的卫星也使用同一 fallback 高度。 |
|
||||
|
||||
## 深度间距规则
|
||||
|
||||
Earth 的地表不是单一 mesh,而是多层近似同心球:基座球、海陆基座、高清材质、地形、云层、大气和遮挡球。近距看起来只差几个小数的半径偏移,在 50% 这类远距视图下会被深度缓冲压到同一批像素,导致 z-fighting,表现为黑块、雪花或闪烁。
|
||||
|
||||
维护规则:
|
||||
|
||||
- 不要用“远距隐藏图层”作为第一反应;先检查相邻 shell 的 `altitudeOffset`、`renderOrder`、`depthTest` 和 `depthWrite`。
|
||||
- 海陆基座和高清材质这类整球 overlay 必须与 `CONFIG.earthRadius` 保持明确间距;当前稳定值为 `landAltitudeOffset = 0.32`、`textureOverlayAltitudeOffset = 0.48`。
|
||||
- 新增整球或近整球地表 overlay 时,必须在 50% 缩放和常用近距视图各截一次图,确认没有黑块、雪花、闪烁,也没有明显漂浮感。
|
||||
- 如果必须调整这些半径,需同步更新本文和 `frontend/public/earth/js/constants.js` 的注释/常量意图。
|
||||
|
||||
## 交互规则
|
||||
|
||||
|
||||
@@ -55,12 +55,12 @@ tasklist /svc /fi "PID eq 4700"
|
||||
临时排障可以在管理员 PowerShell 中停止 IP Helper:
|
||||
|
||||
```powershell
|
||||
Stop-Service iphlpsvc
|
||||
Stop-Service iphlpsvc -Force
|
||||
```
|
||||
|
||||
这可能影响部分网络、代理或转发能力。长期不推荐禁用该服务;如果必须保留 Windows 转发,改用不同后端端口更稳。
|
||||
这可能影响部分网络、代理或转发能力。长期不推荐禁用该服务;`--allow-lan` 会直接绑定 `3000` / `8000` / `8010`,不再需要保留持久 portproxy。
|
||||
|
||||
如果脚本输出 `failed-stop-service` 或 `failed-stop-process`,说明当前权限无法清理 Windows listener。脚本会停止启动,避免后端再次遇到同一端口冲突。
|
||||
如果脚本输出 `Windows 侧端口 ... 存在监听者`,或 Vite 报 `Port 3000 is already in use` 后显示 `Windows listener ... services=iphlpsvc`,说明旧的 Windows listener 仍在占用端口。脚本会请求管理员 PowerShell 清理对应端口;如果自动清理被取消,再手动检查 `netsh interface portproxy show all`,删除对应 `listenport` 规则。如果没有 portproxy 规则,再用 `netstat` / `tasklist` 确认服务,必要时临时 `Stop-Service iphlpsvc -Force`。清理旧规则后重新运行 `./planet.sh restart --allow-lan`,局域网仍访问 `3000` / `8000` / `8010`。
|
||||
|
||||
### 默认端口冲突时应该改哪些参数?
|
||||
|
||||
@@ -89,6 +89,7 @@ Stop-Service iphlpsvc
|
||||
# 在 WSL 或运行 Planet 的 shell 中
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
再到 Windows PowerShell 验证:
|
||||
@@ -96,6 +97,7 @@ curl http://localhost:8000/health
|
||||
```powershell
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
curl http://localhost:8010/health
|
||||
```
|
||||
|
||||
如果 WSL 和 Windows localhost 都通,但手机或其他电脑访问不通,再考虑局域网开放:
|
||||
@@ -110,22 +112,28 @@ curl http://localhost:8000/health
|
||||
./planet.sh restart -f 3000 --allow-lan
|
||||
```
|
||||
|
||||
如果 `ss -ltnp` 显示前端已经监听 `0.0.0.0:3000`,但 Windows PowerShell 中 `Test-NetConnection <Windows局域网IP> -Port 3000` 仍失败,问题通常不在 Vite 或 `.zshrc`,而是在 Windows 侧转发或防火墙。
|
||||
如果 `ss -ltnp` 显示前端已经监听 `0.0.0.0:3000`,但 Windows PowerShell 中 `Test-NetConnection <Windows局域网IP> -Port 3000` 仍失败,问题通常不在 Vite 或 `.zshrc`,而是在 Windows 侧端口占用、旧 `portproxy` 或防火墙。
|
||||
|
||||
传统 WSL NAT 场景下,管理员 PowerShell 中配置 portproxy 和防火墙:
|
||||
`./planet.sh start --allow-lan` 会直接开放 `3000` / `8000` / `8010`,并在启动前检测端口、旧 `portproxy` 和 Windows 防火墙规则。端口被 Windows 侧 listener 占用时,脚本会请求管理员 PowerShell 清理;缺少入站放行时,也会触发一次 UAC 管理员 PowerShell 请求来自动创建。若自动请求被取消,可以手动清理:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=3000 connectaddress=127.0.0.1 connectport=3000
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8000 connectaddress=127.0.0.1 connectport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=3000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8010
|
||||
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 3000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8010" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8010
|
||||
```
|
||||
|
||||
局域网设备访问 Windows 对外端口,例如 `http://<Windows局域网IP>:3000/earth`。
|
||||
|
||||
如果 `wslinfo --networking-mode` 输出 `mirrored`,还需要检查 Hyper-V firewall。普通 Windows 防火墙规则存在时,Hyper-V firewall 仍可能拦截外部设备进入 WSL。管理员 PowerShell 中按端口放行:
|
||||
|
||||
```powershell
|
||||
New-NetFirewallHyperVRule -Name "Planet-Frontend-3000" -DisplayName "Planet Frontend 3000" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 3000 -Action Allow
|
||||
New-NetFirewallHyperVRule -Name "Planet-Backend-8000" -DisplayName "Planet Backend 8000" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 8000 -Action Allow
|
||||
New-NetFirewallHyperVRule -Name "Planet-AIProvider-8010" -DisplayName "Planet AI Provider 8010" -Direction Inbound -VMCreatorId "{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}" -Protocol TCP -LocalPorts 8010 -Action Allow
|
||||
```
|
||||
|
||||
也可以用下面命令确认当前 Hyper-V firewall 状态:
|
||||
@@ -323,6 +331,14 @@ Docs 按 Gatekeeper 权限组控制可见性:
|
||||
|
||||
算力中心候选保存后会写入 `compute_center_locations`。没有可用候选的记录会保留在待定位列表中,系统不会用国家中心点或硬编码 hint 伪造位置。
|
||||
|
||||
### 为什么卫星看起来不在同一个球面上?
|
||||
|
||||
Earth 默认开启“真实卫星高度”。卫星位置仍来自 TLE/SGP4,但高度会经过压缩映射:低轨卫星靠近地球,高轨卫星更远,同时保持在当前视图可读范围内。最高显示偏移使用 `25`,约等于当前地球显示半径的四分之一;这是视觉上区分 GEO / MEO / LEO 和保持镜头可读性的折中,不是把真实公里数按比例直接画出来。这个设置也会影响卫星轨迹和锁定后的预测轨道。
|
||||
|
||||
如果需要旧版所有卫星位于同一显示球面的效果,在 Earth 设置里关闭“真实卫星高度”。缺失 TLE 或传播失败的卫星仍会回退到旧版固定高度,不会因为无法计算真实高度而消失。
|
||||
|
||||
低倾角高轨卫星应该沿赤道附近或固定经度附近分布,而不是绕出接近南北向的大圈。Earth 会先把 SGP4 的惯性系位置转换成地固坐标再绘制当前点;锁定后的预测轨道则固定当前地球姿态来画一圈惯性轨道,所以应该闭合并保留正确倾角。如果以后看到详情卡倾角接近 `0°`,但预测轨道像极轨一样竖着绕,优先检查 ECI/TEME 到 ECF 的转换和预测轨道是否错误使用了逐采样 `gstime`。
|
||||
|
||||
### 动捕调试面板为什么看不到摄像头画面?
|
||||
|
||||
如果输入源是 Browser Camera,调试面板会显示浏览器本机摄像头实时预览,并在画面上绘制骨架。如果勾选了 `只显示骨骼`,视频预览会被隐藏,只显示深色背景和红/绿骨架。
|
||||
|
||||
@@ -232,7 +232,7 @@ Earth `http://localhost:3000/earth` 是公开 3D 态势页面,不需要登录
|
||||
|
||||
### 图层控制
|
||||
|
||||
右侧图层面板用于打开或关闭图层。常见图层:经纬线、国界线、高清材质、大气云图、海缆、算力中心、BGP 观测、卫星、AIS 船只、轨迹、地形。
|
||||
右侧图层面板用于打开或关闭图层。常见图层:经纬线、国界线、高清材质、大气云图、海缆、算力中心、BGP 观测、卫星、AIS 船只、地形。卫星轨迹不再作为单独图层出现在图层列表中,改在设置面板里控制。
|
||||
|
||||
依赖关系:
|
||||
|
||||
@@ -258,7 +258,11 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军
|
||||
|
||||
### 设置
|
||||
|
||||
设置面板包含:旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼、地球默认大小、地形透明度、重置设置。
|
||||
设置面板包含:旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、悬停提示、卫星呼吸闪烁、真实卫星高度、轨迹显示、低缩放圆点、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼、地球默认大小、地形透明度、重置设置。
|
||||
|
||||
“真实卫星高度”默认开启:卫星会按 TLE/SGP4 算出的真实轨道高度做压缩分层显示,低轨仍靠近地球,高轨会更远但不会脱离当前视图。高轨显示高度会被压到地球半径外约四分之一以内,这样 GEO / MEO 仍能和 LEO 分层,但不会把视线、轨迹和选择操作拉得过散;关闭后恢复旧版所有卫星位于同一显示球面的效果。“轨迹显示”控制卫星轨迹线显隐,卫星图层关闭时轨迹也不可见。
|
||||
|
||||
“悬停提示”控制鼠标悬停地表时的 tooltip 内容:`国家` 只在陆地命中国家时显示国家信息,太平洋等海洋区域不弹出地表提示;`位置` 在陆地和海洋都显示纬度、经度和海拔;`完整` 是默认模式,陆地显示国家 + 位置,海洋显示位置。
|
||||
|
||||
这些设置保存在浏览器本地存储,换浏览器或清理站点数据后会恢复默认值。
|
||||
|
||||
@@ -313,6 +317,7 @@ Earth 预留了动作捕捉控制入口。实时链路两种输入源:
|
||||
- **Earth 打不开**:先确认前端服务是否在线;如果端口不是 `3000`,使用启动输出的实际端口
|
||||
- **图层没有数据**:进 `/datasources` 看数据源状态、是否已采集和最近执行结果,再到 `/data` 或 `/bgp` 看是否有记录
|
||||
- **卫星 / BGP / 海缆加载慢**:这些图层依赖后端接口和外部数据源,首次加载需要等启动任务完成
|
||||
- **卫星看起来不在同一层**:这是默认的真实高度压缩显示。想回到旧版同层球面,可在设置中关闭“真实卫星高度”
|
||||
|
||||
## Docs 文档站
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ wait_for_port_release() {
|
||||
- `PORT_PRESTART_RETRIES`:默认 3 次。
|
||||
- `PORT_PRESTART_RETRY_INTERVAL`:默认 2 秒。
|
||||
|
||||
`kill_port_if_requested()` 优先清理当前环境能找到的监听 PID;只有检测到当前运行在 WSL 且没有可杀 PID、但端口仍不可绑定时,才会检查 Windows 侧 listener,并尝试通过 PowerShell 停止对应服务或强制结束对应进程。若没有权限,或 `iphlpsvc` 这类系统服务拒绝停止,脚本会打印 Windows listener 详情并立即停止启动,不再继续拉起服务碰同一个端口错误。非 WSL 环境不会尝试 Windows 清理路径。此时需要用管理员 PowerShell 清理 portproxy/服务占用,或改用其他端口。
|
||||
`kill_port_if_requested()` 优先清理当前环境能找到的监听 PID;只有检测到当前运行在 WSL 且没有可杀 PID、但端口仍不可绑定时,才会检查 Windows 侧 listener,并请求管理员 PowerShell 删除旧 `portproxy`、停止占用端口的服务或强制结束对应进程。若管理员请求被取消,或 `iphlpsvc` 这类系统服务拒绝停止,脚本会打印 Windows listener 详情和管理员 PowerShell 处理命令,然后立即停止启动,不再继续拉起服务碰同一个端口错误。前端 Vite 启动后才发现 `Port 3000 is already in use` 时,也会打印同一套 Windows listener 处理命令。非 WSL 环境不会尝试 Windows 清理路径。`--allow-lan` 直接开放 `3000` / `8000` / `8010`,不再启动额外的 Windows 端口转发进程;旧的持久 portproxy 规则应清理掉。
|
||||
|
||||
## 问题三:端口检测用 Python
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@
|
||||
- 手机或平板演示 Earth
|
||||
- 局域网其他机器访问同一开发实例
|
||||
|
||||
`--allow-lan` 只负责让前端和后端监听 `0.0.0.0`。WSL 中运行时,Windows 本机一般可以通过 `localhost` 访问,但局域网其他机器访问 `http://<Windows局域网IP>:3000` 还需要 Windows 端口转发和防火墙放行。
|
||||
`--allow-lan` 会让前端、后端和 AI Provider 直接对开发机开放:前端 `3000`、后端 `8000`、AI Provider `8010`。脚本启动前会检查这三个端口;如果 WSL/Linux 侧无法释放端口,并检测到 Windows 侧 listener 或旧 `portproxy`,会请求管理员 PowerShell 清理。WSL 中运行时,Windows 本机一般可以通过 `localhost` 访问,局域网其他机器访问 Windows 局域网 IP 时还需要 Windows 防火墙放行。
|
||||
|
||||
建议按顺序排查:
|
||||
|
||||
@@ -128,19 +128,24 @@
|
||||
# 在运行 Planet 的 shell 中
|
||||
curl http://localhost:3000
|
||||
curl http://localhost:8000/health
|
||||
ss -ltnp | grep -E ':3000|:8000'
|
||||
curl http://localhost:8010/health
|
||||
ss -ltnp | grep -E ':3000|:8000|:8010'
|
||||
```
|
||||
|
||||
如果看到 `0.0.0.0:3000` 和 `0.0.0.0:8000`,但局域网 IP 仍访问失败,在管理员 PowerShell 中配置:
|
||||
如果服务已经启动但局域网 IP 仍访问失败,优先清理旧 `portproxy` 并确认 Windows 防火墙放行。脚本会自动检测并请求管理员 PowerShell 处理;自动请求被取消时,手动兜底命令如下:
|
||||
|
||||
```powershell
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=3000 connectaddress=127.0.0.1 connectport=3000
|
||||
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8000 connectaddress=127.0.0.1 connectport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=3000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8000
|
||||
netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=8010
|
||||
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 3000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 3000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8000" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8000
|
||||
New-NetFirewallRule -DisplayName "WSL Planet 8010" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 8010
|
||||
```
|
||||
|
||||
局域网设备访问 Windows 对外端口,例如 `http://<Windows局域网IP>:3000/earth`、`http://<Windows局域网IP>:8000/health`、`http://<Windows局域网IP>:8010/health`。
|
||||
|
||||
## AI Provider 环境变量与构建
|
||||
|
||||
AI Provider 运行期配置可以放在两处:
|
||||
@@ -236,6 +241,16 @@ uv sync
|
||||
uv run pytest backend/tests/test_otp_service.py
|
||||
```
|
||||
|
||||
## Earth 国界 PMTiles 操作步骤
|
||||
|
||||
1. 在后台 Collector Settings 中分别配置 `Earth Admin-0 国界源`、`Earth 海岸线源`、`Earth 主张线源` 的 endpoint、headers/auth、`config.target_schema=earth_boundary_source`、license 和 mapping。
|
||||
2. 在数据源页依次采集这三个源。每个源成功后会保存完整 artifact 到 `data/earth-boundary-sources/<collector>/<sha256>.*`,并写入 sha256、feature count、artifact path、sample properties。
|
||||
3. 三个源都成功后,再采集 `Earth PMTiles 构建器`。缺任一源时它会失败为“未就绪”,不会更新 Earth 国界。
|
||||
4. 构建器需要本机 PATH 里有 `tippecanoe` 和 `pmtiles`。缺工具时任务失败并显示缺失工具。
|
||||
5. 生产构建成功后应输出 `frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles` 和对应 manifest。
|
||||
6. 部署后打开 Earth,开启“国界线”,放大中国东南海岸、台湾、海南、南海、藏南、科索沃、加沙等区域验证 hover 和边界口径。
|
||||
7. 如果 PMTiles 加载失败,Earth 会报国界图层错误并且不绘制旧低精度国界。排查顺序是:浏览器 Network 是否有 PMTiles range 请求、manifest 的 `tileProvider` 是否为 `pmtiles-mvt`、Nginx 是否能静态返回 `.pmtiles`、artifact 路径和 sha256 是否与 manifest 一致。
|
||||
|
||||
## 相关文档
|
||||
|
||||
- [planet.sh 启动机制](/home/ray/dev/linkong/planet/docs/technical/zh/ops-planet-sh-startup.md)
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
- 搜索可以查找海缆、卫星、算力中心、BGP 事件
|
||||
- 算力中心和 BGP 观测站详情卡可以自动采集坐标候选,并能在 Earth 上预览
|
||||
- 鼠标拖动、滚轮缩放、缩放百分比提示工作正常
|
||||
- 设置面板的旋转 / 巡航 / 动捕模式可以切换
|
||||
- 设置面板的旋转 / 巡航 / 动捕模式可以切换;视图设置里可以切换悬停提示,卫星相关设置里可以打开或关闭真实高度分层和轨迹显示
|
||||
|
||||
## 5. 找回密码
|
||||
|
||||
|
||||
@@ -16,12 +16,17 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.53.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.58.0`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `0.58.0` | feature | `dev` | `pending` | Earth 高精度国界切换到 PMTiles/MVT 和标准源采集器,移除旧低精度兜底,修复远距地表 z-fighting 雪花/黑块,并补齐新闻目标地点队列与文档 |
|
||||
| `0.57.0` | feature | `dev` | `pending` | WSL `--allow-lan` 新增临时 Windows relay,保持 localhost 与局域网同用 3000/8000,并自动处理旧 portproxy、防火墙授权和 Vite ESM 配置 |
|
||||
| `0.56.0` | feature | `dev` | `pending` | 修复 Earth 卫星 ECI/TEME 到 ECF 坐标转换和闭合预测轨道,调校真实高度压缩上限,统一 BGP 光晕色调,并更新超算图标与 Earth HUD/新闻体验 |
|
||||
| `0.55.0` | feature | `dev` | `pending` | Earth 卫星新增真实高度压缩显示开关,轨迹和预测轨道跟随高度模式切换,并补齐设置面板、FAQ、用户手册和开发者文档 |
|
||||
| `0.54.0` | feature | `dev` | `pending` | 新增 Earth 轨迹显示设置并迁移到桌面/移动设置面板,持久化轨迹偏好,同时优化卫星呼吸闪烁参数和算力中心图标资产 |
|
||||
| `0.53.0` | feature | `dev` | `pending` | 新增 Gitea Actions CI/CD、生产镜像、Kubernetes Helm chart 与 staging 部署 smoke test,明确 Vite 生产构建和 planet.sh 开发入口边界 |
|
||||
| `0.52.0` | feature | `dev` | `pending` | 新增邮箱验证码账号自助链路、AISStream 船只实时采集与受控 snapshot/WS 展示、数据产品统计接口、受控图层接口和数据源批量运维 |
|
||||
| `0.51.1` | bugfix | `dev` | `pending` | 修复 Earth 静态资源模块相对路径与 Material Symbols 本地字体加载,避免部署路径变化或外部字体不可用时图标/边界资源失效 |
|
||||
|
||||
@@ -6,9 +6,12 @@
|
||||
"name": "planet-frontend",
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.2.6",
|
||||
"@mapbox/vector-tile": "^2.0.4",
|
||||
"antd": "^5.12.5",
|
||||
"axios": "^1.6.2",
|
||||
"dayjs": "^1.11.10",
|
||||
"pbf": "^4.0.1",
|
||||
"pmtiles": "^4.4.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-resizable": "^3.1.3",
|
||||
@@ -19,6 +22,7 @@
|
||||
"zustand": "^4.4.7",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
@@ -142,6 +146,10 @@
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
|
||||
|
||||
"@mapbox/point-geometry": ["@mapbox/point-geometry@1.1.0", "", {}, "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ=="],
|
||||
|
||||
"@mapbox/vector-tile": ["@mapbox/vector-tile@2.0.4", "", { "dependencies": { "@mapbox/point-geometry": "~1.1.0", "@types/geojson": "^7946.0.16", "pbf": "^4.0.1" } }, "sha512-AkOLcbgGTdXScosBWwmmD7cDlvOjkg/DetGva26pIRiZPdeJYjYKarIlb4uxVzi6bwHO6EWH82eZ5Nuv4T5DUg=="],
|
||||
|
||||
"@rc-component/async-validator": ["@rc-component/async-validator@5.1.0", "", { "dependencies": { "@babel/runtime": "^7.24.4" } }, "sha512-n4HcR5siNUXRX23nDizbZBQPO0ZM/5oTtmKZ6/eqL0L2bo747cklFdZGRN2f+c9qWGICwDzrhW0H7tE9PptdcA=="],
|
||||
|
||||
"@rc-component/color-picker": ["@rc-component/color-picker@2.0.1", "", { "dependencies": { "@ant-design/fast-color": "^2.0.6", "@babel/runtime": "^7.23.6", "classnames": "^2.2.6", "rc-util": "^5.38.1" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-WcZYwAThV/b2GISQ8F+7650r5ZZJ043E57aVBFkQ+kSY4C6wdofXgB0hBx+GPGpIU0Z81eETNoDUJMr7oy/P8Q=="],
|
||||
@@ -226,6 +234,10 @@
|
||||
|
||||
"@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
|
||||
|
||||
"@types/geojson": ["@types/geojson@7946.0.16", "", {}, "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg=="],
|
||||
|
||||
"@types/node": ["@types/node@24.12.4", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA=="],
|
||||
|
||||
"@types/prop-types": ["@types/prop-types@15.7.15", "", {}, "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw=="],
|
||||
|
||||
"@types/react": ["@types/react@18.3.27", "", { "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" } }, "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w=="],
|
||||
@@ -288,6 +300,8 @@
|
||||
|
||||
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
|
||||
|
||||
"fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="],
|
||||
|
||||
"follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="],
|
||||
|
||||
"form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="],
|
||||
@@ -336,12 +350,18 @@
|
||||
|
||||
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
|
||||
|
||||
"pbf": ["pbf@4.0.1", "", { "dependencies": { "resolve-protobuf-schema": "^2.1.0" }, "bin": { "pbf": "bin/pbf" } }, "sha512-SuLdBvS42z33m8ejRbInMapQe8n0D3vN/Xd5fmWM3tufNgRQFBpaW2YVJxQZV4iPNqb0vEFvssMEo5w9c6BTIA=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"pmtiles": ["pmtiles@4.4.1", "", { "dependencies": { "fflate": "^0.8.2" } }, "sha512-5oTeQc/yX/ft1evbpIlnoCZugQuug/iYIAj/ZTqIqzdGek4uZEho99En890EE6NOSI3JTI3IG8R7r8+SltphxA=="],
|
||||
|
||||
"postcss": ["postcss@8.5.6", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg=="],
|
||||
|
||||
"prop-types": ["prop-types@15.8.1", "", { "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", "react-is": "^16.13.1" } }, "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg=="],
|
||||
|
||||
"protocol-buffers-schema": ["protocol-buffers-schema@3.6.1", "", {}, "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ=="],
|
||||
|
||||
"proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="],
|
||||
|
||||
"rc-cascader": ["rc-cascader@3.34.0", "", { "dependencies": { "@babel/runtime": "^7.25.7", "classnames": "^2.3.1", "rc-select": "~14.16.2", "rc-tree": "~5.13.0", "rc-util": "^5.43.0" }, "peerDependencies": { "react": ">=16.9.0", "react-dom": ">=16.9.0" } }, "sha512-KpXypcvju9ptjW9FaN2NFcA2QH9E9LHKq169Y0eWtH4e/wHQ5Wh5qZakAgvb8EKZ736WZ3B0zLLOBsrsja5Dag=="],
|
||||
@@ -430,6 +450,8 @@
|
||||
|
||||
"resize-observer-polyfill": ["resize-observer-polyfill@1.5.1", "", {}, "sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg=="],
|
||||
|
||||
"resolve-protobuf-schema": ["resolve-protobuf-schema@2.1.0", "", { "dependencies": { "protocol-buffers-schema": "^3.3.1" } }, "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ=="],
|
||||
|
||||
"rollup": ["rollup@4.57.1", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.57.1", "@rollup/rollup-android-arm64": "4.57.1", "@rollup/rollup-darwin-arm64": "4.57.1", "@rollup/rollup-darwin-x64": "4.57.1", "@rollup/rollup-freebsd-arm64": "4.57.1", "@rollup/rollup-freebsd-x64": "4.57.1", "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", "@rollup/rollup-linux-arm-musleabihf": "4.57.1", "@rollup/rollup-linux-arm64-gnu": "4.57.1", "@rollup/rollup-linux-arm64-musl": "4.57.1", "@rollup/rollup-linux-loong64-gnu": "4.57.1", "@rollup/rollup-linux-loong64-musl": "4.57.1", "@rollup/rollup-linux-ppc64-gnu": "4.57.1", "@rollup/rollup-linux-ppc64-musl": "4.57.1", "@rollup/rollup-linux-riscv64-gnu": "4.57.1", "@rollup/rollup-linux-riscv64-musl": "4.57.1", "@rollup/rollup-linux-s390x-gnu": "4.57.1", "@rollup/rollup-linux-x64-gnu": "4.57.1", "@rollup/rollup-linux-x64-musl": "4.57.1", "@rollup/rollup-openbsd-x64": "4.57.1", "@rollup/rollup-openharmony-arm64": "4.57.1", "@rollup/rollup-win32-arm64-msvc": "4.57.1", "@rollup/rollup-win32-ia32-msvc": "4.57.1", "@rollup/rollup-win32-x64-gnu": "4.57.1", "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" }, "bin": "dist/bin/rollup" }, "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A=="],
|
||||
|
||||
"scheduler": ["scheduler@0.23.2", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="],
|
||||
@@ -458,6 +480,8 @@
|
||||
|
||||
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||
|
||||
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
|
||||
|
||||
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": "cli.js" }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
|
||||
|
||||
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
|
||||
|
||||
@@ -50,6 +50,23 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /earth/data/boundaries/v1/manifest.json {
|
||||
add_header Cache-Control "no-store";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ~ ^/earth/data/boundaries/.*\.pmtiles$ {
|
||||
types { application/octet-stream pmtiles; }
|
||||
add_header Accept-Ranges bytes;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location /earth/data/boundaries/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.53.0",
|
||||
"version": "0.58.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.2.6",
|
||||
"@mapbox/vector-tile": "^2.0.4",
|
||||
"antd": "^5.12.5",
|
||||
"axios": "^1.6.2",
|
||||
"dayjs": "^1.11.10",
|
||||
"pbf": "^4.0.1",
|
||||
"pmtiles": "^4.4.1",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-resizable": "^3.1.3",
|
||||
@@ -20,6 +23,7 @@
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@types/node": "^24.0.0",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.0.10"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#38bdf8" class="bi bi-pc" viewBox="0 0 16 16">
|
||||
<path d="M5 0a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1H5Zm.5 14a.5.5 0 1 1 0 1 .5.5 0 0 1 0-1Zm2 0a.5.5 0 1 1 0 1 .5.5 0 0 1 0-1ZM5 1.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5ZM5.5 3h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1Z"/>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#38bdf8" class="bi bi-buildings-fill" viewBox="0 0 16 16">
|
||||
<path d="M15 .5a.5.5 0 0 0-.724-.447l-8 4A.5.5 0 0 0 6 4.5v3.14L.342 9.526A.5.5 0 0 0 0 10v5.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V14h1v1.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5V.5ZM2 11h1v1H2v-1Zm2 0h1v1H4v-1Zm-1 2v1H2v-1h1Zm1 0h1v1H4v-1Zm9-10v1h-1V3h1ZM8 5h1v1H8V5Zm1 2v1H8V7h1ZM8 9h1v1H8V9Zm2 0h1v1h-1V9Zm-1 2v1H8v-1h1Zm1 0h1v1h-1v-1Zm3-2v1h-1V9h1Zm-1 2h1v1h-1v-1Zm-2-4h1v1h-1V7Zm3 0v1h-1V7h1Zm-2-2v1h-1V5h1Zm1 0h1v1h-1V5Z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 383 B After Width: | Height: | Size: 562 B |
@@ -1,7 +1,7 @@
|
||||
/* earth-stats.css — compact KPI grid panel */
|
||||
|
||||
.hud-panel-stats {
|
||||
top: var(--hud-offset);
|
||||
bottom: var(--hud-offset);
|
||||
right: var(--hud-offset);
|
||||
border-radius: 0; /* square / angular — matches layer panel */
|
||||
padding: 0;
|
||||
@@ -129,9 +129,9 @@
|
||||
/* ── Layout-expanded: slide off-screen ───────────────────────── */
|
||||
|
||||
.earth-app.layout-expanded .hud-panel-stats:not([data-dragged="true"]) {
|
||||
top: var(--hud-offset);
|
||||
bottom: var(--hud-offset);
|
||||
right: var(--hud-offset);
|
||||
transform: translate(calc(100% - var(--hud-offset)), calc(-100% + var(--hud-offset)));
|
||||
transform: translate(calc(100% - var(--hud-offset)), calc(100% - var(--hud-offset)));
|
||||
}
|
||||
|
||||
.layout-mode-mobile .hud-panel-stats {
|
||||
|
||||
@@ -1390,12 +1390,13 @@
|
||||
.earth-mobile-settings-switch-track::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
top: 50%;
|
||||
left: 4px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transform: translateY(-50%);
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
|
||||
@@ -1404,7 +1405,7 @@
|
||||
}
|
||||
|
||||
.earth-mobile-settings-switch input:checked + .earth-mobile-settings-switch-track::after {
|
||||
transform: translateX(16px);
|
||||
transform: translate(16px, -50%);
|
||||
}
|
||||
|
||||
label.is-disabled.earth-mobile-settings-card {
|
||||
@@ -1629,9 +1630,12 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.earth-status-message,
|
||||
.earth-error-message {
|
||||
position: absolute;
|
||||
top: calc(20px * var(--hud-scale));
|
||||
left: 50%;
|
||||
transform: translate(-50%, -18px);
|
||||
top: calc(var(--hud-offset) + calc(2px * var(--hud-scale)));
|
||||
left: min(
|
||||
calc(var(--hud-offset) + calc(340px * var(--hud-scale)) + calc(12px * var(--hud-scale))),
|
||||
calc(100vw - min(calc(440px * var(--hud-scale)), 74vw) - var(--hud-offset))
|
||||
);
|
||||
transform: translateY(-18px);
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: calc(10px * var(--hud-scale));
|
||||
@@ -1664,10 +1668,20 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
|
||||
.earth-status-message.visible,
|
||||
.earth-error-message.visible {
|
||||
transform: translate(-50%, 0);
|
||||
transform: translateY(0);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.earth-status-message.earth-status-message--ticker-stack {
|
||||
top: calc(var(--hud-offset) + calc(50px * var(--hud-scale)));
|
||||
left: 50%;
|
||||
transform: translate(-50%, -18px);
|
||||
}
|
||||
|
||||
.earth-status-message.earth-status-message--ticker-stack.visible {
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.earth-status-message.gesture {
|
||||
min-width: 0;
|
||||
padding-right: calc(16px * var(--hud-scale));
|
||||
@@ -1675,7 +1689,7 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
}
|
||||
|
||||
.earth-error-message {
|
||||
top: calc(62px * var(--hud-scale));
|
||||
top: calc(var(--hud-offset) + calc(92px * var(--hud-scale)));
|
||||
z-index: 211;
|
||||
min-width: min(calc(220px * var(--hud-scale)), 58vw);
|
||||
}
|
||||
@@ -2477,13 +2491,14 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
.earth-settings-switch-track::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: calc(3px * var(--hud-scale));
|
||||
top: 50%;
|
||||
left: calc(3px * var(--hud-scale));
|
||||
width: calc(16px * var(--hud-scale));
|
||||
height: calc(16px * var(--hud-scale));
|
||||
border-radius: 50%;
|
||||
background: #edf4fc;
|
||||
box-shadow: 0 6px 14px rgba(1, 8, 18, 0.26);
|
||||
transform: translateY(-50%);
|
||||
transition: transform 0.18s ease;
|
||||
}
|
||||
|
||||
@@ -2493,7 +2508,7 @@ label.is-disabled.earth-mobile-settings-card {
|
||||
}
|
||||
|
||||
.earth-settings-switch input:checked + .earth-settings-switch-track::after {
|
||||
transform: translateX(calc(16px * var(--hud-scale)));
|
||||
transform: translate(calc(16px * var(--hud-scale)), -50%);
|
||||
}
|
||||
|
||||
.earth-settings-item.is-disabled {
|
||||
|
||||
@@ -1,5 +1,232 @@
|
||||
/* news-panel.css */
|
||||
|
||||
.earth-news-ticker {
|
||||
--news-ticker-width: min(calc(820px * var(--hud-scale)), 58vw);
|
||||
position: absolute;
|
||||
top: calc(var(--hud-offset) + calc(2px * var(--hud-scale)));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: var(--news-ticker-width);
|
||||
height: calc(38px * var(--hud-scale));
|
||||
border: 0;
|
||||
border-top: 1px solid var(--hud-border);
|
||||
border-bottom: 1px solid var(--hud-border);
|
||||
border-radius: 0;
|
||||
padding: 0 calc(18px * var(--hud-scale));
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: calc(12px * var(--hud-scale));
|
||||
color: var(--hud-text);
|
||||
background:
|
||||
linear-gradient(90deg, transparent 0%, rgba(17, 31, 53, 0.82) 11%, rgba(7, 17, 31, 0.78) 89%, transparent 100%),
|
||||
radial-gradient(circle at 50% -80%, rgba(145, 186, 255, 0.18), transparent 58%);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.08),
|
||||
inset 0 -1px 0 rgba(255, 255, 255, 0.03),
|
||||
0 14px 34px rgba(1, 7, 16, 0.22);
|
||||
backdrop-filter: blur(16px) saturate(122%);
|
||||
-webkit-backdrop-filter: blur(16px) saturate(122%);
|
||||
cursor: pointer;
|
||||
z-index: 24;
|
||||
overflow: hidden;
|
||||
transition: opacity 0.18s ease, transform 0.24s ease;
|
||||
}
|
||||
|
||||
.earth-news-ticker.is-hidden {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.earth-news-ticker::before,
|
||||
.earth-news-ticker::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -1px;
|
||||
bottom: -1px;
|
||||
width: calc(96px * var(--hud-scale));
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.earth-news-ticker::before {
|
||||
left: 0;
|
||||
background: linear-gradient(90deg, rgba(0, 0, 0, 0), rgba(8, 18, 32, 0.08));
|
||||
}
|
||||
|
||||
.earth-news-ticker::after {
|
||||
right: 0;
|
||||
background: linear-gradient(270deg, rgba(0, 0, 0, 0), rgba(8, 18, 32, 0.08));
|
||||
}
|
||||
|
||||
.earth-news-ticker__region {
|
||||
position: relative;
|
||||
z-index: 3;
|
||||
color: var(--hud-accent-strong);
|
||||
font-size: calc(0.66rem * var(--hud-scale));
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.earth-news-ticker__viewport {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
-webkit-mask-image: linear-gradient(90deg, transparent 0%, #000 9%, #000 91%, transparent 100%);
|
||||
mask-image: linear-gradient(90deg, transparent 0%, #000 9%, #000 91%, transparent 100%);
|
||||
}
|
||||
|
||||
.earth-news-ticker__track {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: calc(30px * var(--hud-scale));
|
||||
min-width: max-content;
|
||||
color: rgba(232, 242, 252, 0.92);
|
||||
font-size: calc(0.84rem * var(--hud-scale));
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
animation: earthNewsTickerScroll var(--news-ticker-duration, 28s) linear infinite;
|
||||
}
|
||||
|
||||
.earth-news-ticker:hover .earth-news-ticker__track,
|
||||
.earth-news-ticker:focus-visible .earth-news-ticker__track {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
.earth-news-ticker__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: calc(8px * var(--hud-scale));
|
||||
}
|
||||
|
||||
.earth-news-ticker__source {
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.64rem * var(--hud-scale));
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.earth-news-hud {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
top: max(calc(86px * var(--hud-scale)), 10vh);
|
||||
transform: translateX(-50%);
|
||||
width: min(calc(720px * var(--hud-scale)), calc(100vw - 40px));
|
||||
height: min(calc(660px * var(--hud-scale)), calc(100vh - 140px));
|
||||
padding: calc(14px * var(--hud-scale));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--hud-gap-sm);
|
||||
z-index: 220;
|
||||
min-width: calc(420px * var(--hud-scale));
|
||||
min-height: calc(360px * var(--hud-scale));
|
||||
}
|
||||
|
||||
.earth-news-hud.hud-panel-hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.earth-news-hud.is-morphing {
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
transition:
|
||||
left 0.28s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
top 0.28s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
width 0.28s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
height 0.28s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
opacity 0.2s ease;
|
||||
}
|
||||
|
||||
.earth-news-hud.is-morphing > * {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.earth-news-hud.is-resizing {
|
||||
transition: none !important;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.earth-news-hud__header {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.earth-news-hud__body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge {
|
||||
position: absolute;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="r"] {
|
||||
right: 0;
|
||||
top: calc(12px * var(--hud-scale));
|
||||
bottom: calc(12px * var(--hud-scale));
|
||||
width: calc(6px * var(--hud-scale));
|
||||
cursor: ew-resize;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="b"] {
|
||||
bottom: 0;
|
||||
left: calc(12px * var(--hud-scale));
|
||||
right: calc(12px * var(--hud-scale));
|
||||
height: calc(6px * var(--hud-scale));
|
||||
cursor: ns-resize;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="l"] {
|
||||
left: 0;
|
||||
top: calc(12px * var(--hud-scale));
|
||||
bottom: calc(12px * var(--hud-scale));
|
||||
width: calc(6px * var(--hud-scale));
|
||||
cursor: ew-resize;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="br"] {
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: calc(20px * var(--hud-scale));
|
||||
height: calc(20px * var(--hud-scale));
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="bl"] {
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
width: calc(20px * var(--hud-scale));
|
||||
height: calc(20px * var(--hud-scale));
|
||||
cursor: nesw-resize;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="br"]::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: calc(4px * var(--hud-scale));
|
||||
border-right: 2px solid rgba(223, 235, 248, 0.4);
|
||||
border-bottom: 2px solid rgba(223, 235, 248, 0.4);
|
||||
transition: border-color 0.18s ease;
|
||||
}
|
||||
|
||||
.earth-news-hud-edge[data-edge="br"]:hover::before {
|
||||
border-color: rgba(244, 249, 255, 0.75);
|
||||
}
|
||||
|
||||
@keyframes earthNewsTickerScroll {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
to {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
|
||||
.news-panel-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -33,6 +260,10 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.earth-news-hud .news-panel-body {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.news-panel-focus {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
@@ -189,3 +420,8 @@
|
||||
line-height: 1.5;
|
||||
padding: calc(16px * var(--hud-scale)) calc(4px * var(--hud-scale));
|
||||
}
|
||||
|
||||
.layout-mode-mobile .earth-news-ticker,
|
||||
.layout-mode-mobile .earth-news-hud {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
/* media-panel
|
||||
* Outer HUD shell: #media-panel
|
||||
* Inner live pane: #tv-panel
|
||||
* Inner news pane: #news-panel
|
||||
*/
|
||||
|
||||
.hud-panel-media {
|
||||
bottom: var(--hud-offset);
|
||||
top: var(--hud-offset);
|
||||
right: var(--hud-offset);
|
||||
width: calc(420px * var(--hud-scale));
|
||||
max-width: calc(100vw - 32px);
|
||||
max-height: calc(100vh - (2 * var(--hud-offset)));
|
||||
min-height: 0;
|
||||
min-width: calc(300px * var(--hud-scale));
|
||||
padding: calc(10px * var(--hud-scale));
|
||||
display: flex;
|
||||
@@ -18,11 +18,8 @@
|
||||
z-index: 18;
|
||||
}
|
||||
|
||||
.hud-panel-media[data-active-tab="news"]:not([data-resized="true"]) {
|
||||
max-height: min(
|
||||
var(--tv-news-default-max-height, calc(100vh - (2 * var(--hud-offset)))),
|
||||
calc(100vh - (2 * var(--hud-offset)))
|
||||
);
|
||||
.hud-panel-media:has(.tv-panel-meta-wrap.is-collapsed) {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.hud-panel-media.is-reforming {
|
||||
@@ -37,6 +34,10 @@
|
||||
gap: var(--hud-gap-xs);
|
||||
}
|
||||
|
||||
.hud-panel-media:has(.tv-panel-meta-wrap.is-collapsed) .hud-panel__header {
|
||||
margin-bottom: var(--hud-gap-sm);
|
||||
}
|
||||
|
||||
.hud-panel-media .hud-panel__title-group {
|
||||
flex: 0 0 auto;
|
||||
min-width: auto;
|
||||
@@ -54,8 +55,7 @@
|
||||
user-select: auto;
|
||||
}
|
||||
|
||||
.hud-panel-media .hud-panel__header .tv-panel-select,
|
||||
.hud-panel-media .hud-panel__header .media-panel-tab {
|
||||
.hud-panel-media .hud-panel__header .tv-panel-select {
|
||||
cursor: pointer;
|
||||
user-select: auto;
|
||||
}
|
||||
@@ -68,10 +68,6 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tv-panel-header-controls--news {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.tv-panel-content {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
@@ -88,6 +84,10 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.tv-tab-pane:has(.tv-panel-meta-wrap.is-collapsed) {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.tv-panel-toolbar-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -95,13 +95,6 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tv-panel-status {
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.tv-panel-select {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
@@ -124,7 +117,8 @@
|
||||
|
||||
.tv-panel-meta-wrap {
|
||||
overflow: hidden;
|
||||
max-height: calc(120px * var(--hud-scale));
|
||||
flex: 0 0 auto;
|
||||
max-height: none;
|
||||
opacity: 1;
|
||||
transition: max-height 0.22s ease, opacity 0.18s ease, margin 0.22s ease;
|
||||
}
|
||||
@@ -140,24 +134,70 @@
|
||||
.tv-panel-meta {
|
||||
display: grid;
|
||||
gap: calc(4px * var(--hud-scale));
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.tv-panel-title-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: calc(6px * var(--hud-scale));
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tv-panel-title {
|
||||
min-width: 0;
|
||||
color: var(--hud-text);
|
||||
font-size: calc(0.96rem * var(--hud-scale));
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tv-panel-tag {
|
||||
flex: 0 0 auto;
|
||||
border: 1px solid rgba(137, 179, 217, 0.22);
|
||||
border-radius: calc(999px * var(--hud-scale));
|
||||
background: rgba(108, 153, 192, 0.12);
|
||||
color: rgba(214, 232, 248, 0.86);
|
||||
padding: calc(2px * var(--hud-scale)) calc(7px * var(--hud-scale));
|
||||
font-size: calc(0.62rem * var(--hud-scale));
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.tv-panel-tag--status {
|
||||
border-color: rgba(111, 213, 161, 0.34);
|
||||
background: rgba(111, 213, 161, 0.13);
|
||||
color: rgba(174, 244, 202, 0.92);
|
||||
}
|
||||
|
||||
.tv-panel-tag--warning {
|
||||
border-color: rgba(255, 209, 102, 0.36);
|
||||
background: rgba(255, 209, 102, 0.13);
|
||||
color: rgba(255, 226, 149, 0.92);
|
||||
}
|
||||
|
||||
.tv-panel-tag--error {
|
||||
border-color: rgba(255, 117, 117, 0.36);
|
||||
background: rgba(255, 117, 117, 0.13);
|
||||
color: rgba(255, 184, 184, 0.94);
|
||||
}
|
||||
|
||||
.tv-panel-subtitle {
|
||||
color: var(--hud-text-muted);
|
||||
font-size: calc(0.74rem * var(--hud-scale));
|
||||
line-height: 1.35;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tv-panel-notes {
|
||||
color: var(--hud-text-soft);
|
||||
font-size: calc(0.68rem * var(--hud-scale));
|
||||
line-height: 1.45;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tv-panel-catalog {
|
||||
@@ -165,6 +205,8 @@
|
||||
font-size: calc(0.66rem * var(--hud-scale));
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tv-panel-player {
|
||||
@@ -203,37 +245,6 @@
|
||||
background: #050a14;
|
||||
}
|
||||
|
||||
.media-panel-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: calc(8px * var(--hud-scale));
|
||||
}
|
||||
|
||||
.media-panel-tab {
|
||||
border: 1px solid rgba(201, 225, 247, 0.12);
|
||||
border-radius: calc(12px * var(--hud-scale));
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: var(--hud-text-muted);
|
||||
padding: calc(9px * var(--hud-scale)) calc(12px * var(--hud-scale));
|
||||
font-size: calc(0.78rem * var(--hud-scale));
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
cursor: pointer;
|
||||
transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease;
|
||||
}
|
||||
|
||||
.media-panel-tab:hover {
|
||||
color: var(--hud-text);
|
||||
border-color: rgba(214, 235, 255, 0.18);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.media-panel-tab--active {
|
||||
color: var(--hud-accent-strong);
|
||||
border-color: rgba(120, 180, 255, 0.24);
|
||||
background: rgba(120, 180, 255, 0.12);
|
||||
}
|
||||
|
||||
.tv-tab-pane[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -345,9 +356,9 @@
|
||||
}
|
||||
|
||||
.earth-app.layout-expanded .hud-panel-media:not([data-dragged="true"]) {
|
||||
bottom: var(--hud-offset);
|
||||
top: var(--hud-offset);
|
||||
right: var(--hud-offset);
|
||||
transform: translate(calc(100% - var(--hud-offset)), calc(100% - var(--hud-offset)));
|
||||
transform: translate(calc(100% - var(--hud-offset)), calc(-100% + var(--hud-offset)));
|
||||
}
|
||||
|
||||
/* Media panel keeps its fixed width on all screen sizes.
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"ADMIN":"Fiji","NAME_EN":"Fiji","CONTINENT":"Oceania","ADM0_A3":"FJI","ISO_A3":"FJI","NAME":"Fiji","ISO_A2":"FJ","NAME_ZH":"斐济"},"geometry":{"type":"MultiPolygon","coordinates":[[[[180,-16.067133],[180,-16.555217],[179.364143,-16.801354],[178.725059,-17.012042],[178.596839,-16.63915],[179.096609,-16.433984],[179.413509,-16.379054],[180,-16.067133]]],[[[178.12557,-17.50481],[178.3736,-17.33992],[178.71806,-17.62846],[178.55271,-18.15059],[177.93266,-18.28799],[177.38146,-18.16432],[177.28504,-17.72465],[177.67087,-17.38114],[178.12557,-17.50481]]],[[[-179.79332,-16.020882],[-179.917369,-16.501783],[-180,-16.555217],[-180,-16.067133],[-179.79332,-16.020882]]]]}},{"type":"Feature","properties":{"ADMIN":"United Republic of Tanzania","NAME_EN":"Tanzania","CONTINENT":"Africa","ADM0_A3":"TZA","ISO_A3":"TZA","NAME":"Tanzania","ISO_A2":"TZ","NAME_ZH":"坦桑尼亚"},"geometry":{"type":"Polygon","coordinates":[[[33.903711,-0.95],[34.07262,-1.05982],[37.69869,-3.09699],[37.7669,-3.67712],[39.20222,-4.67677],[38.74054,-5.90895],[38.79977,-6.47566],[39.44,-6.84],[39.47,-7.1],[39.19469,-7.7039],[39.25203,-8.00781],[39.18652,-8.48551],[39.53574,-9.11237],[39.9496,-10.0984],[40.316586,-10.317098],[40.31659,-10.3171],[39.521,-10.89688],[38.427557,-11.285202],[37.82764,-11.26879],[37.47129,-11.56876],[36.775151,-11.594537],[36.514082,-11.720938],[35.312398,-11.439146],[34.559989,-11.52002],[34.28,-10.16],[33.940838,-9.693674],[33.73972,-9.41715],[32.759375,-9.230599],[32.191865,-8.930359],[31.556348,-8.762049],[31.157751,-8.594579],[30.74001,-8.340006],[30.740015,-8.340007],[30.199997,-7.079981],[29.620032,-6.520015],[29.419993,-5.939999],[29.519987,-5.419979],[29.339998,-4.499983],[29.753512,-4.452389],[30.11632,-4.09012],[30.50554,-3.56858],[30.75224,-3.35931],[30.74301,-3.03431],[30.52766,-2.80762],[30.469674,-2.413855],[30.46967,-2.41383],[30.758309,-2.28725],[30.816135,-1.698914],[30.419105,-1.134659],[30.76986,-1.01455],[31.86617,-1.02736],[33.903711,-0.95]]]}},{"type":"Feature","properties":{"ADMIN":"Western Sahara","NAME_EN":"Western Sahara","CONTINENT":"Africa","ADM0_A3":"SAH","ISO_A3":"ESH","NAME":"W. Sahara","ISO_A2":"EH","NAME_ZH":"西撒哈拉"},"geometry":{"type":"Polygon","coordinates":[[[-8.66559,27.656426],[-8.665124,27.589479],[-8.6844,27.395744],[-8.687294,25.881056],[-11.969419,25.933353],[-11.937224,23.374594],[-12.874222,23.284832],[-13.118754,22.77122],[-12.929102,21.327071],[-16.845194,21.333323],[-17.063423,20.999752],[-17.020428,21.42231],[-17.002962,21.420734],[-14.750955,21.5006],[-14.630833,21.86094],[-14.221168,22.310163],[-13.89111,23.691009],[-12.500963,24.770116],[-12.030759,26.030866],[-11.71822,26.104092],[-11.392555,26.883424],[-10.551263,26.990808],[-10.189424,26.860945],[-9.735343,26.860945],[-9.413037,27.088476],[-8.794884,27.120696],[-8.817828,27.656426],[-8.66559,27.656426]]]}},{"type":"Feature","properties":{"ADMIN":"Canada","NAME_EN":"Canada","CONTINENT":"North America","ADM0_A3":"CAN","ISO_A3":"CAN","NAME":"Canada","ISO_A2":"CA","NAME_ZH":"加拿大"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-122.84,49],[-122.97421,49.002538],[-124.91024,49.98456],[-125.62461,50.41656],[-127.43561,50.83061],[-127.99276,51.71583],[-127.85032,52.32961],[-129.12979,52.75538],[-129.30523,53.56159],[-130.51497,54.28757],[-130.536109,54.802754],[-130.53611,54.80278],[-129.98,55.285],[-130.00778,55.91583],[-131.70781,56.55212],[-132.73042,57.69289],[-133.35556,58.41028],[-134.27111,58.86111],[-134.945,59.27056],[-135.47583,59.78778],[-136.47972,59.46389],[-137.4525,58.905],[-138.34089,59.56211],[-139.039,60],[-140.013,60.27682],[-140.99778,60.30639],[-140.9925,66.00003],[-140.986,69.712],[-140.985988,69.711998],[-139.12052,69.47102],[-137.54636,68.99002],[-136.50358,68.89804],[-135.62576,69.31512],[-134.41464,69.62743],[-132.92925,69.50534],[-131.43136,69.94451],[-129.79471,70.19369],[-129.10773,69.77927],[-128.36156,70.01286],[-128.13817,70.48384],[-127.44712,70.37721],[-125.75632,69.48058],[-124.42483,70.1584],[-124.28968,69.39969],[-123.06108,69.56372],[-122.6835,69.85553],[-121.47226,69.79778],[-119.94288,69.37786],[-117.60268,69.01128],[-116.22643,68.84151],[-115.2469,68.90591],[-113.89794,68.3989],[-115.30489,67.90261],[-113.49727,67.68815],[-110.798,67.80612],[-109.94619,67.98104],[-108.8802,67.38144],[-107.79239,67.88736],[-108.81299,68.31164],[-108.16721,68.65392],[-106.95,68.7],[-106.15,68.8],[-105.34282,68.56122],[-104.33791,68.018],[-103.22115,68.09775],[-101.45433,67.64689],[-99.90195,67.80566],[-98.4432,67.78165],[-98.5586,68.40394],[-97.66948,68.57864],[-96.11991,68.23939],[-96.12588,67.29338],[-95.48943,68.0907],[-94.685,68.06383],[-94.23282,69.06903],[-95.30408,69.68571],[-96.47131,70.08976],[-96.39115,71.19482],[-95.2088,71.92053],[-93.88997,71.76015],[-92.87818,71.31869],[-91.51964,70.19129],[-92.40692,69.69997],[-90.5471,69.49766],[-90.55151,68.47499],[-89.21515,69.25873],[-88.01966,68.61508],[-88.3Line truncated
|
||||
@@ -8,6 +8,9 @@
|
||||
{
|
||||
"imports": {
|
||||
"three": "https://esm.sh/three@0.128.0",
|
||||
"pmtiles": "https://esm.sh/pmtiles@4.4.1",
|
||||
"@mapbox/vector-tile": "https://esm.sh/@mapbox/vector-tile@2.0.4",
|
||||
"pbf": "https://esm.sh/pbf@4.0.1",
|
||||
"simplex-noise": "https://esm.sh/simplex-noise@4.0.1",
|
||||
"satellite.js": "https://esm.sh/satellite.js@5.0.0",
|
||||
"hls.js": "https://esm.sh/hls.js@1.6.15",
|
||||
@@ -199,16 +202,6 @@
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="layer-row" data-layer-name="轨迹 trails">
|
||||
<span class="material-symbols-rounded layer-row-icon">timeline</span>
|
||||
<div class="layer-row-copy">
|
||||
<span class="layer-row-label">轨迹</span>
|
||||
<span class="layer-row-meta">Trails</span>
|
||||
</div>
|
||||
<button id="toggle-trails" class="layer-row-toggle active" type="button" role="switch" aria-checked="true" title="切换轨迹显示">
|
||||
<span class="layer-row-toggle-track"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="layer-row" data-layer-name="卫星 satellites">
|
||||
<span class="material-symbols-rounded layer-row-icon">satellite_alt</span>
|
||||
<div class="layer-row-copy">
|
||||
@@ -523,7 +516,7 @@
|
||||
<div id="media-panel" class="hud-panel hud-panel-media hud-panel-draggable" data-panel-key="media-panel" data-drag-self="true">
|
||||
<div class="hud-panel__header hud-panel-drag-handle">
|
||||
<div class="hud-panel__title-group">
|
||||
<span class="hud-panel-title hud-panel__title tv-panel-header-title">媒体情报</span>
|
||||
<span class="hud-panel-title hud-panel__title tv-panel-header-title">Live 新闻</span>
|
||||
</div>
|
||||
<div id="tv-header-controls-live" class="tv-panel-header-controls tv-panel-header-controls--live">
|
||||
<select id="tv-source-select" class="tv-panel-select" aria-label="选择新闻直播源"></select>
|
||||
@@ -539,32 +532,22 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="tv-header-controls-news" class="tv-panel-header-controls tv-panel-header-controls--news" hidden>
|
||||
<div class="news-panel-title-row">
|
||||
<span id="news-region-chip" class="news-region-chip hud-panel__chip">global</span>
|
||||
</div>
|
||||
<div class="tv-panel-toolbar-actions">
|
||||
<button id="news-refresh" class="hud-panel__action hud-panel__action--refresh" type="button" title="刷新新闻源" aria-label="刷新新闻源">
|
||||
<span class="material-symbols-rounded">refresh</span>
|
||||
</button>
|
||||
<button id="news-open-external" class="hud-panel__action hud-panel__action--external" type="button" title="打开源站" aria-label="打开源站">
|
||||
<span class="material-symbols-rounded">open_in_new</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hud-panel__actions">
|
||||
<button class="hud-panel-close hud-panel__action hud-panel__action--close" type="button" data-close-panel="media-panel" aria-label="关闭媒体情报面板">
|
||||
<button class="hud-panel-close hud-panel__action hud-panel__action--close" type="button" data-close-panel="media-panel" aria-label="关闭 Live 新闻面板">
|
||||
<span class="material-symbols-rounded">close</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tv-panel-content">
|
||||
<section id="tv-panel" class="tv-tab-pane tv-tab-pane--active" aria-labelledby="tv-tab-live">
|
||||
<section id="tv-panel" class="tv-tab-pane tv-tab-pane--active">
|
||||
<div class="tv-panel-meta-wrap" id="tv-meta-wrap">
|
||||
<div class="tv-panel-meta" id="tv-panel-meta">
|
||||
<span id="tv-source-status" class="tv-panel-status">等待加载直播源</span>
|
||||
<div id="tv-source-title" class="tv-panel-title">暂无可用频道</div>
|
||||
<div class="tv-panel-title-row">
|
||||
<div id="tv-source-title" class="tv-panel-title">暂无可用频道</div>
|
||||
<span id="tv-source-origin" class="tv-panel-tag">待加载</span>
|
||||
<span id="tv-source-status" class="tv-panel-tag tv-panel-tag--status">等待加载</span>
|
||||
</div>
|
||||
<div id="tv-source-meta" class="tv-panel-subtitle">当前未配置可播放新闻直播源</div>
|
||||
<div id="tv-source-catalog" class="tv-panel-catalog">频道目录待同步</div>
|
||||
<div id="tv-source-notes" class="tv-panel-notes">支持后台配置默认源与采集器补充源。</div>
|
||||
@@ -584,34 +567,8 @@
|
||||
<video id="tv-video" class="tv-panel-video" hidden controls autoplay muted playsinline></video>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="news-panel" class="tv-tab-pane tv-tab-pane--news" aria-labelledby="tv-tab-news" hidden>
|
||||
<div id="news-panel-body" class="news-panel-body">
|
||||
<div class="news-panel-subtitle">跟随地球正面视角自动切换区域新闻</div>
|
||||
|
||||
<div class="news-panel-focus">
|
||||
<div>
|
||||
<div class="news-focus-kicker">当前关注区域</div>
|
||||
<div id="news-focus-label" class="news-focus-label">全球焦点</div>
|
||||
<div id="news-focus-coords" class="news-focus-coords">跟随当前视角自动聚焦</div>
|
||||
</div>
|
||||
<div id="news-source-count" class="news-source-count">0 路聚合源</div>
|
||||
</div>
|
||||
|
||||
<div class="news-board">
|
||||
<div id="news-board-status" class="news-board-status">正在准备全球态势新闻...</div>
|
||||
<div id="news-board-list" class="news-board-list"></div>
|
||||
<div id="news-board-empty" class="news-board-empty" hidden>正在准备全球态势新闻聚合源...</div>
|
||||
</div>
|
||||
</div>
|
||||
<a id="news-feed-anchor" hidden rel="noreferrer noopener" target="_blank"></a>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="media-panel-tabs" role="tablist" aria-label="媒体情报切换">
|
||||
<button id="tv-tab-live" class="media-panel-tab media-panel-tab--active" type="button" role="tab" aria-selected="true" aria-controls="tv-panel">电视直播</button>
|
||||
<button id="tv-tab-news" class="media-panel-tab" type="button" role="tab" aria-selected="false" aria-controls="news-panel">态势聚合</button>
|
||||
</div>
|
||||
<div class="tv-panel-edge" data-edge="r"></div>
|
||||
<div class="tv-panel-edge" data-edge="b"></div>
|
||||
<div class="tv-panel-edge" data-edge="l"></div>
|
||||
@@ -619,6 +576,59 @@
|
||||
<div class="tv-panel-edge" data-edge="bl"></div>
|
||||
</div>
|
||||
|
||||
<button id="desktop-news-ticker" class="earth-news-ticker" type="button" aria-label="打开态势新闻">
|
||||
<span id="news-ticker-region" class="earth-news-ticker__region">GLOBAL</span>
|
||||
<span class="earth-news-ticker__viewport">
|
||||
<span id="news-ticker-track" class="earth-news-ticker__track">正在准备全球态势新闻...</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div id="news-hud-panel" class="hud-panel earth-news-hud hud-panel-draggable hud-panel-hidden" role="dialog" aria-modal="false" aria-label="态势聚合新闻">
|
||||
<div class="hud-panel__header earth-news-hud__header hud-panel-drag-handle">
|
||||
<div class="hud-panel__title-group">
|
||||
<span class="hud-panel-title hud-panel__title">态势聚合新闻</span>
|
||||
<span id="news-region-chip" class="news-region-chip hud-panel__chip">global</span>
|
||||
</div>
|
||||
<div class="hud-panel__actions">
|
||||
<button id="news-refresh" class="hud-panel__action hud-panel__action--refresh" type="button" title="刷新新闻源" aria-label="刷新新闻源">
|
||||
<span class="material-symbols-rounded">refresh</span>
|
||||
</button>
|
||||
<button id="news-open-external" class="hud-panel__action hud-panel__action--external" type="button" title="打开源站" aria-label="打开源站">
|
||||
<span class="material-symbols-rounded">open_in_new</span>
|
||||
</button>
|
||||
<button id="news-hud-close" class="hud-panel-close hud-panel__action hud-panel__action--close" type="button" aria-label="收起态势新闻">
|
||||
<span class="material-symbols-rounded">close</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="news-panel" class="earth-news-hud__body">
|
||||
<div id="news-panel-body" class="news-panel-body">
|
||||
<div class="news-panel-subtitle">跟随地球正面视角自动切换区域新闻</div>
|
||||
|
||||
<div class="news-panel-focus">
|
||||
<div>
|
||||
<div class="news-focus-kicker">当前关注区域</div>
|
||||
<div id="news-focus-label" class="news-focus-label">全球焦点</div>
|
||||
<div id="news-focus-coords" class="news-focus-coords">跟随当前视角自动聚焦</div>
|
||||
</div>
|
||||
<div id="news-source-count" class="news-source-count">0 路聚合源</div>
|
||||
</div>
|
||||
|
||||
<div class="news-board">
|
||||
<div id="news-board-status" class="news-board-status">正在准备全球态势新闻...</div>
|
||||
<div id="news-board-list" class="news-board-list"></div>
|
||||
<div id="news-board-empty" class="news-board-empty" hidden>正在准备全球态势新闻聚合源...</div>
|
||||
</div>
|
||||
</div>
|
||||
<a id="news-feed-anchor" hidden rel="noreferrer noopener" target="_blank"></a>
|
||||
</div>
|
||||
<div class="earth-news-hud-edge" data-edge="r"></div>
|
||||
<div class="earth-news-hud-edge" data-edge="b"></div>
|
||||
<div class="earth-news-hud-edge" data-edge="l"></div>
|
||||
<div class="earth-news-hud-edge" data-edge="br"></div>
|
||||
<div class="earth-news-hud-edge" data-edge="bl"></div>
|
||||
</div>
|
||||
|
||||
<div id="status-message" class="earth-status-message" aria-live="polite" aria-atomic="true"></div>
|
||||
<div id="tooltip" class="earth-tooltip"></div>
|
||||
<div id="earth-mobile-popup" class="earth-mobile-popup" hidden aria-live="polite">
|
||||
@@ -879,6 +889,17 @@
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-satellite-display-style="ground_footprint" aria-pressed="true">真实地表覆盖</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">悬停提示</span>
|
||||
<span class="earth-mobile-settings-subtitle">控制鼠标悬停地表时显示国家、位置或完整信息</span>
|
||||
</div>
|
||||
<div class="earth-mobile-settings-segmented" role="group" aria-label="移动端选择悬停提示内容">
|
||||
<button type="button" class="earth-mobile-settings-pill" data-surface-hover-info-mode="country" aria-pressed="false">国家</button>
|
||||
<button type="button" class="earth-mobile-settings-pill" data-surface-hover-info-mode="position" aria-pressed="false">位置</button>
|
||||
<button type="button" class="earth-mobile-settings-pill is-active" data-surface-hover-info-mode="full" aria-pressed="true">完整</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="earth-mobile-settings-card">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">卫星呼吸闪烁</span>
|
||||
@@ -889,6 +910,26 @@
|
||||
<span class="earth-mobile-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-mobile-settings-card">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">真实卫星高度</span>
|
||||
<span class="earth-mobile-settings-subtitle">按真实轨道高度压缩分层显示</span>
|
||||
</div>
|
||||
<span class="earth-mobile-settings-switch">
|
||||
<input type="checkbox" data-satellite-real-altitude-toggle checked>
|
||||
<span class="earth-mobile-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-mobile-settings-card">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">轨迹显示</span>
|
||||
<span class="earth-mobile-settings-subtitle">控制卫星轨迹线显示</span>
|
||||
</div>
|
||||
<span class="earth-mobile-settings-switch">
|
||||
<input type="checkbox" data-trails-toggle checked>
|
||||
<span class="earth-mobile-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-mobile-settings-card">
|
||||
<div class="earth-mobile-settings-copy">
|
||||
<span class="earth-mobile-settings-label">低缩放圆点</span>
|
||||
@@ -1180,6 +1221,38 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="earth-settings-item earth-settings-item--stacked">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">悬停提示</span>
|
||||
<span class="earth-settings-item-subtitle">控制鼠标悬停地表时显示国家、位置或完整信息。</span>
|
||||
</div>
|
||||
<div class="earth-settings-segmented" role="group" aria-label="选择悬停提示内容">
|
||||
<button
|
||||
type="button"
|
||||
class="earth-settings-segmented-btn"
|
||||
data-surface-hover-info-mode="country"
|
||||
aria-pressed="false"
|
||||
>
|
||||
国家
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="earth-settings-segmented-btn"
|
||||
data-surface-hover-info-mode="position"
|
||||
aria-pressed="false"
|
||||
>
|
||||
位置
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="earth-settings-segmented-btn is-active"
|
||||
data-surface-hover-info-mode="full"
|
||||
aria-pressed="true"
|
||||
>
|
||||
完整
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<label class="earth-settings-item" for="toggle-satellite-idle-breathing">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">卫星呼吸闪烁</span>
|
||||
@@ -1190,6 +1263,26 @@
|
||||
<span class="earth-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-settings-item" for="toggle-satellite-real-altitude">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">真实卫星高度</span>
|
||||
<span class="earth-settings-item-subtitle">按真实轨道高度压缩分层显示,关闭后使用旧版同层球面</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-satellite-real-altitude" type="checkbox" data-satellite-real-altitude-toggle checked>
|
||||
<span class="earth-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-settings-item" for="toggle-trails-display">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">轨迹显示</span>
|
||||
<span class="earth-settings-item-subtitle">控制卫星轨迹线显示,卫星图层关闭时会自动隐藏</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-trails-display" type="checkbox" data-trails-toggle checked>
|
||||
<span class="earth-settings-switch-track"></span>
|
||||
</span>
|
||||
</label>
|
||||
<label class="earth-settings-item" for="toggle-interactable-compact-dots">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">低缩放圆点</span>
|
||||
@@ -1260,7 +1353,7 @@
|
||||
<label class="earth-settings-item" for="toggle-view-stats">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">全球态势</span>
|
||||
<span class="earth-settings-item-subtitle">控制右上角全球态势统计面板显示</span>
|
||||
<span class="earth-settings-item-subtitle">控制右下角全球态势统计面板显示</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-view-stats" type="checkbox" data-settings-panel="earth-stats">
|
||||
@@ -1270,7 +1363,7 @@
|
||||
<label class="earth-settings-item" for="toggle-view-tv">
|
||||
<div class="earth-settings-copy">
|
||||
<span class="earth-settings-item-title">新闻直播</span>
|
||||
<span class="earth-settings-item-subtitle">控制电视直播 / 态势聚合显示</span>
|
||||
<span class="earth-settings-item-subtitle">控制右上角 Live 新闻面板显示</span>
|
||||
</div>
|
||||
<span class="earth-settings-switch">
|
||||
<input id="toggle-view-tv" type="checkbox" data-settings-panel="media-panel">
|
||||
|
||||
@@ -414,6 +414,14 @@ function blendHexColors(fromHex, toHex, ratio) {
|
||||
return colorScratchA.getHex();
|
||||
}
|
||||
|
||||
function getHaloTintColor(baseColor) {
|
||||
return blendHexColors(
|
||||
BGP_CONFIG.halo.tintNeutralColor,
|
||||
baseColor || BGP_CONFIG.collectorColor,
|
||||
BGP_CONFIG.halo.tintBlend,
|
||||
);
|
||||
}
|
||||
|
||||
function getCollectorDistanceScale(marker, camera) {
|
||||
if (!marker || !camera || BGP_CONFIG.sizeStabilization?.enabled === false) return 1;
|
||||
|
||||
@@ -1131,7 +1139,7 @@ function attachCollectorEffectSprites(marker) {
|
||||
statusCore.renderOrder = 4;
|
||||
|
||||
const coverageHalo = createOverlaySprite({
|
||||
color: BGP_CONFIG.regionColor,
|
||||
color: getHaloTintColor(activity.color),
|
||||
opacity: 0.0,
|
||||
scale: activity.coverageHaloScale * 0.7,
|
||||
});
|
||||
@@ -1524,6 +1532,9 @@ export function updateBGPVisualState(lockedObjectType, lockedObject, camera, cru
|
||||
if (marker.userData.coverageHalo) {
|
||||
marker.userData.coverageHalo.position.copy(marker.position);
|
||||
marker.userData.coverageHalo.material.opacity = coverageOpacity * haloOpacityMul;
|
||||
marker.userData.coverageHalo.material.color.setHex(
|
||||
getHaloTintColor(marker.userData.baseColor),
|
||||
);
|
||||
marker.userData.coverageHalo.scale.set(
|
||||
marker.userData.activity?.coverageHaloScale * 0.82 * (1 + pulse * 0.012) * haloScaleMul,
|
||||
marker.userData.activity?.coverageHaloScale * 0.56 * (1 + pulse * 0.012) * haloScaleMul,
|
||||
@@ -1753,8 +1764,9 @@ export function showBGPEventOverlay(marker, earth) {
|
||||
const overlayItems = [];
|
||||
|
||||
validRegions.forEach((region) => {
|
||||
const eventBaseColor = marker.userData.baseColor || getSeverityColor(marker.userData.severity);
|
||||
const halo = createOverlaySprite({
|
||||
color: BGP_CONFIG.regionColor,
|
||||
color: getHaloTintColor(eventBaseColor),
|
||||
opacity: 0.24,
|
||||
scale: BGP_CONFIG.regionScale,
|
||||
});
|
||||
@@ -1795,9 +1807,11 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
const scaleBoost = Math.min(10, Math.log2(prefixCount + observationCount + 1) * 1.8);
|
||||
const haloScale = BGP_CONFIG.regionScale * 0.7 + scaleBoost;
|
||||
const pulseHaloScale = haloScale * 1.32;
|
||||
const collectorBaseColor = marker.userData.baseColor || BGP_CONFIG.collectorColor;
|
||||
const collectorHaloColor = getHaloTintColor(collectorBaseColor);
|
||||
|
||||
const halo = createOverlaySprite({
|
||||
color: BGP_CONFIG.regionColor,
|
||||
color: collectorHaloColor,
|
||||
opacity: 0.11,
|
||||
scale: haloScale * 0.78,
|
||||
});
|
||||
@@ -1812,7 +1826,7 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
bgpCollectorRadarGroup.add(halo);
|
||||
|
||||
const pulseHalo = createOverlaySprite({
|
||||
color: BGP_CONFIG.collectorColor,
|
||||
color: collectorHaloColor,
|
||||
opacity: 0.065,
|
||||
scale: pulseHaloScale * 0.82,
|
||||
});
|
||||
@@ -1820,7 +1834,7 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
pulseHalo.renderOrder = 1;
|
||||
bgpCollectorRadarGroup.add(pulseHalo);
|
||||
const innerRing = createOverlaySprite({
|
||||
color: BGP_CONFIG.collectorColor,
|
||||
color: collectorBaseColor,
|
||||
opacity: 0.12,
|
||||
scale: Math.max(haloScale * 0.34, 5.5),
|
||||
});
|
||||
@@ -1840,7 +1854,7 @@ export function showBGPCollectorCoverageOverlay(marker, earth, options = {}) {
|
||||
const sectorHalfWidth = Math.PI * 0.22;
|
||||
const startBearing = (sectorRotation - sectorHalfWidth) * (180 / Math.PI);
|
||||
const endBearing = (sectorRotation + sectorHalfWidth) * (180 / Math.PI);
|
||||
const coverageColor = marker.userData.baseColor || BGP_CONFIG.collectorColor;
|
||||
const coverageColor = collectorBaseColor;
|
||||
const boundaryAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.44;
|
||||
const fillAltitude = CONFIG.earthRadius + BGP_COLLECTOR_ALTITUDE_OFFSET + 0.4;
|
||||
const leftBoundaryPoints = createRadialBoundaryPoints(
|
||||
|
||||
@@ -39,6 +39,15 @@ export const SATELLITE_DISPLAY_STYLES = {
|
||||
export const DEFAULT_SATELLITE_DISPLAY_STYLE =
|
||||
SATELLITE_DISPLAY_STYLES.GROUND_FOOTPRINT;
|
||||
|
||||
export const SURFACE_HOVER_INFO_MODES = {
|
||||
COUNTRY: "country",
|
||||
POSITION: "position",
|
||||
FULL: "full",
|
||||
};
|
||||
|
||||
export const DEFAULT_SURFACE_HOVER_INFO_MODE =
|
||||
SURFACE_HOVER_INFO_MODES.FULL;
|
||||
|
||||
export const CRUISE_CONFIG = {
|
||||
dwellMs: 7_000,
|
||||
focusDurationMs: 1_400,
|
||||
@@ -177,9 +186,28 @@ export const TERRAIN_CONFIG = {
|
||||
};
|
||||
|
||||
export const COUNTRY_BOUNDARY_CONFIG = {
|
||||
dataPath: new URL("../data/countries-admin0.min.geojson", import.meta.url).href,
|
||||
tileManifestPath: new URL("../data/boundaries/v1/manifest.json", import.meta.url).href,
|
||||
tileBasePath: new URL("../data/boundaries/v1/", import.meta.url).href,
|
||||
tileProvider: "auto",
|
||||
pmtilesPath: new URL("../data/boundaries/earth-boundaries-china-pov-v1.pmtiles", import.meta.url).href,
|
||||
mvtLayerNames: {
|
||||
boundary: ["boundary_admin0", "boundary_disputed_internal", "coastline"],
|
||||
claim: ["claim_line"],
|
||||
},
|
||||
tileZoomThresholds: [
|
||||
{ minViewZoom: 5.2, tileZoom: 10 },
|
||||
{ minViewZoom: 4.6, tileZoom: 9 },
|
||||
{ minViewZoom: 4.0, tileZoom: 8 },
|
||||
{ minViewZoom: 3.4, tileZoom: 7 },
|
||||
{ minViewZoom: 2.8, tileZoom: 6 },
|
||||
{ minViewZoom: 1.6, tileZoom: 5 },
|
||||
],
|
||||
tilePrefetchRing: 1,
|
||||
tileDebounceMs: 180,
|
||||
tileCacheLimit: 150,
|
||||
lineAltitudeOffset: 0.115,
|
||||
hoverAltitudeOffset: 0.14,
|
||||
hoverAltitudeOffset: 0.115,
|
||||
hoverMissStickyMs: 160,
|
||||
lineColor: 0x7fc7ff,
|
||||
lineOpacity: 0.58,
|
||||
lineRenderOrder: 2.2,
|
||||
@@ -190,13 +218,13 @@ export const COUNTRY_BOUNDARY_CONFIG = {
|
||||
hoverGlowOpacity: 0.38,
|
||||
hoverGlowLineWidth: 3,
|
||||
hoverGlowRenderOrderOffset: 0.01,
|
||||
hoverGlowRadiusOffset: 0.04,
|
||||
hoverGlowRadiusOffset: 0,
|
||||
tintAltitudeOffset: 0.04,
|
||||
tintColor: 0x0b1830,
|
||||
tintRenderOrder: 0.2,
|
||||
landColor: 0x080f1b,
|
||||
landOpacity: 1.0,
|
||||
landAltitudeOffset: 0.08,
|
||||
landAltitudeOffset: 0.32,
|
||||
landRenderOrder: 0.86,
|
||||
landMaskWidth: 2048,
|
||||
landMaskHeight: 1024,
|
||||
@@ -331,7 +359,11 @@ export const SATELLITE_CONFIG = {
|
||||
hydrateFullAfterInitialLoad: false,
|
||||
trailLength: 10,
|
||||
trailLineWidth: 3,
|
||||
displayAltitudeOffset: 8,
|
||||
fallbackAltitudeOffset: 8,
|
||||
altitudeCompressionKm: 1200,
|
||||
maxDisplayAltitudeKm: 40000,
|
||||
minRealAltitudeOffset: 4,
|
||||
maxRealAltitudeOffset: 25,
|
||||
frontFacingDotThreshold: 0.015,
|
||||
overlayRenderOrder: 12,
|
||||
dotBaseSize: 2.8,
|
||||
@@ -339,13 +371,13 @@ export const SATELLITE_CONFIG = {
|
||||
dotZoomScalePower: 1,
|
||||
ringSize: 0.07,
|
||||
apiPath: '/api/v1/visualization/geo/satellites',
|
||||
breathingSpeed: 0.08,
|
||||
breathingScaleAmplitude: 0.15,
|
||||
breathingOpacityMin: 0.5,
|
||||
breathingOpacityMax: 0.8,
|
||||
breathingSpeed: 0.036,
|
||||
breathingScaleAmplitude: 0.22,
|
||||
breathingOpacityMin: 0.34,
|
||||
breathingOpacityMax: 0.9,
|
||||
dotBreathingSpeed: 0.12,
|
||||
dotBreathingScaleAmplitude: 0.2,
|
||||
dotOpacityMin: 0.7,
|
||||
dotBreathingScaleAmplitude: 0.28,
|
||||
dotOpacityMin: 0.42,
|
||||
dotOpacityMax: 1.0
|
||||
};
|
||||
|
||||
@@ -427,6 +459,8 @@ export const BGP_CONFIG = {
|
||||
collectorScale: 11.5,
|
||||
collectorPulseScale: 16.5,
|
||||
collectorCoverageScale: 22.5,
|
||||
tintNeutralColor: 0xffffff,
|
||||
tintBlend: 0.72,
|
||||
},
|
||||
sizeStabilization: {
|
||||
enabled: true,
|
||||
@@ -477,7 +511,7 @@ export const EARTH_MATERIAL_CONFIG = {
|
||||
shininess: 12,
|
||||
emissive: 0x010609,
|
||||
opacity: 1,
|
||||
textureOverlayAltitudeOffset: 0.1,
|
||||
textureOverlayAltitudeOffset: 0.48,
|
||||
textureOverlayOpacity: 0.88,
|
||||
textureOverlayRenderOrder: 0.96,
|
||||
textureOverlaySpecular: 0x05080d,
|
||||
@@ -521,7 +555,9 @@ export const EARTH_MATERIAL_CONFIG = {
|
||||
sunDirection: { x: 1, y: 0.2, z: 0.4 },
|
||||
nightFloor: 0.24,
|
||||
dayBoost: 1.12,
|
||||
featherScale: 0.001,
|
||||
twilightWidth: 0.2,
|
||||
twilightFeatherScale: 1.0,
|
||||
twilightIntensity: 0.14,
|
||||
twilightColor: 0x4ea0ff,
|
||||
nightTintColor: 0x0b1830,
|
||||
|
||||
Vendored
+180
-21
@@ -4,11 +4,13 @@ import * as THREE from "three";
|
||||
import {
|
||||
CONFIG,
|
||||
CRUISE_MODULES,
|
||||
DEFAULT_SURFACE_HOVER_INFO_MODE,
|
||||
DEFAULT_SATELLITE_DISPLAY_STYLE,
|
||||
DEFAULT_CRUISE_MODULES,
|
||||
EARTH_CONFIG,
|
||||
ROTATION_MODE,
|
||||
SATELLITE_DISPLAY_STYLES,
|
||||
SURFACE_HOVER_INFO_MODES,
|
||||
} from "./constants.js";
|
||||
import {
|
||||
setEarthStatValue,
|
||||
@@ -51,7 +53,9 @@ import {
|
||||
getSatelliteCount,
|
||||
getSatelliteDisplayStyle,
|
||||
getSatelliteIdleBreathingEnabled,
|
||||
getSatelliteRealAltitudeEnabled,
|
||||
setSatelliteIdleBreathingEnabled as applySatelliteIdleBreathingEnabled,
|
||||
setSatelliteRealAltitudeEnabled as applySatelliteRealAltitudeEnabled,
|
||||
setSatelliteDisplayStyle as applySatelliteDisplayStyle,
|
||||
} from "./satellites.js";
|
||||
import {
|
||||
@@ -141,7 +145,7 @@ const SETTINGS_SHEET_MAX_SCALE_X = 0.22;
|
||||
const SETTINGS_SHEET_MAX_SCALE_Y = 0.18;
|
||||
const EARTH_SETTINGS_STORAGE_KEY = "planet.earth.settings.v2";
|
||||
const LEGACY_EARTH_SETTINGS_STORAGE_KEY = "planet.earth.settings.v1";
|
||||
const EARTH_SETTINGS_VERSION = 10;
|
||||
const EARTH_SETTINGS_VERSION = 11;
|
||||
const GRID_LINES_DEFAULT_VERSION = 3;
|
||||
const SATELLITE_DISPLAY_DEFAULT_VERSION = 4;
|
||||
const MEDIA_PANEL_DEFAULT_VERSION = 5;
|
||||
@@ -150,6 +154,7 @@ const MOTION_PROVIDER_DEFAULT_VERSION = 7;
|
||||
const MOTION_DEBUG_SKELETON_ONLY_DEFAULT_VERSION = 8;
|
||||
const MEDIA_PANEL_ACTIVE_TAB_DEFAULT_VERSION = 9;
|
||||
const VISUAL_PREFERENCES_DEFAULT_VERSION = 10;
|
||||
const SURFACE_HOVER_INFO_DEFAULT_VERSION = 11;
|
||||
const DEFAULT_EARTH_ZOOM_STEP = 0.01;
|
||||
const ZOOM_STATUS_UPDATE_INTERVAL_MS = 90;
|
||||
const TARGET_SWITCH_ZOOM_IN_PHASE = 0.28;
|
||||
@@ -177,6 +182,9 @@ const ALLOWED_CRUISE_MODULES = new Set(Object.values(CRUISE_MODULES));
|
||||
const ALLOWED_SATELLITE_DISPLAY_STYLES = new Set(
|
||||
Object.values(SATELLITE_DISPLAY_STYLES),
|
||||
);
|
||||
const ALLOWED_SURFACE_HOVER_INFO_MODES = new Set(
|
||||
Object.values(SURFACE_HOVER_INFO_MODES),
|
||||
);
|
||||
const CRUISE_MODULE_LABELS = {
|
||||
[CRUISE_MODULES.BGP]: "BGP",
|
||||
[CRUISE_MODULES.NEWS]: "新闻",
|
||||
@@ -190,6 +198,12 @@ function normalizeMediaPanelActiveTab(tab) {
|
||||
return tab === "news" ? "news" : "live";
|
||||
}
|
||||
|
||||
function normalizeSurfaceHoverInfoMode(mode) {
|
||||
return ALLOWED_SURFACE_HOVER_INFO_MODES.has(mode)
|
||||
? mode
|
||||
: DEFAULT_SURFACE_HOVER_INFO_MODE;
|
||||
}
|
||||
|
||||
function detectLayoutMode() {
|
||||
const width = window.innerWidth;
|
||||
const height = window.innerHeight;
|
||||
@@ -782,6 +796,7 @@ function getCurrentSharedSettingsSnapshot() {
|
||||
rotationMode,
|
||||
cruiseModules: getCruiseModules(),
|
||||
satelliteDisplayStyle: getSatelliteDisplayStyle(),
|
||||
trailsEnabled: getShowTrails(),
|
||||
layerVisibility: Object.fromEntries(
|
||||
getPersistedLayers().map((layer) => [layer.id, Boolean(layer.getVisible?.())]),
|
||||
),
|
||||
@@ -793,7 +808,9 @@ function getCurrentSharedSettingsSnapshot() {
|
||||
motionDebugSkeletonOnly,
|
||||
mediaPanelActiveTab: normalizeMediaPanelActiveTab(getActiveTVTab()),
|
||||
satelliteIdleBreathingEnabled: getSatelliteIdleBreathingEnabled(),
|
||||
satelliteRealAltitudeEnabled: getSatelliteRealAltitudeEnabled(),
|
||||
interactableCompactDotsEnabled: getInteractableCompactDotsEnabled(),
|
||||
surfaceHoverInfoMode: getSurfaceHoverInfoMode(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -834,6 +851,7 @@ function cloneEarthSettings(settings) {
|
||||
cruiseModules: [...(settings.shared.cruiseModules || DEFAULT_CRUISE_MODULES)],
|
||||
satelliteDisplayStyle:
|
||||
settings.shared.satelliteDisplayStyle || DEFAULT_SATELLITE_DISPLAY_STYLE,
|
||||
trailsEnabled: settings.shared.trailsEnabled !== false,
|
||||
terrainOpacity: settings.shared.terrainOpacity,
|
||||
dayNightEnabled: settings.shared.dayNightEnabled,
|
||||
defaultEarthZoom: settings.shared.defaultEarthZoom,
|
||||
@@ -846,8 +864,13 @@ function cloneEarthSettings(settings) {
|
||||
mediaPanelActiveTab: normalizeMediaPanelActiveTab(settings.shared.mediaPanelActiveTab),
|
||||
satelliteIdleBreathingEnabled:
|
||||
settings.shared.satelliteIdleBreathingEnabled !== false,
|
||||
satelliteRealAltitudeEnabled:
|
||||
settings.shared.satelliteRealAltitudeEnabled !== false,
|
||||
interactableCompactDotsEnabled:
|
||||
settings.shared.interactableCompactDotsEnabled !== false,
|
||||
surfaceHoverInfoMode: normalizeSurfaceHoverInfoMode(
|
||||
settings.shared.surfaceHoverInfoMode,
|
||||
),
|
||||
layerVisibility: { ...(settings.shared.layerVisibility || {}) },
|
||||
},
|
||||
views: {
|
||||
@@ -973,11 +996,24 @@ function normalizeEarthSettings(rawSettings, defaults) {
|
||||
typeof sharedSettings?.satelliteIdleBreathingEnabled === "boolean"
|
||||
? sharedSettings.satelliteIdleBreathingEnabled
|
||||
: defaults.shared.satelliteIdleBreathingEnabled;
|
||||
const nextSatelliteRealAltitudeEnabled =
|
||||
typeof sharedSettings?.satelliteRealAltitudeEnabled === "boolean"
|
||||
? sharedSettings.satelliteRealAltitudeEnabled
|
||||
: defaults.shared.satelliteRealAltitudeEnabled;
|
||||
const nextInteractableCompactDotsEnabled =
|
||||
(rawSettings?.version || 0) >= VISUAL_PREFERENCES_DEFAULT_VERSION &&
|
||||
typeof sharedSettings?.interactableCompactDotsEnabled === "boolean"
|
||||
? sharedSettings.interactableCompactDotsEnabled
|
||||
: defaults.shared.interactableCompactDotsEnabled;
|
||||
const nextSurfaceHoverInfoMode =
|
||||
(rawSettings?.version || 0) >= SURFACE_HOVER_INFO_DEFAULT_VERSION
|
||||
? normalizeSurfaceHoverInfoMode(sharedSettings?.surfaceHoverInfoMode)
|
||||
: defaults.shared.surfaceHoverInfoMode;
|
||||
const nextTrailsEnabled = typeof sharedSettings?.trailsEnabled === "boolean"
|
||||
? sharedSettings.trailsEnabled
|
||||
: typeof inputLayerVisibility.trails === "boolean"
|
||||
? inputLayerVisibility.trails
|
||||
: defaults.shared.trailsEnabled;
|
||||
|
||||
return {
|
||||
version: EARTH_SETTINGS_VERSION,
|
||||
@@ -987,6 +1023,7 @@ function normalizeEarthSettings(rawSettings, defaults) {
|
||||
? nextCruiseModules
|
||||
: [...DEFAULT_CRUISE_MODULES],
|
||||
satelliteDisplayStyle: nextSatelliteDisplayStyle,
|
||||
trailsEnabled: nextTrailsEnabled,
|
||||
layerVisibility: normalizedLayerVisibility,
|
||||
terrainOpacity: Number.isFinite(nextTerrainOpacity)
|
||||
? nextTerrainOpacity
|
||||
@@ -998,7 +1035,9 @@ function normalizeEarthSettings(rawSettings, defaults) {
|
||||
motionDebugSkeletonOnly: nextMotionDebugSkeletonOnly,
|
||||
mediaPanelActiveTab: nextMediaPanelActiveTab,
|
||||
satelliteIdleBreathingEnabled: nextSatelliteIdleBreathingEnabled,
|
||||
satelliteRealAltitudeEnabled: nextSatelliteRealAltitudeEnabled,
|
||||
interactableCompactDotsEnabled: nextInteractableCompactDotsEnabled,
|
||||
surfaceHoverInfoMode: nextSurfaceHoverInfoMode,
|
||||
},
|
||||
views: {
|
||||
desktop: {
|
||||
@@ -1187,6 +1226,15 @@ function syncSatelliteIdleBreathingToggle() {
|
||||
});
|
||||
}
|
||||
|
||||
function syncSatelliteRealAltitudeToggle() {
|
||||
const enabled = getSatelliteRealAltitudeEnabled();
|
||||
document.querySelectorAll("[data-satellite-real-altitude-toggle]").forEach((input) => {
|
||||
if (input instanceof HTMLInputElement) {
|
||||
input.checked = enabled;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function syncInteractableCompactDotsToggle() {
|
||||
const enabled = getInteractableCompactDotsEnabled();
|
||||
document.querySelectorAll("[data-interactable-compact-dots-toggle]").forEach((input) => {
|
||||
@@ -1196,6 +1244,17 @@ function syncInteractableCompactDotsToggle() {
|
||||
});
|
||||
}
|
||||
|
||||
function syncSurfaceHoverInfoModeControls() {
|
||||
const activeMode = getSurfaceHoverInfoMode();
|
||||
document.querySelectorAll("[data-surface-hover-info-mode]").forEach((button) => {
|
||||
if (!(button instanceof HTMLButtonElement)) return;
|
||||
const mode = normalizeSurfaceHoverInfoMode(button.dataset.surfaceHoverInfoMode);
|
||||
const active = mode === activeMode;
|
||||
button.classList.toggle("is-active", active);
|
||||
button.setAttribute("aria-pressed", active ? "true" : "false");
|
||||
});
|
||||
}
|
||||
|
||||
export function getCruiseModules() {
|
||||
const configuredModules = earthSettingsState?.shared?.cruiseModules;
|
||||
return normalizeCruiseModules(configuredModules);
|
||||
@@ -1286,6 +1345,27 @@ export function setSatelliteIdleBreathingEnabled(
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function setSatelliteRealAltitudeEnabled(
|
||||
nextEnabled,
|
||||
{ persist = true, suppressStatus = false } = {},
|
||||
) {
|
||||
const enabled = applySatelliteRealAltitudeEnabled(nextEnabled);
|
||||
ensureMutableEarthSettingsState();
|
||||
earthSettingsState.shared.satelliteRealAltitudeEnabled = enabled;
|
||||
syncSatelliteRealAltitudeToggle();
|
||||
|
||||
if (persist) {
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
showStatusMessage(
|
||||
enabled ? "卫星真实高度已开启" : "卫星已切换为旧版同层高度",
|
||||
"info",
|
||||
);
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function setInteractableCompactDotsEnabled(
|
||||
nextEnabled,
|
||||
{ persist = true, suppressStatus = false } = {},
|
||||
@@ -1304,6 +1384,42 @@ export function setInteractableCompactDotsEnabled(
|
||||
return enabled;
|
||||
}
|
||||
|
||||
export function getSurfaceHoverInfoMode() {
|
||||
return normalizeSurfaceHoverInfoMode(earthSettingsState?.shared?.surfaceHoverInfoMode);
|
||||
}
|
||||
|
||||
export function setSurfaceHoverInfoMode(
|
||||
nextMode,
|
||||
{ persist = true, suppressStatus = false } = {},
|
||||
) {
|
||||
const normalizedMode = normalizeSurfaceHoverInfoMode(nextMode);
|
||||
const previousMode = getSurfaceHoverInfoMode();
|
||||
|
||||
if (normalizedMode === previousMode) {
|
||||
syncSurfaceHoverInfoModeControls();
|
||||
return normalizedMode;
|
||||
}
|
||||
|
||||
ensureMutableEarthSettingsState();
|
||||
earthSettingsState.shared.surfaceHoverInfoMode = normalizedMode;
|
||||
syncSurfaceHoverInfoModeControls();
|
||||
|
||||
if (persist) {
|
||||
persistEarthSettings();
|
||||
}
|
||||
if (!suppressStatus) {
|
||||
const label =
|
||||
normalizedMode === SURFACE_HOVER_INFO_MODES.COUNTRY
|
||||
? "国家"
|
||||
: normalizedMode === SURFACE_HOVER_INFO_MODES.POSITION
|
||||
? "位置"
|
||||
: "完整";
|
||||
showStatusMessage(`悬停提示已切换为:${label}`, "info");
|
||||
}
|
||||
|
||||
return normalizedMode;
|
||||
}
|
||||
|
||||
function syncDefaultEarthZoomUi(nextZoom) {
|
||||
const sliders = document.querySelectorAll("#default-earth-size-slider, [data-default-earth-size-slider]");
|
||||
const values = document.querySelectorAll("#default-earth-size-value, [data-default-earth-size-value]");
|
||||
@@ -1371,14 +1487,26 @@ async function applyEarthSettings(settings, { applyLayers = true } = {}) {
|
||||
persist: false,
|
||||
suppressStatus: true,
|
||||
});
|
||||
setTrailsDisplayEnabled(settings.shared.trailsEnabled, {
|
||||
persist: false,
|
||||
silent: true,
|
||||
});
|
||||
setSatelliteIdleBreathingEnabled(settings.shared.satelliteIdleBreathingEnabled, {
|
||||
persist: false,
|
||||
suppressStatus: true,
|
||||
});
|
||||
setSatelliteRealAltitudeEnabled(settings.shared.satelliteRealAltitudeEnabled, {
|
||||
persist: false,
|
||||
suppressStatus: true,
|
||||
});
|
||||
setInteractableCompactDotsEnabled(settings.shared.interactableCompactDotsEnabled, {
|
||||
persist: false,
|
||||
suppressStatus: true,
|
||||
});
|
||||
setSurfaceHoverInfoMode(settings.shared.surfaceHoverInfoMode, {
|
||||
persist: false,
|
||||
suppressStatus: true,
|
||||
});
|
||||
|
||||
if (typeof settings.shared.dayNightEnabled === "boolean") {
|
||||
applyDayNightEnabled(settings.shared.dayNightEnabled, { persist: false });
|
||||
@@ -1774,14 +1902,34 @@ async function setVesselsLayerEnabled(button, enabled, { persist = true, silent
|
||||
}
|
||||
}
|
||||
|
||||
function setTrailsLayerEnabled(button, enabled, { persist = true, silent = false } = {}) {
|
||||
function syncTrailsDisplayControls() {
|
||||
const trailsEnabled = getShowTrails();
|
||||
const disabledState = getLayerDisabledState("trails");
|
||||
document.querySelectorAll("[data-trails-toggle]").forEach((toggle) => {
|
||||
if (!(toggle instanceof HTMLInputElement)) return;
|
||||
toggle.checked = trailsEnabled;
|
||||
toggle.disabled = disabledState.disabled;
|
||||
const label = toggle.closest("label");
|
||||
label?.classList.toggle("is-disabled", disabledState.disabled);
|
||||
if (label instanceof HTMLElement) {
|
||||
if (disabledState.disabled && disabledState.tooltip) {
|
||||
label.title = disabledState.tooltip;
|
||||
} else {
|
||||
label.removeAttribute("title");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function setTrailsDisplayEnabled(enabled, { persist = true, silent = false } = {}) {
|
||||
toggleTrails(enabled);
|
||||
const disabledState = getLayerDisabledState("trails");
|
||||
setLayerButtonState(button, {
|
||||
setLayerButtonState(getLayerButton("trails"), {
|
||||
active: enabled,
|
||||
disabled: disabledState.disabled,
|
||||
tooltip: disabledState.tooltip || (enabled ? "隐藏轨迹" : "显示轨迹"),
|
||||
});
|
||||
syncTrailsDisplayControls();
|
||||
syncMobileLayerCards();
|
||||
if (persist) persistEarthSettings();
|
||||
if (!silent) {
|
||||
@@ -1798,6 +1946,7 @@ function syncTrailsAvailability() {
|
||||
disabled: disabledState.disabled,
|
||||
tooltip: disabledState.tooltip || (trailsEnabled ? "隐藏轨迹" : "显示轨迹"),
|
||||
});
|
||||
syncTrailsDisplayControls();
|
||||
syncMobileLayerCards();
|
||||
}
|
||||
|
||||
@@ -2021,23 +2170,6 @@ function getBuiltinLayerDefinitions() {
|
||||
setVisible: (visible, options = {}) =>
|
||||
setSatellitesLayerEnabled(getLayerButton("satellites"), visible, options),
|
||||
},
|
||||
{
|
||||
id: "trails",
|
||||
buttonId: "toggle-trails",
|
||||
icon: "timeline",
|
||||
label: "轨迹",
|
||||
meta: "Trails",
|
||||
keywords: "轨迹 trails",
|
||||
defaultActive: true,
|
||||
displayOrder: 20,
|
||||
startupPriority: null,
|
||||
startupMode: "visible",
|
||||
startupLabel: "轨迹",
|
||||
startupMessage: "",
|
||||
getVisible: () => getShowTrails(),
|
||||
setVisible: (visible, options = {}) =>
|
||||
setTrailsLayerEnabled(getLayerButton("trails"), visible, options),
|
||||
},
|
||||
{
|
||||
id: "terrain",
|
||||
buttonId: "toggle-terrain",
|
||||
@@ -2609,6 +2741,7 @@ function setupSettingsControls() {
|
||||
const rotationModeButtons = document.querySelectorAll("[data-rotation-mode]");
|
||||
const cruiseModuleButtons = document.querySelectorAll("[data-cruise-module-toggle]");
|
||||
const satelliteDisplayStyleButtons = document.querySelectorAll("[data-satellite-display-style]");
|
||||
const surfaceHoverInfoModeButtons = document.querySelectorAll("[data-surface-hover-info-mode]");
|
||||
const syncTerrainOpacityUi = (nextOpacity) => {
|
||||
const safeOpacity = Math.round(nextOpacity * 100);
|
||||
terrainOpacitySliders.forEach((slider) => {
|
||||
@@ -2691,6 +2824,14 @@ function setupSettingsControls() {
|
||||
});
|
||||
});
|
||||
|
||||
surfaceHoverInfoModeButtons.forEach((button) => {
|
||||
bindListener(button, "click", (event) => {
|
||||
const target = event.currentTarget;
|
||||
if (!(target instanceof HTMLButtonElement)) return;
|
||||
setSurfaceHoverInfoMode(target.dataset.surfaceHoverInfoMode);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-satellite-idle-breathing-toggle]").forEach((toggle) => {
|
||||
if (!(toggle instanceof HTMLInputElement)) return;
|
||||
bindListener(toggle, "change", () => {
|
||||
@@ -2698,6 +2839,20 @@ function setupSettingsControls() {
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-satellite-real-altitude-toggle]").forEach((toggle) => {
|
||||
if (!(toggle instanceof HTMLInputElement)) return;
|
||||
bindListener(toggle, "change", () => {
|
||||
setSatelliteRealAltitudeEnabled(toggle.checked);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-trails-toggle]").forEach((toggle) => {
|
||||
if (!(toggle instanceof HTMLInputElement)) return;
|
||||
bindListener(toggle, "change", () => {
|
||||
setTrailsDisplayEnabled(toggle.checked);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll("[data-interactable-compact-dots-toggle]").forEach((toggle) => {
|
||||
if (!(toggle instanceof HTMLInputElement)) return;
|
||||
bindListener(toggle, "change", () => {
|
||||
@@ -2744,6 +2899,10 @@ function setupSettingsControls() {
|
||||
syncRotationModeButtons();
|
||||
syncCruiseModuleControls();
|
||||
syncSatelliteDisplayStyleControls();
|
||||
syncSatelliteIdleBreathingToggle();
|
||||
syncSatelliteRealAltitudeToggle();
|
||||
syncInteractableCompactDotsToggle();
|
||||
syncSurfaceHoverInfoModeControls();
|
||||
syncDayNightToggle(dayNightEnabled);
|
||||
syncMotionDebugToggle(motionDebugEnabled);
|
||||
syncMotionProviderControls(motionProvider);
|
||||
@@ -2936,7 +3095,7 @@ function setupDraggableHudPanels() {
|
||||
|
||||
bindListener(handle, "pointerdown", (event) => {
|
||||
if (isMobileLayout()) return;
|
||||
if (event.target.closest(".hud-panel-close, .hud-panel__action, .layer-panel-btn, .info-card-close, .tv-panel-select, .media-panel-tab, .tv-panel-player, .tv-panel-edge, .legend-bar-btn, .news-story-card")) return;
|
||||
if (event.target.closest(".hud-panel-close, .hud-panel__action, .layer-panel-btn, .info-card-close, .tv-panel-select, .tv-panel-player, .tv-panel-edge, .earth-news-hud-edge, .legend-bar-btn, .news-story-card")) return;
|
||||
event.preventDefault();
|
||||
isDragging = true;
|
||||
activePointerId = event.pointerId;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import * as THREE from "three";
|
||||
import { PMTiles } from "pmtiles";
|
||||
import { VectorTile } from "@mapbox/vector-tile";
|
||||
import Pbf from "pbf";
|
||||
import { CONFIG, COUNTRY_BOUNDARY_CONFIG } from "./constants.js";
|
||||
import { latLonToVector3 } from "./utils.js";
|
||||
import { latLonToVector3, screenToEarthCoords, vector3ToLatLon } from "./utils.js";
|
||||
|
||||
// ─── Module state ──────────────────────────────────────────────────────────────
|
||||
let _earthObj = null;
|
||||
@@ -8,21 +11,48 @@ let _features = [];
|
||||
let _landMesh = null;
|
||||
let _tintMesh = null;
|
||||
let _boundaryLines = null;
|
||||
let _coastlineLines = null;
|
||||
let _claimGroup = null;
|
||||
let _hoverGlowLines = null;
|
||||
let _hoverLines = null;
|
||||
let _hoveredFeature = null;
|
||||
let _hoveredGroupKey = null;
|
||||
let _hoverClearTimer = null;
|
||||
let _lastHoverHitAt = 0;
|
||||
let _lastHoverInfo = null;
|
||||
let _hoverGeometryCache = new Map();
|
||||
let _tileManifest = null;
|
||||
let _tileProvider = "pmtiles-mvt";
|
||||
let _pmtilesArchive = null;
|
||||
let _tileCache = new Map();
|
||||
let _tileLru = [];
|
||||
let _inFlightTiles = new Map();
|
||||
let _activeTileKeys = new Set();
|
||||
let _lastTileSignature = "";
|
||||
let _tileUpdateTimer = null;
|
||||
let _visible = false;
|
||||
let _landFillEnabled = true;
|
||||
let _landFillSuppressed = false;
|
||||
let _tintEnabled = false;
|
||||
let _landTexture = null;
|
||||
let _loaded = false;
|
||||
let _loadPromise = null;
|
||||
let _tileAssetVersion = "";
|
||||
|
||||
const OCEAN_HEX = 0x010609;
|
||||
// ─── Equirectangular land/ocean fill texture ──────────────────────────────────
|
||||
|
||||
function configureLandMaskTexture(texture) {
|
||||
texture.wrapS = THREE.ClampToEdgeWrapping;
|
||||
texture.wrapT = THREE.ClampToEdgeWrapping;
|
||||
texture.minFilter = THREE.LinearMipmapLinearFilter;
|
||||
texture.magFilter = THREE.LinearFilter;
|
||||
texture.generateMipmaps = true;
|
||||
texture.anisotropy = 1;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
|
||||
function hexToStyle(hex) {
|
||||
return `#${hex.toString(16).padStart(6, "0")}`;
|
||||
}
|
||||
@@ -35,32 +65,14 @@ function hexToRgb(hex) {
|
||||
];
|
||||
}
|
||||
|
||||
function buildLandTexture(features) {
|
||||
const width = COUNTRY_BOUNDARY_CONFIG.landMaskWidth;
|
||||
const height = COUNTRY_BOUNDARY_CONFIG.landMaskHeight;
|
||||
|
||||
function drawLandMaskCanvas(features, width, height) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d");
|
||||
const oceanRgb = hexToRgb(OCEAN_HEX);
|
||||
|
||||
if (!ctx) {
|
||||
const oceanData = new Uint8Array(width * height * 4);
|
||||
for (let i = 0; i < oceanData.length; i += 4) {
|
||||
oceanData[i] = oceanRgb[0];
|
||||
oceanData[i + 1] = oceanRgb[1];
|
||||
oceanData[i + 2] = oceanRgb[2];
|
||||
oceanData[i + 3] = 255;
|
||||
}
|
||||
const fallbackTexture = new THREE.DataTexture(
|
||||
oceanData,
|
||||
width,
|
||||
height,
|
||||
THREE.RGBAFormat,
|
||||
);
|
||||
fallbackTexture.needsUpdate = true;
|
||||
return fallbackTexture;
|
||||
return null;
|
||||
}
|
||||
|
||||
// Ocean background
|
||||
@@ -93,21 +105,43 @@ function buildLandTexture(features) {
|
||||
}
|
||||
}
|
||||
|
||||
const imageData = ctx.getImageData(0, 0, width, height);
|
||||
const tex = new THREE.DataTexture(
|
||||
new Uint8Array(imageData.data),
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function buildTextureFromCanvas(canvas) {
|
||||
const tex = new THREE.CanvasTexture(canvas);
|
||||
configureLandMaskTexture(tex);
|
||||
tex.flipY = true;
|
||||
tex.userData = {
|
||||
...(tex.userData || {}),
|
||||
sourceCanvas: canvas,
|
||||
};
|
||||
return tex;
|
||||
}
|
||||
|
||||
function buildFallbackLandTexture(width, height) {
|
||||
const oceanRgb = hexToRgb(OCEAN_HEX);
|
||||
const oceanData = new Uint8Array(width * height * 4);
|
||||
for (let i = 0; i < oceanData.length; i += 4) {
|
||||
oceanData[i] = oceanRgb[0];
|
||||
oceanData[i + 1] = oceanRgb[1];
|
||||
oceanData[i + 2] = oceanRgb[2];
|
||||
oceanData[i + 3] = 255;
|
||||
}
|
||||
const fallbackTexture = new THREE.DataTexture(
|
||||
oceanData,
|
||||
width,
|
||||
height,
|
||||
THREE.RGBAFormat,
|
||||
);
|
||||
tex.wrapS = THREE.ClampToEdgeWrapping;
|
||||
tex.wrapT = THREE.ClampToEdgeWrapping;
|
||||
tex.minFilter = THREE.LinearFilter;
|
||||
tex.magFilter = THREE.LinearFilter;
|
||||
tex.generateMipmaps = false;
|
||||
tex.flipY = true;
|
||||
tex.needsUpdate = true;
|
||||
return tex;
|
||||
return configureLandMaskTexture(fallbackTexture);
|
||||
}
|
||||
|
||||
function buildLandTexture(features) {
|
||||
const width = COUNTRY_BOUNDARY_CONFIG.landMaskWidth;
|
||||
const height = COUNTRY_BOUNDARY_CONFIG.landMaskHeight;
|
||||
const canvas = drawLandMaskCanvas(features, width, height);
|
||||
return canvas ? buildTextureFromCanvas(canvas) : buildFallbackLandTexture(width, height);
|
||||
}
|
||||
|
||||
// ─── Sphere mesh helpers ───────────────────────────────────────────────────────
|
||||
@@ -145,6 +179,14 @@ function makeTintMesh() {
|
||||
|
||||
// ─── Boundary line geometry ────────────────────────────────────────────────────
|
||||
|
||||
function boundaryLineRadius({ claim = false } = {}) {
|
||||
return (
|
||||
CONFIG.earthRadius +
|
||||
COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset +
|
||||
(claim ? 0.018 : 0)
|
||||
);
|
||||
}
|
||||
|
||||
function ringToSegments(ring, radius, out) {
|
||||
const n = ring.length;
|
||||
if (n < 2) return;
|
||||
@@ -161,12 +203,16 @@ function featureToSegments(geom, radius) {
|
||||
geom.coordinates.forEach(ring => ringToSegments(ring, radius, pts));
|
||||
} else if (geom.type === "MultiPolygon") {
|
||||
geom.coordinates.forEach(poly => poly.forEach(ring => ringToSegments(ring, radius, pts)));
|
||||
} else if (geom.type === "LineString") {
|
||||
ringToSegments(geom.coordinates, radius, pts);
|
||||
} else if (geom.type === "MultiLineString") {
|
||||
geom.coordinates.forEach(line => ringToSegments(line, radius, pts));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
function buildBoundaryLines(features) {
|
||||
const r = CONFIG.earthRadius + COUNTRY_BOUNDARY_CONFIG.lineAltitudeOffset;
|
||||
const r = boundaryLineRadius();
|
||||
const mat = new THREE.LineBasicMaterial({
|
||||
color: COUNTRY_BOUNDARY_CONFIG.lineColor,
|
||||
transparent: true,
|
||||
@@ -178,7 +224,7 @@ function buildBoundaryLines(features) {
|
||||
const all = [];
|
||||
for (const feat of features) {
|
||||
const pts = featureToSegments(feat.geometry, r);
|
||||
all.push(...pts);
|
||||
for (const point of pts) all.push(point);
|
||||
}
|
||||
|
||||
const geo = all.length > 0
|
||||
@@ -192,6 +238,350 @@ function buildBoundaryLines(features) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
function isStandaloneCoastlineFeature(feature) {
|
||||
const properties = feature?.properties || {};
|
||||
return (
|
||||
properties.PLANET_LAYER === "coastline" ||
|
||||
properties.featurecla === "Coastline"
|
||||
);
|
||||
}
|
||||
|
||||
function buildClaimLines() {
|
||||
const mat = new THREE.LineDashedMaterial({
|
||||
color: COUNTRY_BOUNDARY_CONFIG.hoverLineColor,
|
||||
transparent: true,
|
||||
opacity: 0.82,
|
||||
dashSize: 0.7,
|
||||
gapSize: 0.42,
|
||||
depthTest: true,
|
||||
depthWrite: false,
|
||||
});
|
||||
const lines = new THREE.LineSegments(new THREE.BufferGeometry(), mat);
|
||||
lines.name = "country-boundary-china-claims";
|
||||
lines.renderOrder = COUNTRY_BOUNDARY_CONFIG.lineRenderOrder + 0.02;
|
||||
lines.visible = false;
|
||||
lines.raycast = () => {};
|
||||
return lines;
|
||||
}
|
||||
|
||||
function makeBoundaryTileObject(features, { claim = false } = {}) {
|
||||
const radius = boundaryLineRadius({ claim });
|
||||
const points = featureListToSegments(features, radius);
|
||||
const geometry = makeLineGeometry(points);
|
||||
const material = claim
|
||||
? _claimGroup?.material?.clone?.() || buildClaimLines().material
|
||||
: _boundaryLines?.material?.clone?.() || new THREE.LineBasicMaterial({
|
||||
color: COUNTRY_BOUNDARY_CONFIG.lineColor,
|
||||
transparent: true,
|
||||
opacity: COUNTRY_BOUNDARY_CONFIG.lineOpacity,
|
||||
depthTest: true,
|
||||
depthWrite: false,
|
||||
});
|
||||
const lines = new THREE.LineSegments(geometry, material);
|
||||
lines.name = claim ? "country-boundary-claim-tile" : "country-boundary-tile";
|
||||
lines.renderOrder = claim
|
||||
? COUNTRY_BOUNDARY_CONFIG.lineRenderOrder + 0.02
|
||||
: COUNTRY_BOUNDARY_CONFIG.lineRenderOrder + 0.01;
|
||||
lines.visible = _visible;
|
||||
lines.raycast = () => {};
|
||||
if (claim && typeof lines.computeLineDistances === "function") {
|
||||
lines.computeLineDistances();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function disposeTileObject(object) {
|
||||
if (!object) return;
|
||||
if (_earthObj) _earthObj.remove(object);
|
||||
object.geometry?.dispose?.();
|
||||
object.material?.dispose?.();
|
||||
}
|
||||
|
||||
function touchTileKey(key) {
|
||||
_tileLru = _tileLru.filter(item => item !== key);
|
||||
_tileLru.push(key);
|
||||
}
|
||||
|
||||
function trimTileCache() {
|
||||
const limit = COUNTRY_BOUNDARY_CONFIG.tileCacheLimit;
|
||||
while (_tileLru.length > limit) {
|
||||
const key = _tileLru.shift();
|
||||
if (!key || _activeTileKeys.has(key)) continue;
|
||||
const cached = _tileCache.get(key);
|
||||
_tileCache.delete(key);
|
||||
disposeTileObject(cached?.object);
|
||||
}
|
||||
}
|
||||
|
||||
function setTileObjectVisible(object, visible) {
|
||||
if (object) object.visible = _visible && visible;
|
||||
}
|
||||
|
||||
function setActiveTileKeys(nextKeys) {
|
||||
_activeTileKeys = new Set(nextKeys);
|
||||
_tileCache.forEach((entry, key) => {
|
||||
setTileObjectVisible(entry.object, _activeTileKeys.has(key));
|
||||
});
|
||||
}
|
||||
|
||||
function tileUrlForKey(key) {
|
||||
const [kind, z, x, y] = key.split("/");
|
||||
const prefix = COUNTRY_BOUNDARY_CONFIG.tileBasePath.replace(/\/?$/, "/");
|
||||
const versionSuffix = _tileAssetVersion ? `?v=${encodeURIComponent(_tileAssetVersion)}` : "";
|
||||
if (kind === "claim") {
|
||||
return `${prefix}china-claims/${z}/${x}/${y}.geojson${versionSuffix}`;
|
||||
}
|
||||
return `${prefix}${z}/${x}/${y}.geojson${versionSuffix}`;
|
||||
}
|
||||
|
||||
function versionedBoundaryAssetUrl(path) {
|
||||
const url = new URL(path, COUNTRY_BOUNDARY_CONFIG.tileBasePath);
|
||||
if (_tileAssetVersion) url.searchParams.set("v", _tileAssetVersion);
|
||||
return url.href;
|
||||
}
|
||||
|
||||
function manifestProvider(manifest) {
|
||||
const configured = COUNTRY_BOUNDARY_CONFIG.tileProvider;
|
||||
if (configured && configured !== "auto") return configured;
|
||||
return manifest?.tileProvider || manifest?.format || "pmtiles-mvt";
|
||||
}
|
||||
|
||||
function manifestPmtilesUrl(manifest) {
|
||||
const fromManifest =
|
||||
manifest?.pmtiles?.url ||
|
||||
manifest?.pmtiles?.path ||
|
||||
manifest?.artifacts?.pmtiles?.url ||
|
||||
manifest?.artifacts?.pmtiles?.path ||
|
||||
manifest?.artifact;
|
||||
if (!fromManifest) return COUNTRY_BOUNDARY_CONFIG.pmtilesPath;
|
||||
return new URL(fromManifest, COUNTRY_BOUNDARY_CONFIG.tileBasePath).href;
|
||||
}
|
||||
|
||||
function ensurePmtilesArchive() {
|
||||
if (_pmtilesArchive) return _pmtilesArchive;
|
||||
const url = manifestPmtilesUrl(_tileManifest);
|
||||
_pmtilesArchive = new PMTiles(url);
|
||||
return _pmtilesArchive;
|
||||
}
|
||||
|
||||
function getMvtLayerNames(kind) {
|
||||
const layerConfig = COUNTRY_BOUNDARY_CONFIG.mvtLayerNames || {};
|
||||
if (kind === "claim") return layerConfig.claim || ["claim_line"];
|
||||
return layerConfig.boundary || ["boundary_admin0", "boundary_disputed_internal", "coastline"];
|
||||
}
|
||||
|
||||
async function loadPmtilesMvtFeatures(key) {
|
||||
const [kind, zText, xText, yText] = key.split("/");
|
||||
const z = Number(zText);
|
||||
const x = Number(xText);
|
||||
const y = Number(yText);
|
||||
if (!Number.isInteger(z) || !Number.isInteger(x) || !Number.isInteger(y)) return [];
|
||||
|
||||
const archive = ensurePmtilesArchive();
|
||||
const tile = await archive.getZxy(z, x, y);
|
||||
if (!tile?.data) return [];
|
||||
|
||||
const vectorTile = new VectorTile(new Pbf(new Uint8Array(tile.data)));
|
||||
const features = [];
|
||||
for (const layerName of getMvtLayerNames(kind)) {
|
||||
const layer = vectorTile.layers[layerName];
|
||||
if (!layer) continue;
|
||||
for (let i = 0; i < layer.length; i++) {
|
||||
const feature = layer.feature(i).toGeoJSON(x, y, z);
|
||||
if (feature?.geometry) features.push(feature);
|
||||
}
|
||||
}
|
||||
return features;
|
||||
}
|
||||
|
||||
async function loadDebugGeojsonFeatures(key) {
|
||||
const resp = await fetch(tileUrlForKey(key));
|
||||
if (!resp.ok) {
|
||||
if (resp.status === 404) return [];
|
||||
throw new Error(`boundary tile ${key} HTTP ${resp.status}`);
|
||||
}
|
||||
const payload = await resp.json();
|
||||
return (payload.features || []).filter(f => f.geometry);
|
||||
}
|
||||
|
||||
async function loadBoundaryTile(key) {
|
||||
if (_tileCache.has(key)) {
|
||||
touchTileKey(key);
|
||||
return _tileCache.get(key);
|
||||
}
|
||||
if (_inFlightTiles.has(key)) return _inFlightTiles.get(key);
|
||||
|
||||
const promise = (async () => {
|
||||
if (_tileProvider !== "pmtiles-mvt") {
|
||||
throw new Error(`不支持的国界瓦片 provider: ${_tileProvider}`);
|
||||
}
|
||||
const features = await loadPmtilesMvtFeatures(key);
|
||||
if (features.length === 0) return null;
|
||||
const entry = {
|
||||
object: makeBoundaryTileObject(features, { claim: key.startsWith("claim/") }),
|
||||
};
|
||||
_earthObj.add(entry.object);
|
||||
_tileCache.set(key, entry);
|
||||
touchTileKey(key);
|
||||
trimTileCache();
|
||||
return entry;
|
||||
})().catch(err => {
|
||||
console.warn("[country-boundaries] tile load failed", key, err);
|
||||
return null;
|
||||
}).finally(() => {
|
||||
_inFlightTiles.delete(key);
|
||||
});
|
||||
|
||||
_inFlightTiles.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
function lonToTileX(lon, zoom) {
|
||||
const n = 2 ** zoom;
|
||||
return Math.max(0, Math.min(n - 1, Math.floor(((lon + 180) / 360) * n)));
|
||||
}
|
||||
|
||||
function latToTileY(lat, zoom) {
|
||||
const n = 2 ** zoom;
|
||||
const clamped = Math.max(-85.05112878, Math.min(85.05112878, lat));
|
||||
const rad = clamped * Math.PI / 180;
|
||||
return Math.max(
|
||||
0,
|
||||
Math.min(n - 1, Math.floor((1 - Math.asinh(Math.tan(rad)) / Math.PI) / 2 * n)),
|
||||
);
|
||||
}
|
||||
|
||||
function tileZoomForViewZoom(viewZoom) {
|
||||
const thresholds = COUNTRY_BOUNDARY_CONFIG.tileZoomThresholds || [];
|
||||
const maxZoom = _tileManifest?.tiles?.maxZoom ?? 0;
|
||||
for (const threshold of thresholds) {
|
||||
if (viewZoom >= threshold.minViewZoom) {
|
||||
return Math.min(threshold.tileZoom, maxZoom);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function bboxFromVisibleEarth(camera, renderer, earth) {
|
||||
if (!camera || !renderer?.domElement || !earth) return null;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
if (rect.width <= 0 || rect.height <= 0) return null;
|
||||
|
||||
const samples = [
|
||||
[rect.left + rect.width * 0.5, rect.top + rect.height * 0.5],
|
||||
[rect.left, rect.top],
|
||||
[rect.right, rect.top],
|
||||
[rect.left, rect.bottom],
|
||||
[rect.right, rect.bottom],
|
||||
[rect.left + rect.width * 0.5, rect.top],
|
||||
[rect.left + rect.width * 0.5, rect.bottom],
|
||||
[rect.left, rect.top + rect.height * 0.5],
|
||||
[rect.right, rect.top + rect.height * 0.5],
|
||||
];
|
||||
const coords = [];
|
||||
for (const [x, y] of samples) {
|
||||
const point = screenToEarthCoords(x, y, camera, earth, renderer.domElement);
|
||||
if (!point) continue;
|
||||
coords.push(vector3ToLatLon(point));
|
||||
}
|
||||
if (coords.length === 0) return null;
|
||||
|
||||
const lats = coords.map(coord => coord.lat);
|
||||
const lons = coords.map(coord => coord.lon);
|
||||
const latMin = Math.max(-85.05112878, Math.min(...lats));
|
||||
const latMax = Math.min(85.05112878, Math.max(...lats));
|
||||
const latPad = Math.max(2, (latMax - latMin) * 0.18);
|
||||
const rawLonMin = Math.max(-180, Math.min(...lons));
|
||||
const rawLonMax = Math.min(180, Math.max(...lons));
|
||||
const rawLonSpan = rawLonMax - rawLonMin;
|
||||
|
||||
if (rawLonSpan > 180) {
|
||||
const shifted = lons.map(lon => lon < 0 ? lon + 360 : lon);
|
||||
const shiftedMin = Math.min(...shifted);
|
||||
const shiftedMax = Math.max(...shifted);
|
||||
const shiftedPad = Math.max(2, (shiftedMax - shiftedMin) * 0.18);
|
||||
const west = shiftedMin - shiftedPad;
|
||||
const east = shiftedMax + shiftedPad;
|
||||
const ranges = [];
|
||||
if (west < 180) ranges.push({ west: Math.max(-180, west), east: 180 });
|
||||
if (east > 180) ranges.push({ west: -180, east: Math.min(180, east - 360) });
|
||||
return {
|
||||
south: Math.max(-85.05112878, latMin - latPad),
|
||||
north: Math.min(85.05112878, latMax + latPad),
|
||||
ranges: ranges.length > 0 ? ranges : [{ west: -180, east: 180 }],
|
||||
};
|
||||
}
|
||||
|
||||
const lonPad = Math.max(2, rawLonSpan * 0.18);
|
||||
return {
|
||||
west: Math.max(-180, rawLonMin - lonPad),
|
||||
south: Math.max(-85.05112878, latMin - latPad),
|
||||
east: Math.min(180, rawLonMax + lonPad),
|
||||
north: Math.min(85.05112878, latMax + latPad),
|
||||
};
|
||||
}
|
||||
|
||||
function tileKeysForBbox(bbox, zoom, { claim = false } = {}) {
|
||||
if (Array.isArray(bbox.ranges)) {
|
||||
return bbox.ranges.flatMap(range =>
|
||||
tileKeysForBbox({ ...bbox, west: range.west, east: range.east, ranges: null }, zoom, { claim }),
|
||||
);
|
||||
}
|
||||
|
||||
const prefetch = COUNTRY_BOUNDARY_CONFIG.tilePrefetchRing;
|
||||
const n = 2 ** zoom;
|
||||
const xMin = lonToTileX(bbox.west, zoom);
|
||||
const xMax = lonToTileX(bbox.east, zoom);
|
||||
const yMin = latToTileY(bbox.north, zoom);
|
||||
const yMax = latToTileY(bbox.south, zoom);
|
||||
const keys = [];
|
||||
for (let x = Math.max(0, xMin - prefetch); x <= Math.min(n - 1, xMax + prefetch); x++) {
|
||||
for (let y = Math.max(0, yMin - prefetch); y <= Math.min(n - 1, yMax + prefetch); y++) {
|
||||
keys.push(`${claim ? "claim" : "boundary"}/${zoom}/${x}/${y}`);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
async function refreshBoundaryTiles({ camera, renderer, earth, viewZoom }) {
|
||||
if (!_loaded || !_visible || !_tileManifest) return;
|
||||
if (_tileProvider === "geojson-high-precision") return;
|
||||
const tileZoom = tileZoomForViewZoom(viewZoom);
|
||||
if (!tileZoom) {
|
||||
_lastTileSignature = "";
|
||||
setActiveTileKeys([]);
|
||||
updateBoundaryLineDimState();
|
||||
return;
|
||||
}
|
||||
|
||||
const bbox = bboxFromVisibleEarth(camera, renderer, earth);
|
||||
if (!bbox) return;
|
||||
const keys = tileKeysForBbox(bbox, tileZoom);
|
||||
if (_tileManifest?.chinaClaims?.available) {
|
||||
keys.push(...tileKeysForBbox(bbox, tileZoom, { claim: true }));
|
||||
}
|
||||
const signature = keys.slice().sort().join("|");
|
||||
if (signature === _lastTileSignature) return;
|
||||
_lastTileSignature = signature;
|
||||
setActiveTileKeys(keys);
|
||||
updateBoundaryLineDimState();
|
||||
|
||||
await Promise.all(keys.map(async key => {
|
||||
const entry = await loadBoundaryTile(key);
|
||||
if (!entry) return;
|
||||
entry.object.userData.tileKey = key;
|
||||
setTileObjectVisible(entry.object, _activeTileKeys.has(key));
|
||||
}));
|
||||
}
|
||||
|
||||
export function updateCountryBoundaryTiles(context = {}) {
|
||||
if (_tileUpdateTimer) return;
|
||||
_tileUpdateTimer = setTimeout(() => {
|
||||
_tileUpdateTimer = null;
|
||||
refreshBoundaryTiles(context);
|
||||
}, COUNTRY_BOUNDARY_CONFIG.tileDebounceMs);
|
||||
}
|
||||
|
||||
function buildHoverLines() {
|
||||
const mat = new THREE.LineBasicMaterial({
|
||||
color: COUNTRY_BOUNDARY_CONFIG.hoverLineColor,
|
||||
@@ -236,6 +626,15 @@ function setBoundaryLinesDimmed(dimmed) {
|
||||
_boundaryLines.material.needsUpdate = true;
|
||||
}
|
||||
|
||||
function updateBoundaryLineDimState() {
|
||||
if (_coastlineLines?.material) {
|
||||
_coastlineLines.material.opacity = COUNTRY_BOUNDARY_CONFIG.lineOpacity;
|
||||
_coastlineLines.material.needsUpdate = true;
|
||||
_coastlineLines.visible = _visible && !_hoveredFeature;
|
||||
}
|
||||
setBoundaryLinesDimmed(Boolean(_hoveredFeature) || _activeTileKeys.size > 0);
|
||||
}
|
||||
|
||||
function setHoverLinesVisible(visible) {
|
||||
const nextVisible = _visible && Boolean(visible);
|
||||
if (_hoverGlowLines) _hoverGlowLines.visible = nextVisible;
|
||||
@@ -243,7 +642,12 @@ function setHoverLinesVisible(visible) {
|
||||
}
|
||||
|
||||
function featureListToSegments(features, radius) {
|
||||
return features.flatMap(f => featureToSegments(f.geometry, radius));
|
||||
const all = [];
|
||||
for (const feature of features) {
|
||||
const points = featureToSegments(feature.geometry, radius);
|
||||
for (const point of points) all.push(point);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
function makeLineGeometry(points) {
|
||||
@@ -265,12 +669,26 @@ function setLineGeometry(line, geometry) {
|
||||
line.geometry = geometry;
|
||||
}
|
||||
|
||||
function cancelPendingHoverClear() {
|
||||
if (!_hoverClearTimer) return;
|
||||
clearTimeout(_hoverClearTimer);
|
||||
_hoverClearTimer = null;
|
||||
}
|
||||
|
||||
function scheduleHoverClear(delayMs) {
|
||||
if (_hoverClearTimer) return;
|
||||
_hoverClearTimer = setTimeout(() => {
|
||||
_hoverClearTimer = null;
|
||||
clearCountryBoundaryHover({ cancelSticky: false });
|
||||
}, Math.max(0, delayMs));
|
||||
}
|
||||
|
||||
function getHoverGeometries(groupKey, features) {
|
||||
const cacheKey = groupKey || features[0] || "__empty__";
|
||||
const cached = _hoverGeometryCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
|
||||
const coreRadius = CONFIG.earthRadius + COUNTRY_BOUNDARY_CONFIG.hoverAltitudeOffset;
|
||||
const coreRadius = boundaryLineRadius();
|
||||
const glowRadius = coreRadius + COUNTRY_BOUNDARY_CONFIG.hoverGlowRadiusOffset;
|
||||
const geometries = {
|
||||
core: markCachedHoverGeometry(
|
||||
@@ -357,6 +775,8 @@ export function createCountryBoundaryLayer(earthObj) {
|
||||
_earthObj = earthObj;
|
||||
_tintMesh = makeTintMesh();
|
||||
_earthObj.add(_tintMesh);
|
||||
_claimGroup = buildClaimLines();
|
||||
_earthObj.add(_claimGroup);
|
||||
}
|
||||
|
||||
/** Fetch GeoJSON, build meshes. Idempotent; safe to call multiple times. */
|
||||
@@ -365,18 +785,71 @@ export async function loadCountryBoundaries() {
|
||||
if (_loadPromise) return _loadPromise;
|
||||
|
||||
_loadPromise = (async () => {
|
||||
const resp = await fetch(COUNTRY_BOUNDARY_CONFIG.dataPath);
|
||||
if (!resp.ok) throw new Error(`国界数据加载失败 HTTP ${resp.status}`);
|
||||
const geojson = await resp.json();
|
||||
let geojson = { type: "FeatureCollection", features: [] };
|
||||
let baseGeojson = null;
|
||||
const manifestResp = await fetch(COUNTRY_BOUNDARY_CONFIG.tileManifestPath, { cache: "no-store" });
|
||||
if (!manifestResp.ok) {
|
||||
throw new Error(`高精度国界 PMTiles manifest 未生成 HTTP ${manifestResp.status}`);
|
||||
}
|
||||
_tileManifest = await manifestResp.json();
|
||||
_tileProvider = manifestProvider(_tileManifest);
|
||||
if (!["pmtiles-mvt", "geojson-high-precision"].includes(_tileProvider)) {
|
||||
throw new Error(`高精度国界 provider 不可用: ${_tileProvider}`);
|
||||
}
|
||||
_tileAssetVersion = [
|
||||
_tileManifest.version,
|
||||
_tileManifest.builtAt,
|
||||
_tileManifest.sourceFeatureCount,
|
||||
_tileManifest.pmtiles?.sha256,
|
||||
].filter(Boolean).join("-");
|
||||
if (_tileProvider === "pmtiles-mvt") {
|
||||
const pmtilesUrl = manifestPmtilesUrl(_tileManifest);
|
||||
const pmtilesResp = await fetch(pmtilesUrl, { method: "HEAD", cache: "no-store" });
|
||||
if (!pmtilesResp.ok) {
|
||||
throw new Error(`高精度国界 PMTiles 不存在 HTTP ${pmtilesResp.status}: ${pmtilesUrl}`);
|
||||
}
|
||||
}
|
||||
const basePath = _tileManifest.base || _tileManifest.baseGeojson;
|
||||
const hoverPath = _tileManifest.hoverIndex || _tileManifest.hoverIndexGeojson;
|
||||
const baseResp = basePath ? await fetch(versionedBoundaryAssetUrl(basePath)) : null;
|
||||
const hoverResp = hoverPath ? await fetch(versionedBoundaryAssetUrl(hoverPath)) : null;
|
||||
if (hoverResp?.ok) {
|
||||
if (baseResp?.ok) baseGeojson = await baseResp.json();
|
||||
geojson = await hoverResp.json();
|
||||
}
|
||||
const claimPath = _tileManifest.claimLine || _tileManifest.chinaClaims?.path;
|
||||
const claimResp = claimPath ? await fetch(versionedBoundaryAssetUrl(claimPath)) : null;
|
||||
const claimGeojson = claimResp?.ok ? await claimResp.json() : null;
|
||||
_features = (geojson.features || []).filter(f => f.geometry);
|
||||
const baseFeatures = (baseGeojson?.features || _features).filter(f => f.geometry);
|
||||
const boundaryBaseFeatures = baseFeatures.filter(
|
||||
feature => !isStandaloneCoastlineFeature(feature),
|
||||
);
|
||||
const coastlineFeatures = baseFeatures.filter(isStandaloneCoastlineFeature);
|
||||
|
||||
const tex = buildLandTexture(_features);
|
||||
_landMesh = makeLandMesh(tex);
|
||||
_landTexture = buildLandTexture(_features);
|
||||
_landMesh = makeLandMesh(_landTexture);
|
||||
_earthObj.add(_landMesh);
|
||||
|
||||
_boundaryLines = buildBoundaryLines(_features);
|
||||
_boundaryLines = buildBoundaryLines(boundaryBaseFeatures);
|
||||
_earthObj.add(_boundaryLines);
|
||||
|
||||
_coastlineLines = buildBoundaryLines(coastlineFeatures);
|
||||
_coastlineLines.name = "country-coastline-all";
|
||||
_earthObj.add(_coastlineLines);
|
||||
|
||||
if (claimGeojson?.features?.length && _claimGroup) {
|
||||
const claimPoints = featureListToSegments(
|
||||
claimGeojson.features,
|
||||
boundaryLineRadius({ claim: true }),
|
||||
);
|
||||
_claimGroup.geometry?.dispose();
|
||||
_claimGroup.geometry = makeLineGeometry(claimPoints);
|
||||
if (typeof _claimGroup.computeLineDistances === "function") {
|
||||
_claimGroup.computeLineDistances();
|
||||
}
|
||||
}
|
||||
|
||||
_hoverGlowLines = buildHoverGlowLines();
|
||||
_earthObj.add(_hoverGlowLines);
|
||||
|
||||
@@ -421,13 +894,22 @@ export function toggleCountryBoundaries(
|
||||
_landMesh.visible = _landFillEnabled && !_landFillSuppressed;
|
||||
}
|
||||
if (_boundaryLines) _boundaryLines.visible = _visible;
|
||||
if (_coastlineLines) _coastlineLines.visible = _visible && !_hoveredFeature;
|
||||
_tileCache.forEach((entry, key) => {
|
||||
setTileObjectVisible(entry.object, _visible && _activeTileKeys.has(key));
|
||||
});
|
||||
if (_claimGroup) _claimGroup.visible = _visible && Boolean(_tileManifest?.chinaClaims?.available || _tileManifest?.claimLine);
|
||||
setHoverLinesVisible(_hoveredFeature);
|
||||
|
||||
if (!_visible) {
|
||||
cancelPendingHoverClear();
|
||||
_hoveredFeature = null;
|
||||
_hoveredGroupKey = null;
|
||||
setBoundaryLinesDimmed(false);
|
||||
_lastHoverInfo = null;
|
||||
setHoverLinesVisible(false);
|
||||
setActiveTileKeys([]);
|
||||
_lastTileSignature = "";
|
||||
updateBoundaryLineDimState();
|
||||
}
|
||||
|
||||
if (_tintMesh) _tintMesh.visible = _visible && showTint && _tintEnabled;
|
||||
@@ -459,11 +941,13 @@ export function getShowCountryBoundaries() {
|
||||
}
|
||||
|
||||
/** Clear the hover highlight without hiding the full layer. */
|
||||
export function clearCountryBoundaryHover() {
|
||||
if (!_hoveredFeature) return;
|
||||
export function clearCountryBoundaryHover({ cancelSticky = true } = {}) {
|
||||
if (cancelSticky) cancelPendingHoverClear();
|
||||
if (!_hoveredFeature && !_lastHoverInfo) return;
|
||||
_hoveredFeature = null;
|
||||
_hoveredGroupKey = null;
|
||||
setBoundaryLinesDimmed(false);
|
||||
_lastHoverInfo = null;
|
||||
updateBoundaryLineDimState();
|
||||
setHoverLinesVisible(false);
|
||||
}
|
||||
|
||||
@@ -478,15 +962,30 @@ export function updateCountryBoundaryHover(coords) {
|
||||
const found = _features.find(f => featureContains(lat, lon, f)) || null;
|
||||
const groupKey = getCountryHighlightGroupKey(found);
|
||||
|
||||
if (!found && _hoveredFeature) {
|
||||
const stickyMs = Math.max(0, COUNTRY_BOUNDARY_CONFIG.hoverMissStickyMs || 0);
|
||||
const elapsedMs = Date.now() - _lastHoverHitAt;
|
||||
if (stickyMs > 0 && elapsedMs < stickyMs) {
|
||||
scheduleHoverClear(stickyMs - elapsedMs);
|
||||
return _lastHoverInfo;
|
||||
}
|
||||
}
|
||||
|
||||
if (found) {
|
||||
cancelPendingHoverClear();
|
||||
_lastHoverHitAt = Date.now();
|
||||
_lastHoverInfo = makeCountryInfo(found);
|
||||
}
|
||||
|
||||
if (found !== _hoveredFeature || groupKey !== _hoveredGroupKey) {
|
||||
_hoveredFeature = found;
|
||||
_hoveredGroupKey = groupKey;
|
||||
if (_hoverLines) {
|
||||
if (!found) {
|
||||
setBoundaryLinesDimmed(false);
|
||||
updateBoundaryLineDimState();
|
||||
setHoverLinesVisible(false);
|
||||
} else {
|
||||
setBoundaryLinesDimmed(true);
|
||||
updateBoundaryLineDimState();
|
||||
const highlightFeatures = getHighlightFeatures(found);
|
||||
const geometries = getHoverGeometries(groupKey, highlightFeatures);
|
||||
setLineGeometry(_hoverGlowLines, geometries.glow);
|
||||
@@ -496,13 +995,17 @@ export function updateCountryBoundaryHover(coords) {
|
||||
}
|
||||
}
|
||||
|
||||
return found ? makeCountryInfo(found) : null;
|
||||
if (!found) _lastHoverInfo = null;
|
||||
return found ? _lastHoverInfo : null;
|
||||
}
|
||||
|
||||
/** Dispose all Three.js objects and reset state. */
|
||||
export function clearCountryBoundaryData() {
|
||||
_hoveredFeature = null;
|
||||
_hoveredGroupKey = null;
|
||||
cancelPendingHoverClear();
|
||||
_lastHoverHitAt = 0;
|
||||
_lastHoverInfo = null;
|
||||
|
||||
function disposeObj(obj) {
|
||||
if (!obj) return;
|
||||
@@ -519,14 +1022,33 @@ export function clearCountryBoundaryData() {
|
||||
disposeObj(_hoverLines);
|
||||
disposeObj(_hoverGlowLines);
|
||||
disposeObj(_boundaryLines);
|
||||
disposeObj(_coastlineLines);
|
||||
disposeObj(_claimGroup);
|
||||
disposeObj(_landMesh);
|
||||
disposeObj(_tintMesh);
|
||||
_landTexture?.dispose?.();
|
||||
_tileCache.forEach(entry => disposeTileObject(entry.object));
|
||||
_tileCache.clear();
|
||||
_tileLru = [];
|
||||
_inFlightTiles.clear();
|
||||
_activeTileKeys.clear();
|
||||
_lastTileSignature = "";
|
||||
if (_tileUpdateTimer) {
|
||||
clearTimeout(_tileUpdateTimer);
|
||||
_tileUpdateTimer = null;
|
||||
}
|
||||
|
||||
_hoverLines = null;
|
||||
_hoverGlowLines = null;
|
||||
_boundaryLines = null;
|
||||
_coastlineLines = null;
|
||||
_claimGroup = null;
|
||||
_landMesh = null;
|
||||
_tintMesh = null;
|
||||
_landTexture = null;
|
||||
_tileManifest = null;
|
||||
_tileProvider = "pmtiles-mvt";
|
||||
_pmtilesArchive = null;
|
||||
_features = [];
|
||||
disposeHoverGeometryCache();
|
||||
_loaded = false;
|
||||
|
||||
@@ -36,18 +36,24 @@ const _earthSunDirection = new THREE.Vector3(
|
||||
EARTH_MATERIAL_CONFIG.dayNight.sunDirection.z,
|
||||
).normalize();
|
||||
|
||||
function applyEarthDayNightShader(material) {
|
||||
function applyEarthDayNightShader(material, options = {}) {
|
||||
if (!material || !EARTH_MATERIAL_CONFIG.dayNight.enabled) return;
|
||||
|
||||
const twilightColor = new THREE.Color(EARTH_MATERIAL_CONFIG.dayNight.twilightColor);
|
||||
const nightTintColor = new THREE.Color(EARTH_MATERIAL_CONFIG.dayNight.nightTintColor);
|
||||
|
||||
const {
|
||||
nightFloor = EARTH_MATERIAL_CONFIG.dayNight.nightFloor,
|
||||
} = options;
|
||||
material.onBeforeCompile = (shader) => {
|
||||
_earthShaders.push(shader);
|
||||
shader.uniforms.uSunDirectionWorld = { value: _earthSunDirection.clone() };
|
||||
shader.uniforms.uNightFloor = { value: EARTH_MATERIAL_CONFIG.dayNight.nightFloor };
|
||||
shader.uniforms.uNightFloor = { value: nightFloor };
|
||||
shader.uniforms.uDayBoost = { value: EARTH_MATERIAL_CONFIG.dayNight.dayBoost };
|
||||
shader.uniforms.uFeatherScale = { value: EARTH_MATERIAL_CONFIG.dayNight.featherScale };
|
||||
shader.uniforms.uTwilightWidth = { value: EARTH_MATERIAL_CONFIG.dayNight.twilightWidth };
|
||||
shader.uniforms.uTwilightFeatherScale = {
|
||||
value: EARTH_MATERIAL_CONFIG.dayNight.twilightFeatherScale,
|
||||
};
|
||||
shader.uniforms.uTwilightIntensity = { value: EARTH_MATERIAL_CONFIG.dayNight.twilightIntensity };
|
||||
shader.uniforms.uTwilightColor = { value: twilightColor };
|
||||
shader.uniforms.uNightTintColor = { value: nightTintColor };
|
||||
@@ -71,7 +77,9 @@ varying vec3 vWorldNormal;
|
||||
uniform vec3 uSunDirectionWorld;
|
||||
uniform float uNightFloor;
|
||||
uniform float uDayBoost;
|
||||
uniform float uFeatherScale;
|
||||
uniform float uTwilightWidth;
|
||||
uniform float uTwilightFeatherScale;
|
||||
uniform float uTwilightIntensity;
|
||||
uniform vec3 uTwilightColor;
|
||||
uniform vec3 uNightTintColor;
|
||||
@@ -83,8 +91,9 @@ uniform float uDayNightEnabled;`,
|
||||
vec3 worldNormal = normalize(vWorldNormal);
|
||||
vec3 sunDir = normalize(uSunDirectionWorld);
|
||||
float sunFacing = dot(worldNormal, sunDir);
|
||||
float daylight = smoothstep(-uTwilightWidth, uTwilightWidth, sunFacing);
|
||||
float twilight = 1.0 - smoothstep(0.0, uTwilightWidth, abs(sunFacing));
|
||||
float edgeFeather = max(fwidth(sunFacing) * uFeatherScale, uTwilightWidth);
|
||||
float daylight = smoothstep(-edgeFeather, edgeFeather, sunFacing);
|
||||
float twilight = 1.0 - smoothstep(0.0, edgeFeather * uTwilightFeatherScale, abs(sunFacing));
|
||||
|
||||
// Camera-facing diffuse: vNormal and vViewPosition are both in view space.
|
||||
// N·V gives 1.0 at center-facing, 0 at limb — creates depth cue regardless of earth rotation.
|
||||
@@ -170,10 +179,12 @@ export function createEarth(scene) {
|
||||
);
|
||||
const occluderMaterial = new THREE.MeshBasicMaterial({
|
||||
colorWrite: false,
|
||||
depthTest: false,
|
||||
depthWrite: true,
|
||||
side: THREE.FrontSide,
|
||||
});
|
||||
const occluder = new THREE.Mesh(occluderGeometry, occluderMaterial);
|
||||
occluder.renderOrder = -1;
|
||||
occluder.renderOrder = 0.5;
|
||||
earth.add(occluder);
|
||||
|
||||
// Keep the original atmosphere shells on the legacy camera-facing shader so
|
||||
|
||||
@@ -1276,8 +1276,8 @@ const CARD_CONFIG = {
|
||||
{ key: 'footprint_model', label: '覆盖模型' },
|
||||
{ key: 'inclination', label: '倾角', unit: '°' },
|
||||
{ key: 'period', label: '周期', unit: '分钟' },
|
||||
{ key: 'perigee', label: '近地点', unit: 'km' },
|
||||
{ key: 'apogee', label: '远地点', unit: 'km' }
|
||||
{ key: 'perigee', label: '近地点高度', unit: 'km' },
|
||||
{ key: 'apogee', label: '远地点高度', unit: 'km' }
|
||||
]
|
||||
},
|
||||
bgp: {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
CRUISE_CONFIG,
|
||||
ROTATION_MODE,
|
||||
SCENE_LIGHT_CONFIG,
|
||||
SURFACE_HOVER_INFO_MODES,
|
||||
} from "./constants.js";
|
||||
import { vector3ToLatLon, screenToEarthCoords } from "./utils.js";
|
||||
import {
|
||||
@@ -69,6 +70,7 @@ import {
|
||||
setSurfaceTintEnabled,
|
||||
toggleCountryBoundaries,
|
||||
updateCountryBoundaryHover,
|
||||
updateCountryBoundaryTiles,
|
||||
} from "./country-boundaries.js";
|
||||
import {
|
||||
loadGeoJSONFromPath,
|
||||
@@ -224,6 +226,7 @@ import {
|
||||
setDayNightInteractable,
|
||||
applyDeferredLayerVisibilitySettings,
|
||||
scheduleTerrainPrefetch,
|
||||
getSurfaceHoverInfoMode,
|
||||
} from "./controls.js";
|
||||
import {
|
||||
createLayerStartupTaskMap,
|
||||
@@ -276,6 +279,10 @@ import {
|
||||
setMotionDebugPanelVisible,
|
||||
} from "./motion-debug-panel.js";
|
||||
|
||||
const EARTH_RADIUS_KM = 6371;
|
||||
const EARTH_GRAVITATIONAL_PARAMETER_KM3_S2 = 398600.4418;
|
||||
const SECONDS_PER_DAY = 86400;
|
||||
|
||||
export let scene;
|
||||
export let camera;
|
||||
export let renderer;
|
||||
@@ -391,6 +398,10 @@ const HUD_INTERACTIVE_SELECTORS = [
|
||||
"#earth-stats *",
|
||||
"#media-panel",
|
||||
"#media-panel *",
|
||||
"#desktop-news-ticker",
|
||||
"#desktop-news-ticker *",
|
||||
"#news-hud-panel",
|
||||
"#news-hud-panel *",
|
||||
"#motion-debug-panel",
|
||||
"#motion-debug-panel *",
|
||||
"#mobile-drawer-shell",
|
||||
@@ -1402,9 +1413,10 @@ function getCableBriefHtml(cable) {
|
||||
function showSatelliteInfo(props, coords) {
|
||||
const meanMotion = props?.mean_motion || 0;
|
||||
const period = meanMotion > 0 ? (1440 / meanMotion).toFixed(1) : "-";
|
||||
const ecc = props?.eccentricity || 0;
|
||||
const perigee = (6371 * (1 - ecc)).toFixed(0);
|
||||
const apogee = (6371 * (1 + ecc)).toFixed(0);
|
||||
const altitudeRange = calculateSatelliteAltitudeRangeKm(
|
||||
props?.mean_motion,
|
||||
props?.eccentricity,
|
||||
);
|
||||
const presentation = getSatellitePresentationInfo(props);
|
||||
|
||||
let footprintModel = "不适用";
|
||||
@@ -1426,11 +1438,39 @@ function showSatelliteInfo(props, coords) {
|
||||
footprint_model: footprintModel,
|
||||
inclination: props?.inclination ? props.inclination.toFixed(2) : "-",
|
||||
period,
|
||||
perigee,
|
||||
apogee,
|
||||
perigee: altitudeRange?.perigee ?? "-",
|
||||
apogee: altitudeRange?.apogee ?? "-",
|
||||
}, coords);
|
||||
}
|
||||
|
||||
function calculateSatelliteAltitudeRangeKm(meanMotion, eccentricity = 0) {
|
||||
const revolutionsPerDay = Number(meanMotion);
|
||||
const ecc = Number(eccentricity);
|
||||
if (
|
||||
!Number.isFinite(revolutionsPerDay) ||
|
||||
revolutionsPerDay <= 0 ||
|
||||
!Number.isFinite(ecc) ||
|
||||
ecc < 0 ||
|
||||
ecc >= 1
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const meanMotionRadPerSecond =
|
||||
(revolutionsPerDay * Math.PI * 2) / SECONDS_PER_DAY;
|
||||
const semiMajorAxisKm = Math.cbrt(
|
||||
EARTH_GRAVITATIONAL_PARAMETER_KM3_S2 /
|
||||
(meanMotionRadPerSecond * meanMotionRadPerSecond),
|
||||
);
|
||||
const perigeeKm = semiMajorAxisKm * (1 - ecc) - EARTH_RADIUS_KM;
|
||||
const apogeeKm = semiMajorAxisKm * (1 + ecc) - EARTH_RADIUS_KM;
|
||||
|
||||
return {
|
||||
perigee: Math.max(0, perigeeKm).toFixed(0),
|
||||
apogee: Math.max(0, apogeeKm).toFixed(0),
|
||||
};
|
||||
}
|
||||
|
||||
function getSatelliteBriefHtml(props) {
|
||||
const name = props?.name || "未知卫星";
|
||||
const id = props?.norad_cat_id ? `NORAD: ${props.norad_cat_id}` : "";
|
||||
@@ -1525,6 +1565,16 @@ function getCountryBoundaryBriefHtml(country) {
|
||||
return `<strong>${name}</strong><br>ISO: ${code}<br>大洲: ${continent}`;
|
||||
}
|
||||
|
||||
function getSurfacePositionBriefHtml(coords) {
|
||||
const elevMeters = sampleElevationAt(coords.lat, coords.lon);
|
||||
const elevText = elevMeters !== null
|
||||
? elevMeters >= 1000
|
||||
? `${(elevMeters / 1000).toFixed(2)} km`
|
||||
: `${Math.round(elevMeters)} m`
|
||||
: "—";
|
||||
return `纬度: ${coords.lat}°<br>经度: ${coords.lon}°<br>海拔: ${elevText}`;
|
||||
}
|
||||
|
||||
function showBGPInfo(marker, coords) {
|
||||
setLegendMode("bgp");
|
||||
const impactedRegions =
|
||||
@@ -4476,7 +4526,9 @@ function onMouseMove(event) {
|
||||
inertialVelocity.y = rotationDeltaY;
|
||||
inertialVelocity.x = rotationDeltaX;
|
||||
previousMousePosition = { x: event.clientX, y: event.clientY };
|
||||
clearCountryBoundaryHover();
|
||||
if (!document.body.classList.contains("layout-mode-mobile")) {
|
||||
clearCountryBoundaryHover();
|
||||
}
|
||||
hideTooltip();
|
||||
return;
|
||||
}
|
||||
@@ -4648,9 +4700,33 @@ function onMouseMove(event) {
|
||||
if (earthPoint) {
|
||||
const coords = vector3ToLatLon(earthPoint);
|
||||
updateCoordinatesDisplay(coords.lat, coords.lon, coords.alt);
|
||||
const hoveredCountry = getShowCountryBoundaries()
|
||||
const hoverInfoMode = getSurfaceHoverInfoMode();
|
||||
const shouldShowCountry =
|
||||
hoverInfoMode === SURFACE_HOVER_INFO_MODES.COUNTRY ||
|
||||
hoverInfoMode === SURFACE_HOVER_INFO_MODES.FULL;
|
||||
const shouldShowPosition =
|
||||
hoverInfoMode === SURFACE_HOVER_INFO_MODES.POSITION ||
|
||||
hoverInfoMode === SURFACE_HOVER_INFO_MODES.FULL;
|
||||
const hoveredCountry = shouldShowCountry && getShowCountryBoundaries()
|
||||
? updateCountryBoundaryHover(coords)
|
||||
: null;
|
||||
const positionHtml = shouldShowPosition
|
||||
? getSurfacePositionBriefHtml(coords)
|
||||
: "";
|
||||
|
||||
if (!shouldShowCountry) {
|
||||
clearCountryBoundaryHover();
|
||||
}
|
||||
|
||||
if (hoveredCountry && shouldShowPosition) {
|
||||
showTooltip(
|
||||
event.clientX + TOOLTIP_CURSOR_OFFSET,
|
||||
event.clientY + TOOLTIP_CURSOR_OFFSET,
|
||||
`${getCountryBoundaryBriefHtml(hoveredCountry)}<br>${positionHtml}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (hoveredCountry) {
|
||||
showTooltip(
|
||||
event.clientX + TOOLTIP_CURSOR_OFFSET,
|
||||
@@ -4659,18 +4735,17 @@ function onMouseMove(event) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
clearCountryBoundaryHover();
|
||||
const elevMeters = sampleElevationAt(coords.lat, coords.lon);
|
||||
const elevText = elevMeters !== null
|
||||
? elevMeters >= 1000
|
||||
? `${(elevMeters / 1000).toFixed(2)} km`
|
||||
: `${Math.round(elevMeters)} m`
|
||||
: "—";
|
||||
showTooltip(
|
||||
event.clientX + TOOLTIP_COORDS_OFFSET,
|
||||
event.clientY + TOOLTIP_COORDS_OFFSET,
|
||||
`纬度: ${coords.lat}°<br>经度: ${coords.lon}°<br>海拔: ${elevText}`,
|
||||
);
|
||||
if (shouldShowPosition) {
|
||||
showTooltip(
|
||||
event.clientX + TOOLTIP_COORDS_OFFSET,
|
||||
event.clientY + TOOLTIP_COORDS_OFFSET,
|
||||
positionHtml,
|
||||
);
|
||||
} else {
|
||||
hideTooltip();
|
||||
}
|
||||
} else {
|
||||
clearCountryBoundaryHover();
|
||||
hideTooltip();
|
||||
@@ -5138,6 +5213,12 @@ function animate() {
|
||||
renderer,
|
||||
now: performance.now(),
|
||||
});
|
||||
updateCountryBoundaryTiles({
|
||||
camera,
|
||||
earth: getEarthSurfacePickTarget() || earth,
|
||||
renderer,
|
||||
viewZoom: getZoomLevel(),
|
||||
});
|
||||
updateNewsViewFocus(getCurrentViewCenterCoords());
|
||||
const satPositions = getSatellitePositions();
|
||||
if (
|
||||
|
||||
@@ -106,6 +106,11 @@ function mapNewsItemToCruiseEvent(item) {
|
||||
latitude,
|
||||
longitude,
|
||||
locationLabel: item.location_label || REGION_LABELS[item.region] || "全球",
|
||||
sourceLocationLabel: item.location_label || REGION_LABELS[item.region] || "全球",
|
||||
targetLocationConfidence: item.location_meta?.target?.confidence ?? null,
|
||||
targetLocationSource: item.location_source || "",
|
||||
verified: item.verified === true,
|
||||
locationMeta: item.location_meta || null,
|
||||
sortTimestamp: getItemTimestamp(item),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import { showStatusMessage } from "./ui.js";
|
||||
import { getActiveTVTab, isTVPanelVisible } from "./tv.js";
|
||||
|
||||
// News aggregation now lives inside the shared media panel:
|
||||
// - outer shell: #media-panel
|
||||
// - this module renders into inner pane: #news-panel
|
||||
// Desktop news has two surfaces:
|
||||
// - a persistent top ticker
|
||||
// - a center HUD that expands from the ticker
|
||||
// Mobile keeps its existing drawer page.
|
||||
|
||||
const EARTH_NEWS_API = "/api/v1/news/earth-feed";
|
||||
const FOCUS_UPDATE_INTERVAL_MS = 4000;
|
||||
const DATA_REFRESH_INTERVAL_MS = 180000;
|
||||
const MIN_REGION_SWITCH_INTERVAL_MS = 2500;
|
||||
const REQUEST_TIMEOUT_MS = 15000;
|
||||
const NEWS_HUD_MORPH_MS = 300;
|
||||
const NEWS_HUD_MIN_WIDTH_PX = 420;
|
||||
const NEWS_HUD_MIN_HEIGHT_PX = 360;
|
||||
const NEWS_HUD_RESIZE_MARGIN_PX = 12;
|
||||
const NEWS_REALTIME_RECONNECT_MS = 5000;
|
||||
|
||||
let initialized = false;
|
||||
let refreshPromise = null;
|
||||
@@ -18,6 +23,10 @@ let lastFocus = null;
|
||||
let lastFetchAt = 0;
|
||||
let lastRegionSwitchAt = 0;
|
||||
let selectedCruiseStoryId = null;
|
||||
let morphTimer = null;
|
||||
let newsRealtimeSocket = null;
|
||||
let newsRealtimeReconnectTimer = null;
|
||||
|
||||
function getElements() {
|
||||
const isMobile = document.body.classList.contains("layout-mode-mobile");
|
||||
return {
|
||||
@@ -31,6 +40,11 @@ function getElements() {
|
||||
board: document.getElementById(isMobile ? "mobile-news-board-list" : "news-board-list"),
|
||||
empty: document.getElementById(isMobile ? "mobile-news-board-empty" : "news-board-empty"),
|
||||
feedAnchor: document.getElementById(isMobile ? "mobile-news-feed-anchor" : "news-feed-anchor"),
|
||||
ticker: document.getElementById("desktop-news-ticker"),
|
||||
tickerRegion: document.getElementById("news-ticker-region"),
|
||||
tickerTrack: document.getElementById("news-ticker-track"),
|
||||
hud: document.getElementById("news-hud-panel"),
|
||||
hudCloseBtn: document.getElementById("news-hud-close"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -57,6 +71,250 @@ export function updateNewsToggleUI(visible) {
|
||||
void visible;
|
||||
}
|
||||
|
||||
function getHudScale() {
|
||||
const scale = Number.parseFloat(
|
||||
getComputedStyle(document.documentElement).getPropertyValue("--hud-scale"),
|
||||
);
|
||||
return Number.isFinite(scale) && scale > 0 ? scale : 1;
|
||||
}
|
||||
|
||||
function clearMorphTimer() {
|
||||
if (!morphTimer) return;
|
||||
window.clearTimeout(morphTimer);
|
||||
morphTimer = null;
|
||||
}
|
||||
|
||||
function setHudRect(hud, rect, opacity = 1) {
|
||||
hud.style.left = `${rect.left}px`;
|
||||
hud.style.top = `${rect.top}px`;
|
||||
hud.style.width = `${rect.width}px`;
|
||||
hud.style.height = `${rect.height}px`;
|
||||
hud.style.transform = "none";
|
||||
hud.style.opacity = String(opacity);
|
||||
}
|
||||
|
||||
function setHudRectWithoutTransition(hud, rect, opacity = 1) {
|
||||
const previousTransition = hud.style.transition;
|
||||
hud.style.transition = "none";
|
||||
setHudRect(hud, rect, opacity);
|
||||
void hud.offsetHeight;
|
||||
hud.style.transition = previousTransition;
|
||||
}
|
||||
|
||||
function getNewsHudTargetRect(hud) {
|
||||
const wasHidden = hud.classList.contains("hud-panel-hidden");
|
||||
const previousVisibility = hud.style.visibility;
|
||||
if (wasHidden) hud.classList.remove("hud-panel-hidden");
|
||||
hud.style.visibility = "hidden";
|
||||
|
||||
const rect = hud.getBoundingClientRect();
|
||||
|
||||
hud.style.visibility = previousVisibility;
|
||||
if (wasHidden) hud.classList.add("hud-panel-hidden");
|
||||
return rect;
|
||||
}
|
||||
|
||||
function finishHudOpen(hud) {
|
||||
hud.classList.remove("is-morphing");
|
||||
hud.style.opacity = "";
|
||||
revealSelectedCruiseStory();
|
||||
}
|
||||
|
||||
function finishHudClose(hud, ticker, restoreRect = null) {
|
||||
hud.classList.add("hud-panel-hidden");
|
||||
hud.classList.remove("is-morphing");
|
||||
hud.style.opacity = "";
|
||||
if ((hud.dataset.dragged === "true" || hud.dataset.resized === "true") && restoreRect) {
|
||||
setHudRect(hud, restoreRect, 1);
|
||||
hud.style.opacity = "";
|
||||
} else {
|
||||
hud.style.left = "";
|
||||
hud.style.top = "";
|
||||
hud.style.width = "";
|
||||
hud.style.height = "";
|
||||
hud.style.transform = "";
|
||||
}
|
||||
ticker?.classList.remove("is-hidden");
|
||||
}
|
||||
|
||||
function setNewsHudOpen(open, { highlightId = null } = {}) {
|
||||
const { hud, ticker } = getElements();
|
||||
if (!(hud instanceof HTMLElement)) return;
|
||||
|
||||
clearMorphTimer();
|
||||
if (highlightId) {
|
||||
selectedCruiseStoryId = highlightId;
|
||||
applyCruiseStorySelection();
|
||||
}
|
||||
|
||||
const tickerRect = ticker instanceof HTMLElement
|
||||
? ticker.getBoundingClientRect()
|
||||
: { left: window.innerWidth / 2 - 240, top: 20, width: 480, height: 38 };
|
||||
|
||||
if (open) {
|
||||
const targetRect = getNewsHudTargetRect(hud);
|
||||
hud.classList.remove("hud-panel-hidden");
|
||||
hud.classList.add("is-morphing");
|
||||
setHudRectWithoutTransition(hud, tickerRect, 1);
|
||||
ticker?.classList.add("is-hidden");
|
||||
requestAnimationFrame(() => {
|
||||
setHudRect(hud, targetRect, 1);
|
||||
});
|
||||
morphTimer = window.setTimeout(() => {
|
||||
morphTimer = null;
|
||||
finishHudOpen(hud);
|
||||
}, NEWS_HUD_MORPH_MS);
|
||||
} else {
|
||||
const currentRect = hud.getBoundingClientRect();
|
||||
hud.classList.add("is-morphing");
|
||||
setHudRectWithoutTransition(hud, currentRect, 1);
|
||||
requestAnimationFrame(() => {
|
||||
setHudRect(hud, tickerRect, 1);
|
||||
});
|
||||
morphTimer = window.setTimeout(() => {
|
||||
morphTimer = null;
|
||||
finishHudClose(hud, ticker, currentRect);
|
||||
}, NEWS_HUD_MORPH_MS);
|
||||
}
|
||||
|
||||
ticker?.setAttribute("aria-expanded", open ? "true" : "false");
|
||||
}
|
||||
|
||||
function openNewsHud(options = {}) {
|
||||
setNewsHudOpen(true, options);
|
||||
}
|
||||
|
||||
function closeNewsHud() {
|
||||
setNewsHudOpen(false);
|
||||
}
|
||||
|
||||
function setupNewsHudResize() {
|
||||
const { hud } = getElements();
|
||||
const container = document.getElementById("container");
|
||||
if (!(hud instanceof HTMLElement) || !(container instanceof HTMLElement)) return;
|
||||
|
||||
let resizing = false;
|
||||
let activeEdge = "";
|
||||
const resizeStart = {
|
||||
pointerX: 0,
|
||||
pointerY: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
left: 0,
|
||||
top: 0,
|
||||
};
|
||||
|
||||
const clearPositioningForResize = () => {
|
||||
const rect = hud.getBoundingClientRect();
|
||||
hud.style.left = `${rect.left}px`;
|
||||
hud.style.top = `${rect.top}px`;
|
||||
hud.style.width = `${rect.width}px`;
|
||||
hud.style.height = `${rect.height}px`;
|
||||
hud.style.transform = "none";
|
||||
hud.dataset.dragged = "true";
|
||||
hud.dataset.resized = "true";
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
resizing = false;
|
||||
activeEdge = "";
|
||||
hud.classList.remove("is-resizing");
|
||||
document.body.style.userSelect = "";
|
||||
};
|
||||
|
||||
const onMove = (event) => {
|
||||
if (!resizing) return;
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const hudScale = getHudScale();
|
||||
const minWidth = Math.round(NEWS_HUD_MIN_WIDTH_PX * hudScale);
|
||||
const minHeight = Math.round(NEWS_HUD_MIN_HEIGHT_PX * hudScale);
|
||||
const dx = event.clientX - resizeStart.pointerX;
|
||||
const dy = event.clientY - resizeStart.pointerY;
|
||||
|
||||
if (activeEdge.includes("r")) {
|
||||
const maxW = containerRect.right - resizeStart.left - NEWS_HUD_RESIZE_MARGIN_PX;
|
||||
hud.style.width = `${Math.min(maxW, Math.max(minWidth, resizeStart.width + dx))}px`;
|
||||
}
|
||||
if (activeEdge.includes("l")) {
|
||||
const newW = Math.max(minWidth, resizeStart.width - dx);
|
||||
hud.style.width = `${newW}px`;
|
||||
hud.style.left = `${Math.max(0, resizeStart.left + resizeStart.width - newW)}px`;
|
||||
}
|
||||
if (activeEdge.includes("b")) {
|
||||
const maxH = containerRect.bottom - resizeStart.top - NEWS_HUD_RESIZE_MARGIN_PX;
|
||||
hud.style.height = `${Math.min(maxH, Math.max(minHeight, resizeStart.height + dy))}px`;
|
||||
}
|
||||
};
|
||||
|
||||
hud.querySelectorAll(".earth-news-hud-edge[data-edge]").forEach((edgeEl) => {
|
||||
edgeEl.addEventListener("pointerdown", (event) => {
|
||||
if (document.body.classList.contains("layout-mode-mobile")) return;
|
||||
if (hud.classList.contains("hud-panel-hidden")) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
clearPositioningForResize();
|
||||
activeEdge = edgeEl.dataset.edge ?? "";
|
||||
resizing = true;
|
||||
resizeStart.pointerX = event.clientX;
|
||||
resizeStart.pointerY = event.clientY;
|
||||
|
||||
const rect = hud.getBoundingClientRect();
|
||||
resizeStart.width = rect.width;
|
||||
resizeStart.height = rect.height;
|
||||
resizeStart.left = rect.left;
|
||||
resizeStart.top = rect.top;
|
||||
|
||||
hud.classList.add("is-resizing");
|
||||
document.body.style.userSelect = "none";
|
||||
edgeEl.setPointerCapture?.(event.pointerId);
|
||||
});
|
||||
|
||||
edgeEl.addEventListener("pointermove", onMove);
|
||||
edgeEl.addEventListener("pointerup", stopResize);
|
||||
edgeEl.addEventListener("pointercancel", stopResize);
|
||||
edgeEl.addEventListener("lostpointercapture", stopResize);
|
||||
});
|
||||
}
|
||||
|
||||
function escapeTickerText(value) {
|
||||
return String(value ?? "")
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
}
|
||||
|
||||
function renderTicker(nextPayload) {
|
||||
const { ticker, tickerRegion, tickerTrack } = getElements();
|
||||
if (!(ticker instanceof HTMLElement) || !(tickerTrack instanceof HTMLElement)) return;
|
||||
const items = Array.isArray(nextPayload?.items) ? nextPayload.items : [];
|
||||
const focus = nextPayload?.focus || {};
|
||||
|
||||
if (tickerRegion instanceof HTMLElement) {
|
||||
tickerRegion.textContent = (focus.region || "global").toUpperCase();
|
||||
tickerRegion.style.color = focus.accent || "";
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
tickerTrack.textContent = "正在准备全球态势新闻...";
|
||||
tickerTrack.style.removeProperty("--news-ticker-duration");
|
||||
return;
|
||||
}
|
||||
|
||||
const visibleItems = items.slice(0, 6);
|
||||
const tickerItems = [...visibleItems, ...visibleItems];
|
||||
tickerTrack.innerHTML = tickerItems
|
||||
.map((item) => `
|
||||
<span class="earth-news-ticker__item" data-news-id="${escapeTickerText(item.id || "")}">
|
||||
<span class="earth-news-ticker__source">${escapeTickerText(item.source || item.feed_name || "NEWS")}</span>
|
||||
<span>${escapeTickerText(item.title || "未命名新闻")}</span>
|
||||
</span>
|
||||
`)
|
||||
.join("");
|
||||
tickerTrack.style.setProperty("--news-ticker-duration", `${Math.max(22, visibleItems.length * 7)}s`);
|
||||
}
|
||||
|
||||
function renderEmptyState(message) {
|
||||
const { board, empty, status, openBtn } = getElements();
|
||||
if (board) board.innerHTML = "";
|
||||
@@ -68,6 +326,7 @@ function renderEmptyState(message) {
|
||||
status.textContent = "等待聚合新闻源";
|
||||
}
|
||||
if (openBtn) openBtn.disabled = true;
|
||||
renderTicker({ items: [], focus: payload?.focus || { region: "global" } });
|
||||
}
|
||||
|
||||
function renderPayload(nextPayload) {
|
||||
@@ -87,6 +346,8 @@ function renderPayload(nextPayload) {
|
||||
const sources = Array.isArray(nextPayload?.sources) ? nextPayload.sources : [];
|
||||
const focus = nextPayload?.focus || {};
|
||||
|
||||
renderTicker(nextPayload);
|
||||
|
||||
if (!board || !status || !focusLabel || !focusCoords || !sourceCount || !regionChip) {
|
||||
if (document.body.classList.contains("layout-mode-mobile")) {
|
||||
// Mobile page omits the region chip shell, but the rest of the page is still renderable.
|
||||
@@ -180,6 +441,84 @@ function renderPayload(nextPayload) {
|
||||
}));
|
||||
}
|
||||
|
||||
function getNewsRealtimeUrl() {
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
return `${protocol}//${window.location.host}/ws`;
|
||||
}
|
||||
|
||||
function clearNewsRealtimeReconnectTimer() {
|
||||
if (!newsRealtimeReconnectTimer) return;
|
||||
window.clearTimeout(newsRealtimeReconnectTimer);
|
||||
newsRealtimeReconnectTimer = null;
|
||||
}
|
||||
|
||||
function scheduleNewsRealtimeReconnect() {
|
||||
if (newsRealtimeReconnectTimer) return;
|
||||
newsRealtimeReconnectTimer = window.setTimeout(() => {
|
||||
newsRealtimeReconnectTimer = null;
|
||||
connectNewsRealtime();
|
||||
}, NEWS_REALTIME_RECONNECT_MS);
|
||||
}
|
||||
|
||||
function applyNewsRealtimePatch(updatePayload) {
|
||||
const itemId = updatePayload?.item_id;
|
||||
const patch = updatePayload?.patch;
|
||||
if (!payload || !itemId || !patch || typeof patch !== "object") return;
|
||||
const items = Array.isArray(payload.items) ? payload.items : [];
|
||||
let changed = false;
|
||||
const nextItems = items.map((item) => {
|
||||
if (item?.id !== itemId) return item;
|
||||
changed = true;
|
||||
return {
|
||||
...item,
|
||||
...patch,
|
||||
};
|
||||
});
|
||||
if (!changed) return;
|
||||
renderPayload({
|
||||
...payload,
|
||||
items: nextItems,
|
||||
});
|
||||
}
|
||||
|
||||
function connectNewsRealtime() {
|
||||
if (newsRealtimeSocket || typeof WebSocket === "undefined") return;
|
||||
const socket = new WebSocket(getNewsRealtimeUrl());
|
||||
newsRealtimeSocket = socket;
|
||||
socket.onopen = () => {
|
||||
clearNewsRealtimeReconnectTimer();
|
||||
socket.send(JSON.stringify({
|
||||
type: "subscribe",
|
||||
data: {
|
||||
channel: "earth_news",
|
||||
},
|
||||
}));
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
let message;
|
||||
try {
|
||||
message = JSON.parse(event.data);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (message.type === "heartbeat" && message.data?.action === "ping") {
|
||||
socket.send(JSON.stringify({ type: "heartbeat" }));
|
||||
return;
|
||||
}
|
||||
if (message.type !== "data_frame" || message.channel !== "earth_news") return;
|
||||
applyNewsRealtimePatch(message.payload);
|
||||
};
|
||||
socket.onclose = () => {
|
||||
if (newsRealtimeSocket === socket) {
|
||||
newsRealtimeSocket = null;
|
||||
}
|
||||
scheduleNewsRealtimeReconnect();
|
||||
};
|
||||
socket.onerror = () => {
|
||||
socket.close();
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchNews(lat, lon) {
|
||||
const url = new URL(EARTH_NEWS_API, window.location.origin);
|
||||
if (typeof lat === "number") url.searchParams.set("lat", lat.toFixed(4));
|
||||
@@ -338,21 +677,25 @@ export function initNewsPanel() {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
|
||||
updateNewsToggleUI(isTVPanelVisible());
|
||||
updateNewsToggleUI(true);
|
||||
renderEmptyState("正在准备全球态势新闻聚合源...");
|
||||
|
||||
window.addEventListener("earth:tv-tab-change", () => {
|
||||
updateNewsToggleUI(isTVPanelVisible());
|
||||
if (getActiveTVTab() === "news") {
|
||||
revealSelectedCruiseStory();
|
||||
}
|
||||
const { ticker, hudCloseBtn } = getElements();
|
||||
ticker?.addEventListener("click", (event) => {
|
||||
const itemEl = event.target instanceof Element
|
||||
? event.target.closest("[data-news-id]")
|
||||
: null;
|
||||
const highlightId = itemEl?.getAttribute("data-news-id") || null;
|
||||
openNewsHud({ highlightId });
|
||||
});
|
||||
window.addEventListener("earth:tv-visibility-change", (event) => {
|
||||
updateNewsToggleUI(Boolean(event.detail?.visible));
|
||||
if (event.detail?.visible && getActiveTVTab() === "news") {
|
||||
revealSelectedCruiseStory();
|
||||
}
|
||||
ticker?.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
openNewsHud();
|
||||
});
|
||||
hudCloseBtn?.addEventListener("click", closeNewsHud);
|
||||
setupNewsHudResize();
|
||||
connectNewsRealtime();
|
||||
|
||||
["news-refresh", "mobile-news-refresh"].forEach((id) => {
|
||||
const refreshBtn = document.getElementById(id);
|
||||
|
||||
@@ -23,8 +23,6 @@ function waitForContext(context, durationMs) {
|
||||
}
|
||||
|
||||
function getDefaultCardTarget() {
|
||||
// TODO: replace the singleton card fallback with a presentation/card token check
|
||||
// before BGP/News migrate here, so connectors only attach to their owning card.
|
||||
const mobilePopup = document.getElementById("earth-mobile-popup");
|
||||
if (mobilePopup instanceof HTMLElement && !mobilePopup.hasAttribute("hidden")) {
|
||||
return mobilePopup;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// satellites.js - Satellite visualization module with real SGP4 positions and animations
|
||||
|
||||
import * as THREE from "three";
|
||||
import { twoline2satrec, propagate } from "satellite.js";
|
||||
import { twoline2satrec, propagate, eciToEcf, gstime } from "satellite.js";
|
||||
import {
|
||||
CONFIG,
|
||||
DEFAULT_SATELLITE_DISPLAY_STYLE,
|
||||
@@ -43,6 +43,7 @@ let satelliteCapacity = 0;
|
||||
let satelliteSatrecCache = new Map();
|
||||
let satelliteDisplayStyle = DEFAULT_SATELLITE_DISPLAY_STYLE;
|
||||
let satelliteIdleBreathingEnabled = true;
|
||||
let satelliteRealAltitudeEnabled = true;
|
||||
|
||||
const GROUND_FOOTPRINT_RENDER_ORDER = 3;
|
||||
|
||||
@@ -127,6 +128,7 @@ const FALLBACK_TRAIL_ALPHA_START = 0.2;
|
||||
const FALLBACK_TRAIL_ALPHA_END = 0.8;
|
||||
const DOT_TEXTURE_SIZE = 32;
|
||||
const POSITION_UPDATE_INTERVAL_MS = 250;
|
||||
const FOOTPRINT_DIRECTION_SAMPLE_MS = 30000;
|
||||
const BACKGROUND_TRAIL_RESET_DELTA_MS = 2000;
|
||||
const SATELLITE_TWINKLE_SECONDARY_SPEED = 1.73;
|
||||
const SATELLITE_TWINKLE_SECONDARY_WEIGHT = 0.28;
|
||||
@@ -338,6 +340,28 @@ export function setSatelliteIdleBreathingEnabled(enabled) {
|
||||
return satelliteIdleBreathingEnabled;
|
||||
}
|
||||
|
||||
export function getSatelliteRealAltitudeEnabled() {
|
||||
return satelliteRealAltitudeEnabled;
|
||||
}
|
||||
|
||||
export function setSatelliteRealAltitudeEnabled(enabled) {
|
||||
const nextEnabled = Boolean(enabled);
|
||||
if (nextEnabled === satelliteRealAltitudeEnabled) {
|
||||
return satelliteRealAltitudeEnabled;
|
||||
}
|
||||
|
||||
satelliteRealAltitudeEnabled = nextEnabled;
|
||||
clearSatelliteTrails();
|
||||
updateSatellitePositions(0, true, { resetTrails: true });
|
||||
if (
|
||||
lockedSatelliteIndex !== null &&
|
||||
satellitePositions?.[lockedSatelliteIndex]?.current
|
||||
) {
|
||||
showHoverRing(satellitePositions[lockedSatelliteIndex].current, true);
|
||||
}
|
||||
return satelliteRealAltitudeEnabled;
|
||||
}
|
||||
|
||||
export function updateSatelliteIdleBreathingVisual(isIdle = true) {
|
||||
if (!satellitePoints || !satelliteBackdropPoints) return;
|
||||
|
||||
@@ -681,9 +705,9 @@ function createSatelliteTwinkleState(index) {
|
||||
return {
|
||||
phase: hashSatelliteUnit(index, 1) * Math.PI * 2,
|
||||
secondaryPhase: hashSatelliteUnit(index, 2) * Math.PI * 2,
|
||||
speed: 0.62 + hashSatelliteUnit(index, 3) * 1.45,
|
||||
floor: hashSatelliteUnit(index, 4) * 0.22,
|
||||
intensity: 0.48 + hashSatelliteUnit(index, 5) * 0.52,
|
||||
speed: 0.38 + hashSatelliteUnit(index, 3) * 0.72,
|
||||
floor: hashSatelliteUnit(index, 4) * 0.16,
|
||||
intensity: 0.68 + hashSatelliteUnit(index, 5) * 0.62,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -931,25 +955,101 @@ function computeSatellitePosition(satellite, time) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const x = positionAndVelocity.position.x;
|
||||
const y = positionAndVelocity.position.y;
|
||||
const z = positionAndVelocity.position.z;
|
||||
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const r = Math.sqrt(x * x + y * y + z * z);
|
||||
const displayRadius =
|
||||
CONFIG.earthRadius + SATELLITE_CONFIG.displayAltitudeOffset;
|
||||
const scale = displayRadius / r;
|
||||
|
||||
return new THREE.Vector3(x * scale, y * scale, z * scale);
|
||||
return computeDisplayPositionFromEciPosition(
|
||||
positionAndVelocity.position,
|
||||
gstime(time),
|
||||
);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function computeDisplayPositionFromEciPosition(positionEci, siderealTime) {
|
||||
const earthFixedPosition = convertEciPositionToSceneVector(
|
||||
positionEci,
|
||||
siderealTime,
|
||||
);
|
||||
const x = earthFixedPosition.x;
|
||||
const y = earthFixedPosition.y;
|
||||
const z = earthFixedPosition.z;
|
||||
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const r = Math.sqrt(
|
||||
positionEci.x * positionEci.x +
|
||||
positionEci.y * positionEci.y +
|
||||
positionEci.z * positionEci.z,
|
||||
);
|
||||
if (!Number.isFinite(r) || r <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const displayRadius = satelliteRealAltitudeEnabled
|
||||
? CONFIG.earthRadius + getCompressedRealAltitudeOffset(r)
|
||||
: CONFIG.earthRadius + SATELLITE_CONFIG.fallbackAltitudeOffset;
|
||||
const sceneRadius = Math.sqrt(x * x + y * y + z * z);
|
||||
if (!Number.isFinite(sceneRadius) || sceneRadius <= 0) {
|
||||
return null;
|
||||
}
|
||||
const scale = displayRadius / sceneRadius;
|
||||
|
||||
return new THREE.Vector3(x * scale, y * scale, z * scale);
|
||||
}
|
||||
|
||||
function computeSatelliteInertialOrbitPosition(satellite, time, siderealTime) {
|
||||
try {
|
||||
const props = satellite.properties;
|
||||
if (!props || !props.norad_cat_id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const satrec = getOrBuildSatrec(props, time);
|
||||
if (!satrec || satrec.error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const positionAndVelocity = propagate(satrec, time);
|
||||
if (!positionAndVelocity || !positionAndVelocity.position) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return computeDisplayPositionFromEciPosition(
|
||||
positionAndVelocity.position,
|
||||
siderealTime,
|
||||
);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function convertEciPositionToSceneVector(positionEci, siderealTime) {
|
||||
const positionEcf = eciToEcf(positionEci, siderealTime);
|
||||
return new THREE.Vector3(
|
||||
positionEcf.x,
|
||||
positionEcf.z,
|
||||
-positionEcf.y,
|
||||
);
|
||||
}
|
||||
|
||||
function getCompressedRealAltitudeOffset(radiusKm) {
|
||||
const altitudeKm = Math.max(0, radiusKm - EARTH_RADIUS_KM);
|
||||
const clampedAltitudeKm = Math.min(
|
||||
altitudeKm,
|
||||
SATELLITE_CONFIG.maxDisplayAltitudeKm,
|
||||
);
|
||||
const compressionKm = Math.max(1, SATELLITE_CONFIG.altitudeCompressionKm);
|
||||
const normalizedAltitude = Math.log1p(clampedAltitudeKm / compressionKm) /
|
||||
Math.log1p(SATELLITE_CONFIG.maxDisplayAltitudeKm / compressionKm);
|
||||
|
||||
return THREE.MathUtils.lerp(
|
||||
SATELLITE_CONFIG.minRealAltitudeOffset,
|
||||
SATELLITE_CONFIG.maxRealAltitudeOffset,
|
||||
THREE.MathUtils.clamp(normalizedAltitude, 0, 1),
|
||||
);
|
||||
}
|
||||
|
||||
function buildSatrecFromProperties(props, fallbackTime) {
|
||||
if (props.tle_line1 && props.tle_line2) {
|
||||
// Prefer source-provided TLE lines so the client does not need to rebuild them.
|
||||
@@ -1088,7 +1188,7 @@ function buildTleLinesFromElements(props, fallbackTime) {
|
||||
}
|
||||
|
||||
function generateFallbackPosition(satellite, index, total, time = new Date()) {
|
||||
const radius = CONFIG.earthRadius + SATELLITE_CONFIG.displayAltitudeOffset;
|
||||
const radius = CONFIG.earthRadius + SATELLITE_CONFIG.fallbackAltitudeOffset;
|
||||
|
||||
const noradId = satellite.properties?.norad_cat_id || index;
|
||||
const inclination = satellite.properties?.inclination || 53;
|
||||
@@ -1907,14 +2007,15 @@ function getLockedSatelliteTrackDirection(groundNormal) {
|
||||
const props = satellite?.properties;
|
||||
if (!props?.norad_cat_id) return null;
|
||||
|
||||
const satrec = getOrBuildSatrec(props, new Date());
|
||||
if (!satrec || satrec.error) return null;
|
||||
const now = new Date();
|
||||
const currentPosition = computeSatellitePosition(satellite, now);
|
||||
const nextPosition = computeSatellitePosition(
|
||||
satellite,
|
||||
new Date(now.getTime() + FOOTPRINT_DIRECTION_SAMPLE_MS),
|
||||
);
|
||||
if (!currentPosition || !nextPosition) return null;
|
||||
|
||||
const propagation = propagate(satrec, new Date());
|
||||
const velocity = propagation?.velocity;
|
||||
if (!velocity) return null;
|
||||
|
||||
scratchFootprintVelocity.set(velocity.x, velocity.y, velocity.z);
|
||||
scratchFootprintVelocity.subVectors(nextPosition, currentPosition);
|
||||
if (!Number.isFinite(scratchFootprintVelocity.lengthSq())) return null;
|
||||
|
||||
scratchFootprintTangent
|
||||
@@ -2547,32 +2648,65 @@ function calculatePredictedOrbit(
|
||||
const points = [];
|
||||
const samples = Math.ceil(periodSeconds / sampleInterval);
|
||||
const now = new Date();
|
||||
const fixedSiderealTime = gstime(now);
|
||||
|
||||
for (let i = 0; i <= samples; i++) {
|
||||
const time = new Date(now.getTime() + i * sampleInterval * 1000);
|
||||
const pos = computeSatellitePosition(satellite, time);
|
||||
const pos = computeSatelliteInertialOrbitPosition(
|
||||
satellite,
|
||||
time,
|
||||
fixedSiderealTime,
|
||||
);
|
||||
if (pos) points.push(pos);
|
||||
}
|
||||
|
||||
if (points.length < samples * 0.5) {
|
||||
points.length = 0;
|
||||
const radius =
|
||||
CONFIG.earthRadius + SATELLITE_CONFIG.displayAltitudeOffset;
|
||||
const inclination = satellite.properties?.inclination || 53;
|
||||
const raan = satellite.properties?.raan || 0;
|
||||
|
||||
for (let i = 0; i <= samples; i++) {
|
||||
const theta = (i / samples) * Math.PI * 2;
|
||||
const phi = (inclination * Math.PI) / 180;
|
||||
const x =
|
||||
radius * Math.sin(phi) * Math.cos(theta + (raan * Math.PI) / 180);
|
||||
const y = radius * Math.cos(phi);
|
||||
const z =
|
||||
radius * Math.sin(phi) * Math.sin(theta + (raan * Math.PI) / 180);
|
||||
points.push(new THREE.Vector3(x, y, z));
|
||||
}
|
||||
return calculateFallbackPredictedOrbit(satellite, samples);
|
||||
}
|
||||
|
||||
closeOrbitLoop(points);
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
function closeOrbitLoop(points) {
|
||||
if (points.length > 2) {
|
||||
points.push(points[0].clone());
|
||||
}
|
||||
}
|
||||
|
||||
function calculateFallbackPredictedOrbit(satellite, samples) {
|
||||
const points = [];
|
||||
const radius =
|
||||
CONFIG.earthRadius + SATELLITE_CONFIG.fallbackAltitudeOffset;
|
||||
const inclinationRad = THREE.MathUtils.degToRad(
|
||||
satellite.properties?.inclination ?? 53,
|
||||
);
|
||||
const raanRad = THREE.MathUtils.degToRad(satellite.properties?.raan ?? 0);
|
||||
const cosRaan = Math.cos(raanRad);
|
||||
const sinRaan = Math.sin(raanRad);
|
||||
const cosInclination = Math.cos(inclinationRad);
|
||||
const sinInclination = Math.sin(inclinationRad);
|
||||
|
||||
for (let i = 0; i <= samples; i++) {
|
||||
const argument = (i / samples) * Math.PI * 2;
|
||||
const cosArgument = Math.cos(argument);
|
||||
const sinArgument = Math.sin(argument);
|
||||
|
||||
const ecfX =
|
||||
radius *
|
||||
(cosRaan * cosArgument -
|
||||
sinRaan * sinArgument * cosInclination);
|
||||
const ecfY =
|
||||
radius *
|
||||
(sinRaan * cosArgument +
|
||||
cosRaan * sinArgument * cosInclination);
|
||||
const ecfZ = radius * sinArgument * sinInclination;
|
||||
|
||||
points.push(new THREE.Vector3(ecfX, ecfZ, -ecfY));
|
||||
}
|
||||
|
||||
closeOrbitLoop(points);
|
||||
return points;
|
||||
}
|
||||
|
||||
|
||||
+41
-339
@@ -5,7 +5,6 @@ import { createHUDPanel } from "./hud-panels.js";
|
||||
// Naming convention:
|
||||
// - #media-panel is the outer HUD shell, responsible for drag/resize/show-hide
|
||||
// - #tv-panel is the inner live tab pane
|
||||
// - #news-panel is the inner aggregation-news tab pane
|
||||
|
||||
const TV_STREAMS_API = "/api/v1/tv/streams";
|
||||
const TV_PROXY_API = "/api/v1/tv/proxy";
|
||||
@@ -13,8 +12,8 @@ const TV_STATUS_MESSAGE = {
|
||||
idle: "等待加载直播源",
|
||||
syncing: "正在同步直播源...",
|
||||
empty: "暂无可播放直播源",
|
||||
iframeReady: "直播页已加载",
|
||||
videoReady: "视频流已加载",
|
||||
iframeReady: "直播已加载",
|
||||
videoReady: "直播已加载",
|
||||
videoError: "当前视频流不可播放,请尝试其他频道",
|
||||
externalOnly: "当前频道仅支持外部打开",
|
||||
loadFailed: "电视直播源加载失败",
|
||||
@@ -28,25 +27,15 @@ let hlsPlayer = null;
|
||||
let hlsRecoveryAttempts = 0;
|
||||
let metaAutoCollapseTimer = null;
|
||||
let mediaPanel = null;
|
||||
let activeTab = "live";
|
||||
const failedSourceIds = new Set();
|
||||
let probeTimer = null;
|
||||
let reformCleanupTimer = null;
|
||||
const tabPanelState = {
|
||||
live: null,
|
||||
news: null,
|
||||
};
|
||||
let mobileMetaCollapsed = false;
|
||||
|
||||
const META_AUTO_COLLAPSE_DELAY = 2500;
|
||||
const PROBE_INTERVAL_MS = 2 * 60 * 1000;
|
||||
const DEFAULT_HUD_OFFSET_PX = 20;
|
||||
const MIN_NEWS_TAB_HEIGHT_PX = 280;
|
||||
const PANEL_RESIZE_MARGIN_PX = 12;
|
||||
const TV_PANEL_MIN_WIDTH_PX = 360;
|
||||
const TV_PANEL_MIN_HEIGHT_PX = 340;
|
||||
const REFORM_CLEANUP_MS = 280;
|
||||
const REFORM_RESTORE_ANCHOR_DATA_KEY = "reformRestoreAnchor";
|
||||
|
||||
const HLS_MAX_RECOVERY_ATTEMPTS = 3;
|
||||
const HLS_RETRY_CONFIG = {
|
||||
@@ -66,6 +55,7 @@ function getElements() {
|
||||
title: document.getElementById(isMobile ? "mobile-tv-source-title" : "tv-source-title"),
|
||||
meta: document.getElementById(isMobile ? "mobile-tv-source-meta" : "tv-source-meta"),
|
||||
catalog: document.getElementById(isMobile ? "mobile-tv-source-catalog" : "tv-source-catalog"),
|
||||
origin: document.getElementById("tv-source-origin"),
|
||||
status: document.getElementById(isMobile ? "mobile-tv-source-status" : "tv-source-status"),
|
||||
notes: document.getElementById(isMobile ? "mobile-tv-source-notes" : "tv-source-notes"),
|
||||
iframe: document.getElementById(isMobile ? "mobile-tv-iframe" : "tv-iframe"),
|
||||
@@ -75,13 +65,8 @@ function getElements() {
|
||||
openBtn: document.getElementById(isMobile ? "mobile-tv-open-external" : "tv-open-external"),
|
||||
metaWrap: document.getElementById(isMobile ? "mobile-tv-meta-wrap" : "tv-meta-wrap"),
|
||||
metaToggle: document.getElementById(isMobile ? "mobile-tv-meta-toggle" : "tv-meta-toggle"),
|
||||
liveHeaderControls: document.getElementById("tv-header-controls-live"),
|
||||
newsHeaderControls: document.getElementById("tv-header-controls-news"),
|
||||
liveTabBtn: document.getElementById("tv-tab-live"),
|
||||
newsTabBtn: document.getElementById("tv-tab-news"),
|
||||
// Inner tab panes.
|
||||
livePane: document.getElementById("tv-panel"),
|
||||
newsPane: document.getElementById("news-panel"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -124,37 +109,13 @@ function setMetaCollapsed(collapsed) {
|
||||
syncMetaToggleState(Boolean(collapsed));
|
||||
}
|
||||
|
||||
function syncPanelActiveTab(tab = activeTab) {
|
||||
function syncPanelActiveTab(tab = "live") {
|
||||
const { panel } = getElements();
|
||||
if (panel instanceof HTMLElement) {
|
||||
panel.dataset.activeTab = tab;
|
||||
}
|
||||
}
|
||||
|
||||
function syncNewsDefaultMaxHeight() {
|
||||
const { panel } = getElements();
|
||||
if (!(panel instanceof HTMLElement)) return;
|
||||
|
||||
const earthStats = document.getElementById("earth-stats");
|
||||
const hudOffset = Number.parseFloat(
|
||||
getComputedStyle(document.documentElement).getPropertyValue("--hud-offset"),
|
||||
);
|
||||
const resolvedOffset = Number.isFinite(hudOffset) ? hudOffset : DEFAULT_HUD_OFFSET_PX;
|
||||
|
||||
if (!(earthStats instanceof HTMLElement)) {
|
||||
panel.style.removeProperty("--tv-news-default-max-height");
|
||||
return;
|
||||
}
|
||||
|
||||
const statsRect = earthStats.getBoundingClientRect();
|
||||
const availableHeight = Math.max(
|
||||
Math.round(MIN_NEWS_TAB_HEIGHT_PX * getHudScale()),
|
||||
Math.floor(window.innerHeight - resolvedOffset - statsRect.bottom),
|
||||
);
|
||||
|
||||
panel.style.setProperty("--tv-news-default-max-height", `${availableHeight}px`);
|
||||
}
|
||||
|
||||
function autoExpandMeta() {
|
||||
if (isMobileLayout()) {
|
||||
clearTimeout(metaAutoCollapseTimer);
|
||||
@@ -174,82 +135,6 @@ function clearPanelPositioningForResize(panel) {
|
||||
panel.dataset.dragged = "true";
|
||||
}
|
||||
|
||||
function readPanelLayoutState(panel) {
|
||||
return {
|
||||
width: panel.style.width || "",
|
||||
height: panel.style.height || "",
|
||||
resized: panel.dataset.resized === "true",
|
||||
};
|
||||
}
|
||||
|
||||
function resetPanelLayoutState(panel) {
|
||||
panel.style.width = "";
|
||||
panel.style.height = "";
|
||||
delete panel.dataset.resized;
|
||||
}
|
||||
|
||||
function captureTabState(tab = activeTab) {
|
||||
const { panel } = getElements();
|
||||
if (!(panel instanceof HTMLElement)) return;
|
||||
tabPanelState[tab] = {
|
||||
layout: readPanelLayoutState(panel),
|
||||
metaCollapsed:
|
||||
tab === "live" ? isMetaCollapsed() : null,
|
||||
};
|
||||
}
|
||||
|
||||
function restoreTabState(tab, panel, container, anchor = null) {
|
||||
if (!(panel instanceof HTMLElement)) return;
|
||||
|
||||
const snapshot = tabPanelState[tab];
|
||||
if (!snapshot?.layout) {
|
||||
resetPanelLayoutState(panel);
|
||||
return;
|
||||
}
|
||||
|
||||
const { layout } = snapshot;
|
||||
panel.style.width = layout.width;
|
||||
panel.style.height = layout.height;
|
||||
|
||||
if (layout.resized) {
|
||||
panel.dataset.resized = "true";
|
||||
} else {
|
||||
delete panel.dataset.resized;
|
||||
}
|
||||
|
||||
if (tab === "live" && snapshot.metaCollapsed !== null) {
|
||||
setMetaCollapsed(snapshot.metaCollapsed);
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
if (anchor) {
|
||||
const panelRect = panel.getBoundingClientRect();
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const margin = Math.round(PANEL_RESIZE_MARGIN_PX * getHudScale());
|
||||
const targetLeft = anchor.right - containerRect.left - panelRect.width;
|
||||
const targetTop = anchor.bottom - containerRect.top - panelRect.height;
|
||||
const maxLeft = Math.max(0, containerRect.width - panelRect.width - margin);
|
||||
const maxTop = Math.max(0, containerRect.height - panelRect.height - margin);
|
||||
const clampedLeft = Math.min(maxLeft, Math.max(0, targetLeft));
|
||||
const clampedTop = Math.min(maxTop, Math.max(0, targetTop));
|
||||
|
||||
panel.style.left = `${clampedLeft}px`;
|
||||
panel.style.top = `${clampedTop}px`;
|
||||
panel.style.right = "auto";
|
||||
panel.style.bottom = "auto";
|
||||
panel.style.transform = "none";
|
||||
panel.dataset.dragged = "true";
|
||||
} else {
|
||||
panel.style.right = "";
|
||||
panel.style.bottom = "";
|
||||
panel.style.left = "";
|
||||
panel.style.top = "";
|
||||
panel.style.transform = "";
|
||||
delete panel.dataset.dragged;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getHudScale() {
|
||||
const scale = Number.parseFloat(
|
||||
getComputedStyle(document.documentElement).getPropertyValue("--hud-scale"),
|
||||
@@ -365,14 +250,11 @@ function updateToggleButton(visible) {
|
||||
const { toggleBtn } = getElements();
|
||||
if (!toggleBtn) return;
|
||||
const icon = toggleBtn.querySelector(".material-symbols-rounded");
|
||||
const isLiveTab = activeTab === "live";
|
||||
toggleBtn.classList.toggle("active", visible);
|
||||
if (icon) {
|
||||
icon.textContent = isLiveTab ? "live_tv" : "newspaper";
|
||||
icon.textContent = "live_tv";
|
||||
}
|
||||
const title = visible
|
||||
? (isLiveTab ? "切换到态势新闻" : "切换到新闻直播")
|
||||
: (isLiveTab ? "打开新闻直播" : "打开态势新闻");
|
||||
const title = visible ? "关闭 Live 新闻" : "打开 Live 新闻";
|
||||
toggleBtn.title = title;
|
||||
toggleBtn.setAttribute("aria-label", title);
|
||||
const tooltip = toggleBtn.querySelector(".earth-toolbar-tooltip");
|
||||
@@ -404,182 +286,16 @@ export function setTVPanelVisible(visible, options = {}) {
|
||||
setPanelVisible(visible, options);
|
||||
}
|
||||
|
||||
function clearReformState() {
|
||||
const { panel } = getElements();
|
||||
if (!(panel instanceof HTMLElement)) return;
|
||||
panel.classList.remove("is-reforming");
|
||||
panel.style.height = "";
|
||||
if (panel.dataset[REFORM_RESTORE_ANCHOR_DATA_KEY] === "true") {
|
||||
panel.style.top = "";
|
||||
panel.style.bottom = "";
|
||||
delete panel.dataset[REFORM_RESTORE_ANCHOR_DATA_KEY];
|
||||
}
|
||||
if (reformCleanupTimer) {
|
||||
clearTimeout(reformCleanupTimer);
|
||||
reformCleanupTimer = null;
|
||||
}
|
||||
function setActiveTab() {
|
||||
syncPanelActiveTab("live");
|
||||
window.dispatchEvent(new CustomEvent("earth:tv-tab-change", {
|
||||
detail: { tab: "live" },
|
||||
}));
|
||||
}
|
||||
|
||||
function animateTabReform(applyChange) {
|
||||
const { panel } = getElements();
|
||||
const container = document.getElementById("container");
|
||||
if (!(panel instanceof HTMLElement)) {
|
||||
applyChange();
|
||||
return;
|
||||
}
|
||||
if (!(container instanceof HTMLElement)) {
|
||||
applyChange();
|
||||
return;
|
||||
}
|
||||
|
||||
if (panel.dataset.resized === "true") {
|
||||
applyChange();
|
||||
requestAnimationFrame(() => {
|
||||
clampPanelToContainer(panel, container);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (panel.classList.contains("is-dragging") || panel.classList.contains("is-resizing")) {
|
||||
applyChange();
|
||||
return;
|
||||
}
|
||||
|
||||
clearReformState();
|
||||
|
||||
const reformStartRect = panel.getBoundingClientRect();
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const reformSnapshot = {
|
||||
height: reformStartRect.height,
|
||||
anchoredBottom: reformStartRect.bottom - containerRect.top,
|
||||
shouldRestoreDefaultAnchoring: panel.dataset.dragged !== "true",
|
||||
};
|
||||
|
||||
if (reformSnapshot.shouldRestoreDefaultAnchoring) {
|
||||
panel.dataset[REFORM_RESTORE_ANCHOR_DATA_KEY] = "true";
|
||||
panel.style.bottom = "auto";
|
||||
}
|
||||
|
||||
panel.style.top = `${reformSnapshot.anchoredBottom - reformSnapshot.height}px`;
|
||||
panel.style.height = `${reformSnapshot.height}px`;
|
||||
panel.classList.add("is-reforming");
|
||||
void panel.offsetHeight;
|
||||
|
||||
applyChange();
|
||||
|
||||
panel.style.height = "auto";
|
||||
const targetHeight = panel.getBoundingClientRect().height;
|
||||
panel.style.height = `${reformSnapshot.height}px`;
|
||||
void panel.offsetHeight;
|
||||
const targetTop = reformSnapshot.anchoredBottom - targetHeight;
|
||||
|
||||
const finalizeReform = () => {
|
||||
panel.removeEventListener("transitionend", handleReformTransitionEnd);
|
||||
clearReformState();
|
||||
};
|
||||
|
||||
const handleReformTransitionEnd = (event) => {
|
||||
if (event.target === panel && event.propertyName === "height") {
|
||||
finalizeReform();
|
||||
}
|
||||
};
|
||||
|
||||
panel.addEventListener("transitionend", handleReformTransitionEnd);
|
||||
reformCleanupTimer = window.setTimeout(finalizeReform, REFORM_CLEANUP_MS);
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
panel.style.top = `${targetTop}px`;
|
||||
panel.style.height = `${targetHeight}px`;
|
||||
});
|
||||
}
|
||||
|
||||
function updateTabState(target, isActive, activeClassName = "") {
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
target.hidden = !isActive;
|
||||
if (activeClassName) {
|
||||
target.classList.toggle(activeClassName, isActive);
|
||||
}
|
||||
}
|
||||
|
||||
function updateTabButtonState(button, isActive) {
|
||||
if (!(button instanceof HTMLButtonElement)) return;
|
||||
button.classList.toggle("media-panel-tab--active", isActive);
|
||||
button.setAttribute("aria-selected", isActive ? "true" : "false");
|
||||
}
|
||||
|
||||
function setActiveTab(tab) {
|
||||
const nextTab = tab === "news" ? "news" : "live";
|
||||
if (activeTab === nextTab) return;
|
||||
|
||||
captureTabState(activeTab);
|
||||
|
||||
const { panel } = getElements();
|
||||
const targetSnapshot = tabPanelState[nextTab];
|
||||
const currentIsCustom =
|
||||
panel instanceof HTMLElement && panel.dataset.resized === "true";
|
||||
const targetIsCustom = Boolean(targetSnapshot?.layout?.resized);
|
||||
const container = document.getElementById("container");
|
||||
const currentAnchor =
|
||||
panel instanceof HTMLElement && container instanceof HTMLElement
|
||||
? (() => {
|
||||
const panelRect = panel.getBoundingClientRect();
|
||||
return {
|
||||
right: panelRect.right,
|
||||
bottom: panelRect.bottom,
|
||||
};
|
||||
})()
|
||||
: null;
|
||||
|
||||
const applyTabSwitch = (restoreLayoutState = false) => {
|
||||
activeTab = nextTab;
|
||||
syncPanelActiveTab(nextTab);
|
||||
syncNewsDefaultMaxHeight();
|
||||
const {
|
||||
liveTabBtn,
|
||||
newsTabBtn,
|
||||
liveHeaderControls,
|
||||
newsHeaderControls,
|
||||
livePane,
|
||||
newsPane,
|
||||
} = getElements();
|
||||
|
||||
updateTabButtonState(liveTabBtn, nextTab === "live");
|
||||
updateTabButtonState(newsTabBtn, nextTab === "news");
|
||||
updateTabState(liveHeaderControls, nextTab === "live");
|
||||
updateTabState(newsHeaderControls, nextTab === "news");
|
||||
updateTabState(livePane, nextTab === "live", "tv-tab-pane--active");
|
||||
updateTabState(newsPane, nextTab === "news", "tv-tab-pane--active");
|
||||
updateToggleButton(mediaPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
|
||||
|
||||
if (
|
||||
restoreLayoutState &&
|
||||
panel instanceof HTMLElement &&
|
||||
container instanceof HTMLElement
|
||||
) {
|
||||
restoreTabState(nextTab, panel, container, currentAnchor);
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
captureTabState(nextTab);
|
||||
});
|
||||
|
||||
window.dispatchEvent(new CustomEvent("earth:tv-tab-change", {
|
||||
detail: { tab: nextTab },
|
||||
}));
|
||||
};
|
||||
|
||||
if (currentIsCustom || targetIsCustom) {
|
||||
applyTabSwitch(true);
|
||||
return;
|
||||
}
|
||||
|
||||
animateTabReform(() => applyTabSwitch(false));
|
||||
}
|
||||
|
||||
export function openTVPanelTab(tab = "live") {
|
||||
export function openTVPanelTab() {
|
||||
setPanelVisible(true);
|
||||
if (activeTab === tab) return;
|
||||
setActiveTab(tab);
|
||||
setActiveTab("live");
|
||||
}
|
||||
|
||||
export function setActiveTVTab(tab = "live") {
|
||||
@@ -591,7 +307,7 @@ export function isTVPanelVisible() {
|
||||
}
|
||||
|
||||
export function getActiveTVTab() {
|
||||
return activeTab;
|
||||
return "live";
|
||||
}
|
||||
|
||||
function getEmbeddedUrl(source) {
|
||||
@@ -913,6 +629,21 @@ function setPanelMessage(message) {
|
||||
const { status } = getElements();
|
||||
if (status) {
|
||||
status.textContent = message || TV_STATUS_MESSAGE.idle;
|
||||
if (status.id === "tv-source-status") {
|
||||
const normalized = message || TV_STATUS_MESSAGE.idle;
|
||||
status.classList.toggle(
|
||||
"tv-panel-tag--error",
|
||||
normalized === TV_STATUS_MESSAGE.videoError || normalized === TV_STATUS_MESSAGE.loadFailed,
|
||||
);
|
||||
status.classList.toggle(
|
||||
"tv-panel-tag--warning",
|
||||
normalized === TV_STATUS_MESSAGE.syncing ||
|
||||
normalized === TV_STATUS_MESSAGE.externalOnly ||
|
||||
normalized.includes("重试") ||
|
||||
normalized.includes("恢复") ||
|
||||
normalized.includes("回退"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -967,12 +698,11 @@ function renderSourceOptions() {
|
||||
const fragment = document.createDocumentFragment();
|
||||
|
||||
sources.forEach((source) => {
|
||||
const sourceOriginLabel = source.collector_source ? "[采集]" : "[内置]";
|
||||
const defaultMark = source.id === tvPayload?.default_source_id ? " · 默认" : "";
|
||||
const failMark = failedSourceIds.has(source.id) ? " ⚠" : "";
|
||||
const option = document.createElement("option");
|
||||
option.value = source.id;
|
||||
option.textContent = `${sourceOriginLabel} ${source.name}${defaultMark}${failMark}`;
|
||||
option.textContent = `${source.name}${defaultMark}${failMark}`;
|
||||
fragment.appendChild(option);
|
||||
});
|
||||
|
||||
@@ -983,7 +713,7 @@ function renderSourceOptions() {
|
||||
}
|
||||
|
||||
function renderSource(source) {
|
||||
const { title, meta, catalog, notes, iframe, video, empty } = getElements();
|
||||
const { title, meta, catalog, origin, notes, iframe, video, empty } = getElements();
|
||||
const embeddedUrl = getEmbeddedUrl(source);
|
||||
const videoUrl = getVideoUrl(source);
|
||||
const externalUrl = getExternalUrl(source);
|
||||
@@ -993,6 +723,10 @@ function renderSource(source) {
|
||||
if (title) {
|
||||
title.textContent = source?.name || "暂无可用频道";
|
||||
}
|
||||
if (origin instanceof HTMLElement) {
|
||||
origin.textContent = source?.collector_source ? "采集" : source ? "内置" : "待加载";
|
||||
origin.title = source?.collector_source ? `采集源:${source.collector_source}` : source ? "内置源" : "待加载";
|
||||
}
|
||||
if (meta) {
|
||||
meta.textContent = source
|
||||
? `${source.provider} · ${source.region} · ${source.language} · ${source.source_type}`
|
||||
@@ -1004,12 +738,7 @@ function renderSource(source) {
|
||||
const latestLabel = latestUpdatedAt
|
||||
? `最近同步 ${new Date(latestUpdatedAt).toLocaleString("zh-CN", { hour12: false })}`
|
||||
: "尚未同步";
|
||||
const sourceOriginLabel = source?.collector_source
|
||||
? `采集源 ${source.collector_source}`
|
||||
: source
|
||||
? "内置源"
|
||||
: "";
|
||||
catalog.textContent = `共 ${sourceCount} 个频道 · ${latestLabel}${sourceOriginLabel ? ` · ${sourceOriginLabel}` : ""}`;
|
||||
catalog.textContent = `共 ${sourceCount} 个频道 · ${latestLabel}`;
|
||||
}
|
||||
if (notes) {
|
||||
notes.textContent = source?.notes || "支持后台配置默认源与采集器补充源。";
|
||||
@@ -1039,9 +768,7 @@ function renderSource(source) {
|
||||
|
||||
hideEmptyState(empty);
|
||||
|
||||
setPanelMessage(
|
||||
source.id === tvPayload?.default_source_id ? "当前正在播放默认源" : "当前正在播放已选频道",
|
||||
);
|
||||
setPanelMessage("直播加载中");
|
||||
updateOpenButton(source);
|
||||
autoExpandMeta();
|
||||
}
|
||||
@@ -1117,8 +844,6 @@ export function initTVPanel() {
|
||||
toggleBtn,
|
||||
panel,
|
||||
metaToggle,
|
||||
liveTabBtn,
|
||||
newsTabBtn,
|
||||
} = getElements();
|
||||
const mobileOverviewBar = document.getElementById("mobile-tv-overview-bar");
|
||||
|
||||
@@ -1148,23 +873,13 @@ export function initTVPanel() {
|
||||
const currentlyVisible = mediaPanel?.isVisible() ?? false;
|
||||
if (!currentlyVisible) {
|
||||
setPanelVisible(true);
|
||||
if (activeTab === "live") {
|
||||
await ensureTVPanelReady();
|
||||
showStatusMessage("新闻直播窗口已打开", "info");
|
||||
} else {
|
||||
showStatusMessage("态势新闻窗口已打开", "info");
|
||||
}
|
||||
await ensureTVPanelReady();
|
||||
showStatusMessage("Live 新闻窗口已打开", "info");
|
||||
return;
|
||||
}
|
||||
|
||||
const nextTab = activeTab === "live" ? "news" : "live";
|
||||
setActiveTab(nextTab);
|
||||
if (nextTab === "live") {
|
||||
await ensureTVPanelReady();
|
||||
showStatusMessage("已切换到新闻直播", "info");
|
||||
return;
|
||||
}
|
||||
showStatusMessage("已切换到态势新闻", "info");
|
||||
setPanelVisible(false);
|
||||
showStatusMessage("Live 新闻窗口已关闭", "info");
|
||||
});
|
||||
|
||||
[select, document.getElementById("mobile-tv-source-select"), document.getElementById("tv-source-select")]
|
||||
@@ -1213,13 +928,6 @@ export function initTVPanel() {
|
||||
});
|
||||
});
|
||||
|
||||
liveTabBtn?.addEventListener("click", () => {
|
||||
setActiveTab("live");
|
||||
});
|
||||
newsTabBtn?.addEventListener("click", () => {
|
||||
setActiveTab("news");
|
||||
});
|
||||
|
||||
[iframe, document.getElementById("mobile-tv-iframe"), document.getElementById("tv-iframe")]
|
||||
.filter((element, index, array) => element && array.indexOf(element) === index)
|
||||
.forEach((iframeEl) => {
|
||||
@@ -1249,10 +957,4 @@ export function initTVPanel() {
|
||||
|
||||
setupResizeHandle();
|
||||
syncPanelActiveTab("live");
|
||||
syncNewsDefaultMaxHeight();
|
||||
updateTabButtonState(liveTabBtn, true);
|
||||
updateTabButtonState(newsTabBtn, false);
|
||||
captureTabState("live");
|
||||
|
||||
window.addEventListener("resize", syncNewsDefaultMaxHeight);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
let statusTimeoutId = null;
|
||||
let statusHideTimeoutId = null;
|
||||
const STATUS_BASE_CLASS = "earth-status-message";
|
||||
const STATUS_TICKER_STACK_CLASS = "earth-status-message--ticker-stack";
|
||||
const STATUS_DISPLAY_MS = 3000;
|
||||
const STATUS_FADE_MS = 280;
|
||||
const GESTURE_STATUS_DISPLAY_MS = 760;
|
||||
@@ -87,6 +88,52 @@ function buildStatusContent(statusEl, message, type) {
|
||||
statusEl.appendChild(text);
|
||||
}
|
||||
|
||||
function getStatusSidePlacement(statusEl) {
|
||||
if (!(statusEl instanceof HTMLElement)) return false;
|
||||
if (document.body.classList.contains("layout-mode-mobile")) return false;
|
||||
|
||||
const ticker = document.getElementById("desktop-news-ticker");
|
||||
const brand = document.getElementById("brand-panel");
|
||||
if (!(ticker instanceof HTMLElement) || !(brand instanceof HTMLElement)) return false;
|
||||
if (ticker.classList.contains("is-hidden") || ticker.offsetParent === null) return false;
|
||||
|
||||
const tickerRect = ticker.getBoundingClientRect();
|
||||
const brandRect = brand.getBoundingClientRect();
|
||||
const statusWidth = Math.ceil(statusEl.getBoundingClientRect().width || statusEl.scrollWidth || 0);
|
||||
if (!statusWidth || !tickerRect.width || !brandRect.width) return false;
|
||||
|
||||
const rootStyle = getComputedStyle(document.documentElement);
|
||||
const hudScale = Number.parseFloat(rootStyle.getPropertyValue("--hud-scale")) || 1;
|
||||
const requiredGap = Math.max(10, Math.round(12 * hudScale));
|
||||
const availableWidth = tickerRect.left - brandRect.right - requiredGap * 2;
|
||||
return {
|
||||
shouldStack: availableWidth < statusWidth,
|
||||
left: Math.round(brandRect.right + requiredGap),
|
||||
maxWidth: Math.max(160, Math.floor(availableWidth)),
|
||||
};
|
||||
}
|
||||
|
||||
function syncStatusPlacement(statusEl) {
|
||||
if (!(statusEl instanceof HTMLElement)) return;
|
||||
const placement = getStatusSidePlacement(statusEl);
|
||||
const shouldStack = !placement || placement.shouldStack;
|
||||
statusEl.classList.toggle(STATUS_TICKER_STACK_CLASS, shouldStack);
|
||||
if (!placement || shouldStack) {
|
||||
statusEl.style.left = "";
|
||||
statusEl.style.maxWidth = "";
|
||||
return;
|
||||
}
|
||||
statusEl.style.left = `${placement.left}px`;
|
||||
statusEl.style.maxWidth = `${placement.maxWidth}px`;
|
||||
}
|
||||
|
||||
function syncVisibleStatusPlacement() {
|
||||
const statusEl = getElement("status-message");
|
||||
if (statusEl?.classList.contains("visible")) {
|
||||
syncStatusPlacement(statusEl);
|
||||
}
|
||||
}
|
||||
|
||||
function buildPersistentErrorContent(errorEl, message) {
|
||||
buildStatusContent(errorEl, message, "error");
|
||||
}
|
||||
@@ -97,6 +144,8 @@ function hideStatusElement(statusEl, onHidden) {
|
||||
if (!statusEl.classList.contains("visible")) {
|
||||
setElementDisplay(statusEl, false);
|
||||
statusEl.className = STATUS_BASE_CLASS;
|
||||
statusEl.style.left = "";
|
||||
statusEl.style.maxWidth = "";
|
||||
statusEl.innerHTML = "";
|
||||
}
|
||||
statusHideTimeoutId = null;
|
||||
@@ -123,6 +172,7 @@ function startTransientStatus(message, type = "info") {
|
||||
buildStatusContent(statusEl, message, type);
|
||||
statusEl.className = `${STATUS_BASE_CLASS} ${type}`;
|
||||
setElementDisplay(statusEl, true, "inline-flex");
|
||||
syncStatusPlacement(statusEl);
|
||||
statusEl.offsetHeight;
|
||||
statusEl.classList.add("visible");
|
||||
|
||||
@@ -159,6 +209,7 @@ export function showGestureStatusMessage(message, type = "info") {
|
||||
buildStatusContent(statusEl, message, type);
|
||||
statusEl.className = `${STATUS_BASE_CLASS} ${type} gesture`;
|
||||
setElementDisplay(statusEl, true, "inline-flex");
|
||||
syncStatusPlacement(statusEl);
|
||||
statusEl.offsetHeight;
|
||||
statusEl.classList.add("visible");
|
||||
|
||||
@@ -246,6 +297,7 @@ export function setLoading(loading) {
|
||||
pendingLoadingMessage = "";
|
||||
statusEl.className = `${STATUS_BASE_CLASS} loading`;
|
||||
setElementDisplay(statusEl, true, "inline-flex");
|
||||
syncStatusPlacement(statusEl);
|
||||
statusEl.offsetHeight;
|
||||
statusEl.classList.add("visible");
|
||||
requestAnimationFrame(() => {
|
||||
@@ -268,6 +320,8 @@ export function setLoading(loading) {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", syncVisibleStatusPlacement, { passive: true });
|
||||
|
||||
export function setLoadingMessage(title) {
|
||||
const statusEl = getElement("status-message");
|
||||
if (!statusEl || !statusEl.classList.contains("loading")) {
|
||||
@@ -279,6 +333,7 @@ export function setLoadingMessage(title) {
|
||||
textEl.textContent = title;
|
||||
requestAnimationFrame(() => {
|
||||
updateLoadingWidthLock(statusEl);
|
||||
syncStatusPlacement(statusEl);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -334,6 +389,8 @@ export function clearUiState() {
|
||||
if (statusEl) {
|
||||
statusEl.className = STATUS_BASE_CLASS;
|
||||
setElementDisplay(statusEl, false);
|
||||
statusEl.style.left = "";
|
||||
statusEl.style.maxWidth = "";
|
||||
statusEl.innerHTML = "";
|
||||
clearLoadingWidthLock(statusEl);
|
||||
}
|
||||
|
||||
+40
-10
@@ -1437,7 +1437,7 @@ body {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 14px;
|
||||
border-radius: 8px;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.96) 0%, rgba(245, 247, 250, 0.96) 100%);
|
||||
border: 1px solid rgba(5, 5, 5, 0.08);
|
||||
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
|
||||
@@ -1593,31 +1593,33 @@ body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
border: 1px solid #f0f0f0;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.data-source-table-region .ant-table-wrapper,
|
||||
.data-source-table-region .ant-spin-nested-loading,
|
||||
.data-source-table-region .ant-spin-container,
|
||||
.data-source-table-region .ant-table,
|
||||
.data-source-table-region .ant-table-container,
|
||||
.data-source-table-region .ant-table-body {
|
||||
.data-source-table-region .ant-table-container {
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* users table: flex-fill approach so overlay x-track aligns with table bottom */
|
||||
.users-table-region .ant-table-container {
|
||||
.data-source-table-region .ant-table-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
border-radius: inherit;
|
||||
overflow: hidden;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.users-table-region .ant-table-header {
|
||||
.data-source-table-region .ant-table-header {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.users-table-region .ant-table-body {
|
||||
.data-source-table-region .ant-table-body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
height: 0 !important;
|
||||
@@ -1656,6 +1658,27 @@ body {
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.tasks-page > .ant-row {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.tasks-page__table-card {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.tasks-page__table-card .ant-card-body {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.data-source-drawer-collapse {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
@@ -2074,13 +2097,20 @@ body {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.system-alerts-page__table-card .ant-card-head,
|
||||
.bgp-alerts-page__table-card .ant-card-head {
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.system-alerts-page__table-card .ant-card-body,
|
||||
.bgp-alerts-page__table-card .ant-card-body {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -303,7 +303,7 @@ export default function AISettings() {
|
||||
nextSecret === savedPreview ||
|
||||
nextSecret === revealedSecret ||
|
||||
nextSecret.startsWith('••••') ||
|
||||
nextSecret.includes('*')
|
||||
Array.from(nextSecret).every((char) => char === '*' || char === '•' || /\s/.test(char))
|
||||
)
|
||||
|
||||
const buildAiProviderDraftPayload = (values: any) => {
|
||||
@@ -381,9 +381,11 @@ export default function AISettings() {
|
||||
setFeedback({ type: 'success', message: 'AI 配置已保存' })
|
||||
message.success('AI 配置已保存')
|
||||
await fetchAISettings()
|
||||
} catch {
|
||||
setFeedback({ type: 'error', message: 'AI 配置保存失败' })
|
||||
message.error('AI 配置保存失败')
|
||||
} catch (error: unknown) {
|
||||
const err = error as { response?: { data?: { detail?: string; message?: string } } }
|
||||
const errorMessage = err.response?.data?.message || err.response?.data?.detail || 'AI 配置保存失败'
|
||||
setFeedback({ type: 'error', message: errorMessage })
|
||||
message.error(errorMessage)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
@@ -591,12 +593,8 @@ export default function AISettings() {
|
||||
buildAiProviderDraftPayload(values),
|
||||
)
|
||||
if (response.data.success || response.data.connected) {
|
||||
if (response.data.integrations) {
|
||||
setIntegrations(response.data.integrations)
|
||||
await fetchAISettings()
|
||||
}
|
||||
setFeedback({ type: 'success', message: response.data.message || 'AI Provider 连接成功' })
|
||||
message.success(response.data.message || 'AI Provider 连接成功')
|
||||
setFeedback({ type: 'success', message: response.data.message || '连接测试通过' })
|
||||
message.success(response.data.message || '连接测试通过')
|
||||
} else {
|
||||
setFeedback({ type: 'error', message: response.data.message || 'AI Provider 连接失败' })
|
||||
message.error(response.data.message || 'AI Provider 连接失败')
|
||||
@@ -680,6 +678,9 @@ export default function AISettings() {
|
||||
)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<div style={{ marginTop: -16, marginBottom: 12 }}>
|
||||
<Text type="secondary">测试不保存,保存才生效。</Text>
|
||||
</div>
|
||||
<Form.Item name={['ai_provider', 'provider_api']} label="协议适配">
|
||||
<Select>
|
||||
<Select.Option value="openai-completions">OpenAI Chat Completions</Select.Option>
|
||||
@@ -819,6 +820,9 @@ export default function AISettings() {
|
||||
onTest={() => { void testWebSearchConnection() }}
|
||||
/>
|
||||
</Form.Item>
|
||||
<div style={{ marginTop: -16, marginBottom: 12 }}>
|
||||
<Text type="secondary">测试不保存,保存才生效。</Text>
|
||||
</div>
|
||||
<Form.Item label="WebSearch API Key">
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
<Space>
|
||||
|
||||
@@ -38,6 +38,8 @@ import { formatPhaseMetric, getPhaseDisplay, getPhaseSummary } from '../../utils
|
||||
|
||||
const { Text } = Typography
|
||||
const COLLECTION_REFRESH_DELAY_MS = 800
|
||||
const COLLECTION_STATUS_POLL_MS = 900
|
||||
const COLLECTION_STATUS_MAX_POLLS = 30
|
||||
|
||||
interface BuiltInDataSource {
|
||||
id: number
|
||||
@@ -217,6 +219,7 @@ type DatasourceTaskStatus = {
|
||||
records_processed?: number | null
|
||||
total_records?: number | null
|
||||
status?: string | null
|
||||
error_message?: string | null
|
||||
}
|
||||
|
||||
type ActiveFilter = 'enabled' | 'disabled' | 'all'
|
||||
@@ -228,6 +231,7 @@ const PRODUCT_LABELS: Record<string, string> = {
|
||||
cables: '海底光缆',
|
||||
satellites: '卫星',
|
||||
bgp: 'BGP',
|
||||
earth: 'Earth',
|
||||
compute: '算力',
|
||||
ai: 'AI',
|
||||
media: '媒体',
|
||||
@@ -239,6 +243,7 @@ const PRODUCT_TAG_COLORS: Record<string, string> = {
|
||||
cables: 'geekblue',
|
||||
satellites: 'purple',
|
||||
bgp: 'volcano',
|
||||
earth: 'lime',
|
||||
compute: 'blue',
|
||||
ai: 'magenta',
|
||||
media: 'green',
|
||||
@@ -412,11 +417,44 @@ function DataSources() {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchDatasourceTaskStatus = async (id: number) => {
|
||||
const res = await axios.get<DatasourceTaskStatus>(`/api/v1/datasources/${id}/task-status`)
|
||||
const fetchDatasourceTaskStatus = async (id: number, taskId?: number | null) => {
|
||||
const res = await axios.get<DatasourceTaskStatus>(`/api/v1/datasources/${id}/task-status`, {
|
||||
params: taskId ? { task_id: taskId } : undefined,
|
||||
})
|
||||
return res.data
|
||||
}
|
||||
|
||||
const pollDatasourceAfterTrigger = (id: number, taskId?: number | null) => {
|
||||
let polls = 0
|
||||
let lastTaskId = taskId ?? null
|
||||
|
||||
const poll = async () => {
|
||||
polls += 1
|
||||
try {
|
||||
const status = await fetchDatasourceTaskStatus(id, lastTaskId)
|
||||
lastTaskId = status.task_id ?? lastTaskId
|
||||
await fetchData()
|
||||
|
||||
if (status.status === 'failed') {
|
||||
messageApi.error(status.error_message || status.phase_message || '采集失败')
|
||||
return
|
||||
}
|
||||
if (status.status && status.status !== 'running' && status.status !== 'idle') {
|
||||
return
|
||||
}
|
||||
if (polls < COLLECTION_STATUS_MAX_POLLS) {
|
||||
window.setTimeout(poll, COLLECTION_STATUS_POLL_MS)
|
||||
}
|
||||
} catch (error) {
|
||||
if (polls < COLLECTION_STATUS_MAX_POLLS) {
|
||||
window.setTimeout(poll, COLLECTION_STATUS_POLL_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.setTimeout(poll, COLLECTION_REFRESH_DELAY_MS)
|
||||
}
|
||||
|
||||
const triggerDatasource = async (id: number, options?: { force?: boolean }) => {
|
||||
const res = await axios.post(`/api/v1/datasources/${id}/trigger`, null, {
|
||||
params: { force: options?.force ?? false },
|
||||
@@ -427,11 +465,8 @@ function DataSources() {
|
||||
return { ok: false, status: res.status, detail: res.data?.detail } satisfies TriggerDatasourceResult
|
||||
}
|
||||
|
||||
if (res.data.task_id) {
|
||||
void fetchData()
|
||||
} else {
|
||||
window.setTimeout(fetchData, COLLECTION_REFRESH_DELAY_MS)
|
||||
}
|
||||
void fetchData()
|
||||
pollDatasourceAfterTrigger(id, res.data.task_id)
|
||||
return { ok: true, response: res } satisfies TriggerDatasourceResult
|
||||
}
|
||||
|
||||
@@ -833,10 +868,12 @@ function DataSources() {
|
||||
<div className="page-shell__header">
|
||||
<h2 style={{ margin: 0 }}>数据源</h2>
|
||||
</div>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
<div className="page-shell__body data-source-tabs-shell">
|
||||
<Tabs
|
||||
className="data-source-tabs"
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
{
|
||||
key: 'tasks',
|
||||
label: '采集任务',
|
||||
@@ -914,6 +951,7 @@ function DataSources() {
|
||||
{ value: 'cables', label: '海底光缆' },
|
||||
{ value: 'satellites', label: '卫星' },
|
||||
{ value: 'bgp', label: 'BGP' },
|
||||
{ value: 'earth', label: 'Earth' },
|
||||
{ value: 'compute', label: '算力' },
|
||||
{ value: 'ai', label: 'AI' },
|
||||
{ value: 'media', label: '媒体' },
|
||||
@@ -1048,8 +1086,9 @@ function DataSources() {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
|
||||
@@ -417,6 +417,11 @@ function Settings() {
|
||||
const collectorOptions = useMemo(() => [...collectors, ...customCollectors], [collectors, customCollectors])
|
||||
const selectedCollector = collectorOptions.find((collector) => collector.source === selectedCollectorSource)
|
||||
const selectedCollectorConfig = [...collectorConfigs, ...customSourceConfigs].find((config) => config.name === selectedCollectorSource)
|
||||
const isEarthBoundarySourceCollector = Boolean(
|
||||
selectedCollector?.source &&
|
||||
['earth_admin0_boundaries', 'earth_coastline', 'earth_claim_lines'].includes(selectedCollector.source),
|
||||
)
|
||||
const isEarthPmtilesBuilder = selectedCollector?.source === 'earth_boundary_tiles'
|
||||
const [customStreamStatus, setCustomStreamStatus] = useState<{ running: boolean; done: boolean } | null>(null)
|
||||
const [customStreamBusy, setCustomStreamBusy] = useState(false)
|
||||
const selectedCollectorHealth = selectedCollector
|
||||
@@ -561,7 +566,11 @@ function Settings() {
|
||||
}, [integrationForm, integrations, loading])
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !selectedCollectorConfig) return
|
||||
if (loading) return
|
||||
if (!selectedCollectorConfig) {
|
||||
collectorConfigForm.resetFields()
|
||||
return
|
||||
}
|
||||
const config = selectedCollectorConfig.config || {}
|
||||
const boundingBoxes = config.bounding_boxes ?? [[[-90, -180], [90, 180]]]
|
||||
if (selectedCollector?.is_custom) {
|
||||
@@ -591,6 +600,10 @@ function Settings() {
|
||||
config: {
|
||||
timeout: config.timeout ?? 30,
|
||||
retry: config.retry ?? 3,
|
||||
method: config.method || 'GET',
|
||||
target_schema: config.target_schema || (isEarthBoundarySourceCollector ? 'earth_boundary_source' : undefined),
|
||||
license: config.license || '',
|
||||
mapping_json_text: JSON.stringify(config.mapping_json || {}, null, 2),
|
||||
max_messages: config.max_messages ?? 500,
|
||||
receive_timeout_seconds: config.receive_timeout_seconds ?? 30,
|
||||
message_types: config.message_types ?? ['PositionReport', 'ShipStaticData'],
|
||||
@@ -598,7 +611,7 @@ function Settings() {
|
||||
bounding_boxes_json: stringifyBoundingBoxes(boundingBoxes),
|
||||
},
|
||||
})
|
||||
}, [collectorConfigForm, loading, selectedCollector, selectedCollectorConfig])
|
||||
}, [collectorConfigForm, isEarthBoundarySourceCollector, loading, selectedCollector, selectedCollectorConfig])
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestedCollector || !collectorOptions.some((collector) => collector.source === requestedCollector)) return
|
||||
@@ -706,10 +719,12 @@ function Settings() {
|
||||
setWebSearchSaveFeedback({ type: 'success', message: 'WebSearch 配置已保存' })
|
||||
message.success('外部集成配置已保存')
|
||||
await fetchSettings()
|
||||
} catch {
|
||||
setAiProviderSaveFeedback({ type: 'error', message: 'AI 配置保存失败' })
|
||||
} catch (error: unknown) {
|
||||
const err = error as { response?: { data?: { detail?: string; message?: string } } }
|
||||
const errorMessage = err.response?.data?.message || err.response?.data?.detail || '外部集成配置保存失败'
|
||||
setAiProviderSaveFeedback({ type: 'error', message: errorMessage })
|
||||
setWebSearchSaveFeedback({ type: 'error', message: 'WebSearch 配置保存失败' })
|
||||
message.error('外部集成配置保存失败')
|
||||
message.error(errorMessage)
|
||||
} finally {
|
||||
setSavingIntegrations(false)
|
||||
}
|
||||
@@ -724,7 +739,7 @@ function Settings() {
|
||||
nextSecret === savedPreview ||
|
||||
nextSecret === revealedSecret ||
|
||||
nextSecret.startsWith('••••') ||
|
||||
nextSecret.includes('*')
|
||||
Array.from(nextSecret).every((char) => char === '*' || char === '•' || /\s/.test(char))
|
||||
)
|
||||
|
||||
const buildAiProviderDraftPayload = (values: any) => {
|
||||
@@ -899,31 +914,8 @@ function Settings() {
|
||||
buildAiProviderDraftPayload(values),
|
||||
)
|
||||
if (response.data.success || response.data.connected) {
|
||||
if (response.data.integrations) {
|
||||
setIntegrations(response.data.integrations)
|
||||
integrationForm.setFieldsValue({
|
||||
ai_provider: {
|
||||
service_url: response.data.integrations.ai_provider.service_url,
|
||||
service_token: response.data.integrations.ai_provider.service_token.configured
|
||||
? response.data.integrations.ai_provider.service_token.preview
|
||||
: '',
|
||||
default_provider: response.data.integrations.ai_provider.default_provider || response.data.integrations.ai_provider.provider,
|
||||
provider: response.data.integrations.ai_provider.provider,
|
||||
provider_api: response.data.integrations.ai_provider.provider_api,
|
||||
base_url: response.data.integrations.ai_provider.base_url,
|
||||
model: response.data.integrations.ai_provider.model,
|
||||
api_key: response.data.integrations.ai_provider.api_key.configured
|
||||
? response.data.integrations.ai_provider.api_key.preview
|
||||
: '',
|
||||
max_tokens: response.data.integrations.ai_provider.max_tokens,
|
||||
anthropic_version: response.data.integrations.ai_provider.anthropic_version,
|
||||
timeout_seconds: response.data.integrations.ai_provider.timeout_seconds,
|
||||
retry_attempts: response.data.integrations.ai_provider.retry_attempts,
|
||||
},
|
||||
})
|
||||
}
|
||||
setAiProviderSaveFeedback({ type: 'success', message: response.data.message || 'AI Provider 连接成功,已保存为全局默认配置' })
|
||||
message.success(response.data.message || 'AI Provider 连接成功')
|
||||
setAiProviderSaveFeedback({ type: 'success', message: response.data.message || '连接测试通过' })
|
||||
message.success(response.data.message || '连接测试通过')
|
||||
} else {
|
||||
setAiProviderSaveFeedback({ type: 'error', message: response.data.message || 'AI Provider 连接失败' })
|
||||
message.error(response.data.message || 'AI Provider 连接失败')
|
||||
@@ -996,12 +988,23 @@ function Settings() {
|
||||
delete configValues.bounding_boxes_json
|
||||
delete configValues.bounding_box_preset
|
||||
}
|
||||
if (['earth_admin0_boundaries', 'earth_coastline', 'earth_claim_lines'].includes(selectedCollector.source)) {
|
||||
try {
|
||||
configValues.mapping_json = JSON.parse(configValues.mapping_json_text || '{}')
|
||||
} catch {
|
||||
message.error('Earth 边界 mapping_json 必须是合法 JSON')
|
||||
return
|
||||
}
|
||||
configValues.target_schema = configValues.target_schema || 'earth_boundary_source'
|
||||
configValues.method = configValues.method || 'GET'
|
||||
delete configValues.mapping_json_text
|
||||
}
|
||||
|
||||
const payload: Record<string, any> = {
|
||||
name: selectedCollector.source,
|
||||
description: `内置采集器覆盖配置:${selectedCollector.name}`,
|
||||
source_type: selectedCollector.source === 'aisstream_vessels' ? 'websocket' : 'http',
|
||||
endpoint: baseValues.endpoint,
|
||||
source_type: selectedCollector.source === 'aisstream_vessels' ? 'websocket' : isEarthPmtilesBuilder ? 'internal' : 'http',
|
||||
endpoint: baseValues.endpoint || '',
|
||||
auth_type: selectedCollector.source === 'aisstream_vessels' ? 'api_key' : 'none',
|
||||
headers,
|
||||
config: configValues,
|
||||
@@ -2026,6 +2029,9 @@ function Settings() {
|
||||
)}
|
||||
/>
|
||||
</Form.Item>
|
||||
<div style={{ marginTop: -16, marginBottom: 12 }}>
|
||||
<Text type="secondary">测试不保存,保存才生效。</Text>
|
||||
</div>
|
||||
|
||||
<Form.Item name={['ai_provider', 'provider_api']} label="协议适配">
|
||||
<Select>
|
||||
@@ -2151,6 +2157,9 @@ function Settings() {
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<div style={{ marginTop: -16, marginBottom: 12 }}>
|
||||
<Text type="secondary">测试不保存,保存才生效。</Text>
|
||||
</div>
|
||||
|
||||
<Form.Item label="WebSearch API Key">
|
||||
<Space direction="vertical" style={{ width: '100%' }}>
|
||||
@@ -2481,14 +2490,39 @@ function Settings() {
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
<Form.Item name="endpoint" label="Endpoint" rules={[{ required: true, message: '请输入 Endpoint' }]}>
|
||||
<Input placeholder={selectedCollectorConfig?.default_url || 'https://api.example.com'} />
|
||||
<Form.Item
|
||||
name="endpoint"
|
||||
label="Endpoint"
|
||||
rules={isEarthPmtilesBuilder ? [] : [{ required: true, message: '请输入 Endpoint' }]}
|
||||
>
|
||||
<Input
|
||||
disabled={isEarthPmtilesBuilder}
|
||||
placeholder={isEarthPmtilesBuilder ? '内部构建器不需要 Endpoint' : selectedCollectorConfig?.default_url || 'https://api.example.com'}
|
||||
/>
|
||||
</Form.Item>
|
||||
{!selectedCollector?.is_custom ? (
|
||||
<Form.Item label="默认 Endpoint">
|
||||
<Input value={selectedCollectorConfig?.default_url || '-'} disabled />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
{isEarthBoundarySourceCollector ? (
|
||||
<>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
|
||||
<Form.Item name={['config', 'method']} label="请求方法">
|
||||
<Select options={[{ value: 'GET', label: 'GET' }, { value: 'POST', label: 'POST' }]} />
|
||||
</Form.Item>
|
||||
<Form.Item name={['config', 'target_schema']} label="目标 Schema">
|
||||
<Select options={[{ value: 'earth_boundary_source', label: 'earth_boundary_source' }]} />
|
||||
</Form.Item>
|
||||
</div>
|
||||
<Form.Item name={['config', 'license']} label="License">
|
||||
<Input placeholder="例如 ODbL / source license / internal" />
|
||||
</Form.Item>
|
||||
<Form.Item name={['config', 'mapping_json_text']} label="Mapping JSON">
|
||||
<Input.TextArea rows={8} />
|
||||
</Form.Item>
|
||||
</>
|
||||
) : null}
|
||||
<Form.List name="headers">
|
||||
{(fields, { add, remove }) => (
|
||||
<Form.Item label="请求头">
|
||||
|
||||
@@ -134,46 +134,49 @@ function Tasks() {
|
||||
|
||||
return (
|
||||
<AppLayout>
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic title="今日任务" value={tasks.length} prefix={<ReloadOutlined />} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="成功率"
|
||||
value={successRate.toFixed(1)}
|
||||
suffix="%"
|
||||
valueStyle={{ color: successRate >= 90 ? '#52c41a' : '#faad14' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic title="成功" value={statusCounts.success} valueStyle={{ color: '#52c41a' }} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col span={6}>
|
||||
<Card>
|
||||
<Statistic title="失败" value={statusCounts.failed} valueStyle={{ color: '#ff4d4f' }} />
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
<div className="page-shell tasks-page">
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24} md={6}>
|
||||
<Card>
|
||||
<Statistic title="今日任务" value={tasks.length} prefix={<ReloadOutlined />} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Card>
|
||||
<Statistic
|
||||
title="成功率"
|
||||
value={successRate.toFixed(1)}
|
||||
suffix="%"
|
||||
valueStyle={{ color: successRate >= 90 ? '#52c41a' : '#faad14' }}
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Card>
|
||||
<Statistic title="成功" value={statusCounts.success} valueStyle={{ color: '#52c41a' }} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} md={6}>
|
||||
<Card>
|
||||
<Statistic title="失败" value={statusCounts.failed} valueStyle={{ color: '#ff4d4f' }} />
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
title="任务历史"
|
||||
extra={
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={fetchTasks}>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<TableScrollRegion>
|
||||
<Table columns={columns} dataSource={tasks} rowKey="id" loading={loading} pagination={{ pageSize: 10 }} scroll={{ x: 'max-content', y: 'calc(100% - 360px)' }} tableLayout="fixed" />
|
||||
</TableScrollRegion>
|
||||
</Card>
|
||||
<Card
|
||||
className="tasks-page__table-card"
|
||||
title="任务历史"
|
||||
extra={
|
||||
<Button type="primary" icon={<ReloadOutlined />} onClick={fetchTasks}>
|
||||
刷新
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<TableScrollRegion className="data-source-table-region">
|
||||
<Table columns={columns} dataSource={tasks} rowKey="id" loading={loading} pagination={{ pageSize: 10 }} scroll={{ x: 'max-content', y: 480 }} tableLayout="fixed" />
|
||||
</TableScrollRegion>
|
||||
</Card>
|
||||
</div>
|
||||
</AppLayout>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,13 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"target": "ES2020",
|
||||
"lib": ["ES2020"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.tooling.tsbuildinfo",
|
||||
"types": ["node"],
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
"include": ["vite.config.mts"]
|
||||
}
|
||||
@@ -2,6 +2,12 @@ import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'path'
|
||||
import fs from 'fs'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const backendPort = process.env.PLANET_BACKEND_PORT || '8000'
|
||||
const backendHttpTarget = `http://localhost:${backendPort}`
|
||||
const backendWsTarget = `ws://localhost:${backendPort}`
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
@@ -42,18 +48,18 @@ export default defineConfig({
|
||||
port: 3000,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:8000',
|
||||
target: backendHttpTarget,
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
},
|
||||
'/ws': {
|
||||
target: 'ws://localhost:8000',
|
||||
target: backendWsTarget,
|
||||
ws: true,
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
},
|
||||
'/health': {
|
||||
target: 'http://localhost:8000',
|
||||
target: backendHttpTarget,
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
},
|
||||
@@ -639,17 +639,271 @@ EOF
|
||||
log_lan_access_notes() {
|
||||
local frontend_port="$1"
|
||||
local backend_port="$2"
|
||||
local ai_provider_port="${3:-$AI_PROVIDER_PORT}"
|
||||
local recommended_lan_ip=""
|
||||
|
||||
if recommended_lan_ip="$(get_recommended_lan_ipv4)"; then
|
||||
log_note "推荐访问地址: http://${recommended_lan_ip}:${frontend_port}"
|
||||
log_note "后端健康检查: http://${recommended_lan_ip}:${backend_port}/health"
|
||||
log_note "AI Provider 健康检查: http://${recommended_lan_ip}:${ai_provider_port}/health"
|
||||
else
|
||||
log_note "前端已对局域网开放,请使用本机局域网 IP 访问 :${frontend_port}"
|
||||
log_note "后端已对局域网开放,请使用本机局域网 IP 访问 :${backend_port}/health"
|
||||
log_note "AI Provider 已对局域网开放,请使用本机局域网 IP 访问 :${ai_provider_port}/health"
|
||||
fi
|
||||
}
|
||||
|
||||
run_windows_admin_powershell_script() {
|
||||
local script_path="$1"
|
||||
local warn_context="$2"
|
||||
local script_win_path=""
|
||||
|
||||
chmod 600 "$script_path" 2>/dev/null || true
|
||||
|
||||
script_win_path="$(wslpath -w "$script_path" 2>/dev/null || true)"
|
||||
if [ -z "$script_win_path" ]; then
|
||||
log_warn "${warn_context},但无法生成管理员 PowerShell 请求"
|
||||
return 1
|
||||
fi
|
||||
|
||||
powershell.exe -NoProfile -Command "Start-Process powershell.exe -Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"${script_win_path}\"'" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
join_csv() {
|
||||
local IFS=","
|
||||
printf "%s" "$*"
|
||||
}
|
||||
|
||||
windows_firewall_missing_ports() {
|
||||
local ports_csv
|
||||
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 1
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
ports_csv="$(join_csv "$@")"
|
||||
|
||||
powershell.exe -NoProfile -Command "
|
||||
\$ErrorActionPreference = 'SilentlyContinue'
|
||||
\$ports = @(${ports_csv})
|
||||
function Test-PortAllowed {
|
||||
param([int]\$Port)
|
||||
\$displayName = 'WSL Planet ' + \$Port
|
||||
\$rule = Get-NetFirewallRule -DisplayName \$displayName -ErrorAction SilentlyContinue |
|
||||
Where-Object { \$_.Enabled -eq 'True' -and \$_.Direction -eq 'Inbound' -and \$_.Action -eq 'Allow' } |
|
||||
Select-Object -First 1
|
||||
if (-not \$rule) { return \$false }
|
||||
\$filter = \$rule | Get-NetFirewallPortFilter -ErrorAction SilentlyContinue |
|
||||
Where-Object { \$_.Protocol -in @('TCP', 'Any') -and \$_.LocalPort -eq [string]\$Port } |
|
||||
Select-Object -First 1
|
||||
if (\$filter) {
|
||||
return \$true
|
||||
}
|
||||
return \$false
|
||||
}
|
||||
\$missing = @()
|
||||
foreach (\$port in \$ports) {
|
||||
if (-not (Test-PortAllowed \$port)) { \$missing += \$port }
|
||||
}
|
||||
if (\$missing.Count -gt 0) {
|
||||
'missing=' + (\$missing -join ',')
|
||||
}
|
||||
" 2>/dev/null | tr -d '\r' | sed -nE 's/^missing=//p' | tail -n 1
|
||||
}
|
||||
|
||||
request_windows_firewall_rules_if_needed() {
|
||||
local missing_ports=""
|
||||
local script_path=""
|
||||
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
is_wsl_environment || return 0
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 0
|
||||
case "${PLANET_WINDOWS_FIREWALL_AUTO_PROMPT:-1}" in
|
||||
0|false|no|off)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
missing_ports="$(windows_firewall_missing_ports "$@" || true)"
|
||||
[ -n "$missing_ports" ] || return 0
|
||||
|
||||
script_path="$PLANET_STATE_DIR/windows_firewall_planet.ps1"
|
||||
mkdir -p "$PLANET_STATE_DIR"
|
||||
cat > "$script_path" <<EOF
|
||||
\$ErrorActionPreference = 'Stop'
|
||||
\$ports = @(${missing_ports})
|
||||
foreach (\$port in \$ports) {
|
||||
\$displayName = "WSL Planet \$port"
|
||||
\$exists = Get-NetFirewallRule -DisplayName \$displayName -ErrorAction SilentlyContinue |
|
||||
Where-Object { \$_.Enabled -eq 'True' -and \$_.Direction -eq 'Inbound' -and \$_.Action -eq 'Allow' }
|
||||
if (-not \$exists) {
|
||||
New-NetFirewallRule -DisplayName \$displayName -Direction Inbound -Action Allow -Protocol TCP -LocalPort \$port | Out-Null
|
||||
}
|
||||
}
|
||||
Write-Host "Planet firewall rules are ready for ports: \$((\$ports -join ', '))"
|
||||
Start-Sleep -Seconds 2
|
||||
EOF
|
||||
|
||||
log_warn "检测到 Windows 防火墙可能未放行端口 ${missing_ports},即将请求管理员 PowerShell 添加规则"
|
||||
run_windows_admin_powershell_script "$script_path" "检测到 Windows 防火墙缺少端口 ${missing_ports} 放行规则" || {
|
||||
log_warn "管理员 PowerShell 未完成防火墙规则创建;局域网设备可能仍无法访问"
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
windows_portproxy_conflict_ports() {
|
||||
local ports_csv
|
||||
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 1
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
ports_csv="$(join_csv "$@")"
|
||||
|
||||
powershell.exe -NoProfile -Command "
|
||||
\$ErrorActionPreference = 'SilentlyContinue'
|
||||
\$ports = @(${ports_csv})
|
||||
\$netsh = Join-Path \$env:WINDIR 'System32\netsh.exe'
|
||||
if (-not (Test-Path \$netsh)) { \$netsh = 'netsh' }
|
||||
\$lines = @(& \$netsh interface portproxy show v4tov4)
|
||||
\$found = @()
|
||||
foreach (\$line in \$lines) {
|
||||
if (\$line -match '^\\s*(\\S+)\\s+(\\d+)\\s+(\\S+)\\s+(\\d+)\\s*$') {
|
||||
\$listenPort = [int]\$Matches[2]
|
||||
if (\$ports -contains \$listenPort) { \$found += \$listenPort }
|
||||
}
|
||||
}
|
||||
if (\$found.Count -gt 0) {
|
||||
'conflict=' + ((\$found | Sort-Object -Unique) -join ',')
|
||||
}
|
||||
" 2>/dev/null | tr -d '\r' | sed -nE 's/^conflict=//p' | tail -n 1
|
||||
}
|
||||
|
||||
write_windows_portproxy_cleanup_script() {
|
||||
local script_path="$1"
|
||||
shift
|
||||
local ports_csv
|
||||
|
||||
ports_csv="$(join_csv "$@")"
|
||||
cat > "$script_path" <<EOF
|
||||
\$ErrorActionPreference = 'Continue'
|
||||
\$ports = @(${ports_csv})
|
||||
\$netsh = Join-Path \$env:WINDIR 'System32\netsh.exe'
|
||||
if (-not (Test-Path \$netsh)) { \$netsh = 'netsh' }
|
||||
\$lines = @(& \$netsh interface portproxy show v4tov4)
|
||||
\$removed = @()
|
||||
foreach (\$line in \$lines) {
|
||||
if (\$line -match '^\\s*(\\S+)\\s+(\\d+)\\s+(\\S+)\\s+(\\d+)\\s*$') {
|
||||
\$listenAddress = \$Matches[1]
|
||||
\$listenPort = [int]\$Matches[2]
|
||||
if (\$ports -contains \$listenPort) {
|
||||
& \$netsh interface portproxy delete v4tov4 listenaddress=\$listenAddress listenport=\$listenPort | Out-Null
|
||||
\$removed += (\$listenAddress + ':' + \$listenPort)
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Host "Planet removed stale portproxy rules: \$((\$removed -join ', '))"
|
||||
Start-Sleep -Seconds 2
|
||||
EOF
|
||||
}
|
||||
|
||||
request_windows_portproxy_cleanup_if_needed() {
|
||||
local conflict_ports=""
|
||||
local script_path=""
|
||||
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
is_wsl_environment || return 0
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 0
|
||||
case "${PLANET_WINDOWS_PORTPROXY_CLEANUP_PROMPT:-1}" in
|
||||
0|false|no|off)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
|
||||
conflict_ports="$(windows_portproxy_conflict_ports "$@" || true)"
|
||||
[ -n "$conflict_ports" ] || return 0
|
||||
|
||||
script_path="$PLANET_STATE_DIR/windows_portproxy_cleanup_planet.ps1"
|
||||
mkdir -p "$PLANET_STATE_DIR"
|
||||
write_windows_portproxy_cleanup_script "$script_path" "$@"
|
||||
|
||||
log_warn "检测到旧 Windows portproxy 占用端口 ${conflict_ports},即将请求管理员 PowerShell 删除"
|
||||
run_windows_admin_powershell_script "$script_path" "检测到旧 portproxy 占用端口 ${conflict_ports}" || {
|
||||
log_warn "管理员 PowerShell 未完成旧 portproxy 清理;端口 ${conflict_ports} 可能仍被 iphlpsvc 占用"
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
write_windows_port_cleanup_script() {
|
||||
local script_path="$1"
|
||||
shift
|
||||
local ports_csv
|
||||
|
||||
ports_csv="$(join_csv "$@")"
|
||||
cat > "$script_path" <<EOF
|
||||
\$ErrorActionPreference = 'Continue'
|
||||
\$ports = @(${ports_csv})
|
||||
\$netsh = Join-Path \$env:WINDIR 'System32\netsh.exe'
|
||||
if (-not (Test-Path \$netsh)) { \$netsh = 'netsh' }
|
||||
|
||||
foreach (\$port in \$ports) {
|
||||
\$lines = @(& \$netsh interface portproxy show v4tov4)
|
||||
foreach (\$line in \$lines) {
|
||||
if (\$line -match '^\\s*(\\S+)\\s+(\\d+)\\s+(\\S+)\\s+(\\d+)\\s*$') {
|
||||
\$listenAddress = \$Matches[1]
|
||||
\$listenPort = [int]\$Matches[2]
|
||||
if (\$listenPort -eq \$port) {
|
||||
& \$netsh interface portproxy delete v4tov4 listenaddress=\$listenAddress listenport=\$listenPort | Out-Null
|
||||
Write-Host "Planet removed portproxy \$($listenAddress):\$listenPort"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
\$connections = @(Get-NetTCPConnection -LocalPort \$port -State Listen -ErrorAction SilentlyContinue)
|
||||
\$seen = @{}
|
||||
foreach (\$connection in \$connections) {
|
||||
\$pidValue = [int]\$connection.OwningProcess
|
||||
if (\$pidValue -le 0 -or \$seen.ContainsKey(\$pidValue)) { continue }
|
||||
\$seen[\$pidValue] = \$true
|
||||
|
||||
\$process = Get-CimInstance Win32_Process -Filter "ProcessId=\$pidValue" -ErrorAction SilentlyContinue
|
||||
\$processName = if (\$process.Name) { \$process.Name } else { 'unknown' }
|
||||
\$services = @(Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { \$_.ProcessId -eq \$pidValue })
|
||||
foreach (\$service in \$services) {
|
||||
try {
|
||||
Stop-Service -Name \$service.Name -Force -ErrorAction Stop
|
||||
Write-Host "Planet stopped service \$($service.Name) on port \$port"
|
||||
} catch {
|
||||
Write-Host "Planet failed to stop service \$($service.Name) on port \$port: \$($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Stop-Process -Id \$pidValue -Force -ErrorAction Stop
|
||||
Write-Host "Planet stopped process \$pidValue (\$processName) on port \$port"
|
||||
} catch {
|
||||
Write-Host "Planet failed to stop process \$pidValue (\$processName) on port \$port: \$($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Start-Sleep -Seconds 1
|
||||
EOF
|
||||
}
|
||||
|
||||
request_windows_port_cleanup() {
|
||||
local script_path="$PLANET_STATE_DIR/windows_port_cleanup_planet.ps1"
|
||||
local ports_label
|
||||
|
||||
[ "$#" -gt 0 ] || return 0
|
||||
is_wsl_environment || return 1
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 1
|
||||
ports_label="$(join_csv "$@")"
|
||||
mkdir -p "$PLANET_STATE_DIR"
|
||||
write_windows_port_cleanup_script "$script_path" "$@"
|
||||
|
||||
log_warn "即将请求管理员 PowerShell 清理 Windows 侧端口 ${ports_label}"
|
||||
run_windows_admin_powershell_script "$script_path" "清理 Windows 侧端口 ${ports_label}" || {
|
||||
log_warn "管理员 PowerShell 未完成端口清理;端口 ${ports_label} 可能仍无法绑定"
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
log_motion_agent_access_notes() {
|
||||
local motion_agent_port="$1"
|
||||
local lan_enabled="${2:-0}"
|
||||
@@ -717,13 +971,29 @@ run_with_retry() {
|
||||
return 1
|
||||
fi
|
||||
|
||||
animate_wait_spinner "${retry_label} 第 ${attempt}/${max_retries} 次失败,${interval} 秒后重试" "$interval"
|
||||
animate_wait_spinner "${retry_label} 本次执行失败,${interval} 秒后进行第 $((attempt + 1)) 次尝试" "$interval"
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
format_wait_elapsed_seconds() {
|
||||
local completed_intervals="${1:-0}"
|
||||
local interval="${2:-1}"
|
||||
|
||||
awk -v completed="$completed_intervals" -v interval="$interval" '
|
||||
BEGIN {
|
||||
value = completed * interval
|
||||
if (value == int(value)) {
|
||||
printf "%d", value
|
||||
} else {
|
||||
printf "%.1f", value
|
||||
}
|
||||
}
|
||||
'
|
||||
}
|
||||
|
||||
docker_daemon_available() {
|
||||
docker info >/dev/null 2>&1
|
||||
}
|
||||
@@ -1196,8 +1466,9 @@ wait_for_http() {
|
||||
local attempt=1
|
||||
local wait_message="检查${service_name}健康检查"
|
||||
local wait_detail_prefix="请求"
|
||||
local elapsed_seconds=""
|
||||
|
||||
set_wait_detail "${wait_detail_prefix} ${url} (1/${attempts})"
|
||||
set_wait_detail "${wait_detail_prefix} ${url},已等待 0 秒"
|
||||
|
||||
while [ "$attempt" -le "$attempts" ]; do
|
||||
if http_ok "$url"; then
|
||||
@@ -1205,7 +1476,8 @@ wait_for_http() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
set_wait_detail "${wait_detail_prefix} ${url} (${attempt}/${attempts})"
|
||||
elapsed_seconds="$(format_wait_elapsed_seconds "$((attempt - 1))" "$interval")"
|
||||
set_wait_detail "${wait_detail_prefix} ${url},已等待 ${elapsed_seconds} 秒"
|
||||
animate_wait_spinner "${wait_message}" "$interval"
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
@@ -1325,8 +1597,9 @@ wait_for_container_health() {
|
||||
local health_status
|
||||
local wait_message="检查${service_name}容器健康检查"
|
||||
local wait_detail_prefix="读取"
|
||||
local elapsed_seconds=""
|
||||
|
||||
set_wait_detail "${wait_detail_prefix} ${container_name} 容器健康状态 (1/${attempts})"
|
||||
set_wait_detail "${wait_detail_prefix} ${container_name} 容器健康状态,已等待 0 秒"
|
||||
|
||||
while [ "$attempt" -le "$attempts" ]; do
|
||||
health_status="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container_name" 2>/dev/null || true)"
|
||||
@@ -1336,7 +1609,8 @@ wait_for_container_health() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
set_wait_detail "${wait_detail_prefix} ${container_name} 容器健康状态 (${attempt}/${attempts})"
|
||||
elapsed_seconds="$(format_wait_elapsed_seconds "$((attempt - 1))" "$interval")"
|
||||
set_wait_detail "${wait_detail_prefix} ${container_name} 容器健康状态,已等待 ${elapsed_seconds} 秒"
|
||||
animate_wait_spinner "${wait_message}" "$interval"
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
@@ -1351,7 +1625,7 @@ fail_unreleased_port() {
|
||||
if [ -z "$(collect_port_pids "$port" || true)" ]; then
|
||||
log_error "端口 ${port} 当前环境内未发现占用进程,但端口仍不可用,请检查宿主机或外部环境占用"
|
||||
print_port_listener_details "$port"
|
||||
log_note "如果显示 Windows listener(如 svchost.exe / iphlpsvc),请优先用管理员 PowerShell 检查 portproxy:netsh interface portproxy show all;删除冲突转发或改用其他端口。"
|
||||
log_note "如果显示 Windows listener(如 svchost.exe / iphlpsvc),脚本会在需要时请求管理员 PowerShell 清理 Windows 侧端口。"
|
||||
else
|
||||
log_error "端口 ${port} 清理失败,请检查占用进程"
|
||||
if command -v lsof >/dev/null 2>&1; then
|
||||
@@ -1360,7 +1634,7 @@ fail_unreleased_port() {
|
||||
ss -ltnp "( sport = :${port} )" 2>/dev/null || true
|
||||
fi
|
||||
print_windows_port_listener_details "$port" || true
|
||||
log_note "请手动停止占用进程,或改用其他端口。"
|
||||
log_note "请手动停止占用进程后重试。"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
@@ -1371,6 +1645,7 @@ retry_wait_for_port_release() {
|
||||
local service_name="$2"
|
||||
local attempt=1
|
||||
local pids=""
|
||||
local elapsed_seconds=""
|
||||
|
||||
while [ "$attempt" -le "$PORT_PRESTART_RETRIES" ]; do
|
||||
if wait_for_port_release "$port"; then
|
||||
@@ -1378,13 +1653,14 @@ retry_wait_for_port_release() {
|
||||
fi
|
||||
|
||||
pids="$(collect_port_pids "$port" || true)"
|
||||
elapsed_seconds="$(format_wait_elapsed_seconds "$((attempt - 1))" "$PORT_PRESTART_RETRY_INTERVAL")"
|
||||
if [ -n "$pids" ]; then
|
||||
log_warn "${service_name}端口 ${port} 仍有监听进程,继续清理 (${attempt}/${PORT_PRESTART_RETRIES})"
|
||||
log_warn "${service_name}端口 ${port} 仍有监听进程,已等待 ${elapsed_seconds} 秒,继续清理"
|
||||
for pid in $pids; do
|
||||
terminate_process_tree KILL "$pid"
|
||||
done
|
||||
else
|
||||
log_warn "${service_name}端口 ${port} 暂未发现监听进程但仍不可绑定,等待释放 (${attempt}/${PORT_PRESTART_RETRIES})"
|
||||
log_warn "${service_name}端口 ${port} 暂未发现监听进程但仍不可绑定,已等待 ${elapsed_seconds} 秒,继续等待释放"
|
||||
print_port_listener_details "$port"
|
||||
fi
|
||||
|
||||
@@ -1395,99 +1671,71 @@ retry_wait_for_port_release() {
|
||||
return 1
|
||||
}
|
||||
|
||||
print_windows_cleanup_recovery_steps() {
|
||||
local port="$1"
|
||||
local service_name="$2"
|
||||
local port_flag
|
||||
local command_example
|
||||
|
||||
case "$service_name" in
|
||||
前端)
|
||||
port_flag="-f"
|
||||
command_example="./planet.sh restart ${port_flag} ${port} --allow-lan"
|
||||
;;
|
||||
后端)
|
||||
port_flag="-b"
|
||||
command_example="./planet.sh restart ${port_flag} ${port} --allow-lan"
|
||||
;;
|
||||
"AI Provider")
|
||||
port_flag="-a"
|
||||
command_example="./planet.sh restart ${port_flag} ${port}"
|
||||
;;
|
||||
"Motion Agent")
|
||||
port_flag="--motion-agent-port"
|
||||
command_example="./planet.sh restart ${port_flag} ${port} --allow-lan"
|
||||
;;
|
||||
*)
|
||||
port_flag=""
|
||||
command_example="./planet.sh restart --allow-lan"
|
||||
;;
|
||||
esac
|
||||
|
||||
log_note "Windows 侧端口被 svchost.exe / iphlpsvc 占用时,通常是管理员 PowerShell 中创建过持久 portproxy 规则,例如 listenport=${port}。"
|
||||
log_note "该规则会由 Windows IP Helper 持续监听端口,项目停止后也不会自动消失;下次启动前必须先删除,否则会与 Vite/后端绑定同一端口冲突。"
|
||||
log_note "请打开“管理员 PowerShell”,优先检查并删除冲突 portproxy:"
|
||||
printf "${DIM} netsh interface portproxy show all${NC}\n"
|
||||
printf "${DIM} netsh interface portproxy delete v4tov4 listenaddress=0.0.0.0 listenport=%s${NC}\n" "$port"
|
||||
log_note "如果没有 portproxy 规则,再确认 PID/服务并临时停止对应服务:"
|
||||
printf "${DIM} netstat -ano | findstr :%s${NC}\n" "$port"
|
||||
printf "${DIM} tasklist /svc /fi \"PID eq <PID>\"${NC}\n"
|
||||
printf "${DIM} Stop-Service iphlpsvc -Force${NC}\n"
|
||||
log_note "如需局域网仍使用 ${port},请清理冲突监听后重新运行 --allow-lan;脚本会直接用 0.0.0.0 绑定该端口。"
|
||||
log_note "重新启动示例:${command_example}"
|
||||
}
|
||||
|
||||
force_cleanup_external_port_listener() {
|
||||
local port="$1"
|
||||
local service_name="$2"
|
||||
local output=""
|
||||
local saw_windows_listener=0
|
||||
local saw_no_windows_listener=0
|
||||
local saw_cleanup_failure=0
|
||||
|
||||
validate_port "$port"
|
||||
is_wsl_environment || return 1
|
||||
command -v powershell.exe >/dev/null 2>&1 || return 1
|
||||
|
||||
log_warn "检测到 WSL 环境,正在检查 ${service_name} 端口 ${port} 的 Windows 侧监听"
|
||||
output="$(
|
||||
powershell.exe -NoProfile -Command "
|
||||
\$ErrorActionPreference = 'Continue'
|
||||
\$port = [int]${port}
|
||||
\$connections = @(Get-NetTCPConnection -LocalPort \$port -State Listen -ErrorAction SilentlyContinue)
|
||||
if (-not \$connections -or \$connections.Count -eq 0) {
|
||||
'no-windows-listener'
|
||||
exit 0
|
||||
}
|
||||
\$seen = @{}
|
||||
foreach (\$connection in \$connections) {
|
||||
\$pidValue = [int]\$connection.OwningProcess
|
||||
if (\$seen.ContainsKey(\$pidValue)) { continue }
|
||||
\$seen[\$pidValue] = \$true
|
||||
\$process = Get-CimInstance Win32_Process -Filter \"ProcessId=\$pidValue\" -ErrorAction SilentlyContinue
|
||||
\$processName = if (\$process.Name) { \$process.Name } else { 'unknown' }
|
||||
\$services = @(Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | Where-Object { \$_.ProcessId -eq \$pidValue })
|
||||
\$serviceNames = @(\$services | Select-Object -ExpandProperty Name)
|
||||
'attempt-windows-cleanup pid={0} process={1} services={2}' -f \$pidValue, \$processName, (\$serviceNames -join ',')
|
||||
log_warn "检查 Windows 侧端口占用: ${port}"
|
||||
if ! print_windows_port_listener_details "$port"; then
|
||||
log_note "Windows 侧未发现端口 ${port} 监听,继续启动"
|
||||
return 0
|
||||
fi
|
||||
|
||||
foreach (\$service in \$services) {
|
||||
try {
|
||||
Stop-Service -Name \$service.Name -Force -ErrorAction Stop
|
||||
'stopped-service {0}' -f \$service.Name
|
||||
} catch {
|
||||
'failed-stop-service {0}: {1}' -f \$service.Name, \$_.Exception.Message
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Stop-Process -Id \$pidValue -Force -ErrorAction Stop
|
||||
'stopped-process {0}' -f \$pidValue
|
||||
} catch {
|
||||
'failed-stop-process {0}: {1}' -f \$pidValue, \$_.Exception.Message
|
||||
}
|
||||
}
|
||||
" 2>&1 | tr -d '\r'
|
||||
)"
|
||||
|
||||
while IFS= read -r line; do
|
||||
[ -n "$line" ] || continue
|
||||
case "$line" in
|
||||
no-windows-listener)
|
||||
saw_no_windows_listener=1
|
||||
log_note "Windows 侧未发现端口 ${port} 监听,继续启动"
|
||||
;;
|
||||
stopped-service*|stopped-process*)
|
||||
saw_windows_listener=1
|
||||
printf "${GREEN} %s${NC}\n" "$line"
|
||||
;;
|
||||
failed-*)
|
||||
saw_windows_listener=1
|
||||
saw_cleanup_failure=1
|
||||
printf "${DIM} %s${NC}\n" "$line"
|
||||
;;
|
||||
attempt-windows-cleanup*)
|
||||
saw_windows_listener=1
|
||||
printf "${DIM} %s${NC}\n" "$line"
|
||||
;;
|
||||
*)
|
||||
printf "${DIM} %s${NC}\n" "$line"
|
||||
;;
|
||||
esac
|
||||
done <<EOF
|
||||
$output
|
||||
EOF
|
||||
log_warn "Windows 侧端口 ${port} 存在监听者,准备请求管理员权限清理"
|
||||
request_windows_port_cleanup "$port" || return 1
|
||||
|
||||
if wait_for_port_release "$port" 10 0.3; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ "$saw_no_windows_listener" -eq 1 ] && [ "$saw_windows_listener" -eq 0 ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ "$saw_windows_listener" -eq 0 ]; then
|
||||
log_warn "Windows 侧未发现端口 ${port} 监听,但端口仍不可绑定"
|
||||
elif [ "$saw_cleanup_failure" -eq 1 ]; then
|
||||
log_warn "Windows 侧监听清理失败,端口 ${port} 仍不可绑定"
|
||||
fi
|
||||
log_warn "Windows 侧端口 ${port} 清理后仍不可绑定"
|
||||
print_windows_cleanup_recovery_steps "$port" "$service_name"
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -1546,6 +1794,7 @@ cleanup_backend_processes() {
|
||||
start_backend_with_retry() {
|
||||
local backend_port="$1"
|
||||
local retry=1
|
||||
local backend_bind_host="0.0.0.0"
|
||||
|
||||
while [ "$retry" -le "$BACKEND_MAX_RETRIES" ]; do
|
||||
if ! cleanup_backend_processes "$backend_port"; then
|
||||
@@ -1553,7 +1802,7 @@ start_backend_with_retry() {
|
||||
fi
|
||||
cd "$SCRIPT_DIR/backend"
|
||||
: > "$BACKEND_LOG_FILE"
|
||||
PYTHONPATH="$SCRIPT_DIR/backend" nohup uv run --project "$SCRIPT_DIR" python -m uvicorn app.main:app --host 0.0.0.0 --port "$backend_port" --reload > "$BACKEND_LOG_FILE" 2>&1 &
|
||||
PYTHONPATH="$SCRIPT_DIR/backend" nohup uv run --project "$SCRIPT_DIR" python -m uvicorn app.main:app --host "$backend_bind_host" --port "$backend_port" --reload > "$BACKEND_LOG_FILE" 2>&1 &
|
||||
BACKEND_PID=$!
|
||||
write_pid_file "$BACKEND_PID_FILE" "$BACKEND_PID"
|
||||
if [ "$VERBOSE" -eq 1 ]; then
|
||||
@@ -1575,7 +1824,7 @@ start_backend_with_retry() {
|
||||
report_backend_port_conflict_if_needed "$backend_port" "$BACKEND_LOG_FILE"
|
||||
return 1
|
||||
fi
|
||||
animate_wait_spinner "后端第 ${retry}/${BACKEND_MAX_RETRIES} 次启动未就绪,准备重试" "$BACKEND_HEALTH_CHECK_INTERVAL"
|
||||
animate_wait_spinner "后端启动未就绪,准备再次尝试" "$BACKEND_HEALTH_CHECK_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
|
||||
@@ -1616,7 +1865,7 @@ start_ai_provider_service() {
|
||||
|
||||
remove_ai_provider_containers
|
||||
AI_PROVIDER_RECREATE_REQUIRED=1
|
||||
animate_wait_spinner "AI Provider 第 ${retry}/${AI_PROVIDER_START_MAX_RETRIES} 次启动后仍未健康,正在重启容器" "$AI_PROVIDER_RETRY_INTERVAL"
|
||||
animate_wait_spinner "AI Provider 启动后仍未健康,正在重启容器并准备再次尝试" "$AI_PROVIDER_RETRY_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
|
||||
@@ -1647,7 +1896,7 @@ ensure_database_services_healthy() {
|
||||
fi
|
||||
|
||||
docker restart planet_postgres planet_redis >/dev/null 2>&1 || true
|
||||
animate_wait_spinner "数据库第 ${retry}/${DATABASE_START_MAX_RETRIES} 次启动后仍未健康,正在重启容器" "$DATABASE_RETRY_INTERVAL"
|
||||
animate_wait_spinner "数据库启动后仍未健康,正在重启容器并准备再次尝试" "$DATABASE_RETRY_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
}
|
||||
@@ -1672,7 +1921,7 @@ ensure_postgres_service_healthy() {
|
||||
fi
|
||||
|
||||
docker restart planet_postgres >/dev/null 2>&1 || true
|
||||
animate_wait_spinner "PostgreSQL 第 ${retry}/${DATABASE_START_MAX_RETRIES} 次启动后仍未健康,正在重启容器" "$DATABASE_RETRY_INTERVAL"
|
||||
animate_wait_spinner "PostgreSQL 启动后仍未健康,正在重启容器并准备再次尝试" "$DATABASE_RETRY_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
}
|
||||
@@ -1692,7 +1941,7 @@ restart_database_service() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
animate_wait_spinner "数据库第 ${retry}/${DATABASE_START_MAX_RETRIES} 次重启后仍未健康,继续重试" "$DATABASE_RETRY_INTERVAL"
|
||||
animate_wait_spinner "数据库重启后仍未健康,准备再次尝试" "$DATABASE_RETRY_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
}
|
||||
@@ -2064,6 +2313,7 @@ cleanup_frontend_processes() {
|
||||
fi
|
||||
|
||||
pkill -f "${FRONTEND_VITE_ENTRY} --port ${frontend_port} --strictPort" 2>/dev/null || true
|
||||
pkill -f "${FRONTEND_VITE_ENTRY} --host 127.0.0.1 --port ${frontend_port} --strictPort" 2>/dev/null || true
|
||||
pkill -f "${FRONTEND_VITE_ENTRY} --host 0.0.0.0 --port ${frontend_port} --strictPort" 2>/dev/null || true
|
||||
}
|
||||
|
||||
@@ -2071,6 +2321,7 @@ start_frontend_with_retry() {
|
||||
local frontend_port="$1"
|
||||
local frontend_port_requested="${2:-0}"
|
||||
local frontend_lan_enabled="${3:-0}"
|
||||
local backend_port="${4:-$DEFAULT_BACKEND_PORT}"
|
||||
local retry=1
|
||||
|
||||
while [ "$retry" -le "$FRONTEND_MAX_RETRIES" ]; do
|
||||
@@ -2087,7 +2338,7 @@ start_frontend_with_retry() {
|
||||
frontend_args+=(--host 0.0.0.0)
|
||||
fi
|
||||
frontend_args+=(--port "$frontend_port" --strictPort)
|
||||
nohup "$FRONTEND_RUNTIME_BIN" "${frontend_args[@]}" > "$FRONTEND_LOG_FILE" 2>&1 &
|
||||
PLANET_BACKEND_PORT="$backend_port" nohup "$FRONTEND_RUNTIME_BIN" "${frontend_args[@]}" > "$FRONTEND_LOG_FILE" 2>&1 &
|
||||
FRONTEND_PID=$!
|
||||
write_pid_file "$FRONTEND_PID_FILE" "$FRONTEND_PID"
|
||||
|
||||
@@ -2102,7 +2353,7 @@ start_frontend_with_retry() {
|
||||
kill_port_if_requested "$frontend_port" "前端"
|
||||
fi
|
||||
|
||||
animate_wait_spinner "前端第 ${retry}/${FRONTEND_MAX_RETRIES} 次启动未就绪,准备重试" "$FRONTEND_HEALTH_CHECK_INTERVAL"
|
||||
animate_wait_spinner "前端启动未就绪,准备再次尝试" "$FRONTEND_HEALTH_CHECK_INTERVAL"
|
||||
retry=$((retry + 1))
|
||||
done
|
||||
|
||||
@@ -2114,6 +2365,7 @@ start_frontend_service() {
|
||||
local frontend_port="$1"
|
||||
local frontend_port_requested="$2"
|
||||
local frontend_lan_enabled="${3:-0}"
|
||||
local backend_port="${4:-$DEFAULT_BACKEND_PORT}"
|
||||
|
||||
if [ "$frontend_port_requested" -eq 1 ]; then
|
||||
kill_port_if_requested "$frontend_port" "前端"
|
||||
@@ -2130,11 +2382,14 @@ start_frontend_service() {
|
||||
else
|
||||
set_wait_detail "启动 Vite 开发服务器"
|
||||
fi
|
||||
if ! start_frontend_with_retry "$frontend_port" "$frontend_port_requested" "$frontend_lan_enabled"; then
|
||||
if ! start_frontend_with_retry "$frontend_port" "$frontend_port_requested" "$frontend_lan_enabled" "$backend_port"; then
|
||||
stop_wait_session
|
||||
log_error "前端启动失败,已重试 ${FRONTEND_MAX_RETRIES} 次"
|
||||
tail -10 "$FRONTEND_LOG_FILE"
|
||||
print_port_listener_details "$frontend_port"
|
||||
if frontend_log_indicates_port_conflict "$FRONTEND_LOG_FILE"; then
|
||||
print_windows_cleanup_recovery_steps "$frontend_port" "前端"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
stop_wait_session
|
||||
@@ -2602,10 +2857,51 @@ PY
|
||||
log_note "邮箱: ${email}"
|
||||
}
|
||||
|
||||
prepare_allow_lan_public_ports() {
|
||||
[ "$FRONTEND_LAN_ENABLED" -eq 1 ] || return 0
|
||||
|
||||
log_step "检查局域网端口可绑定"
|
||||
kill_port_if_requested "$FRONTEND_PORT" "前端"
|
||||
kill_port_if_requested "$BACKEND_PORT" "后端"
|
||||
kill_port_if_requested "$AI_PROVIDER_PORT" "AI Provider"
|
||||
request_windows_portproxy_cleanup_if_needed "$FRONTEND_PORT" "$BACKEND_PORT" "$AI_PROVIDER_PORT" || true
|
||||
request_windows_firewall_rules_if_needed "$FRONTEND_PORT" "$BACKEND_PORT" "$AI_PROVIDER_PORT" || true
|
||||
}
|
||||
|
||||
verify_http_endpoint() {
|
||||
local label="$1"
|
||||
local url="$2"
|
||||
|
||||
log_note "检查${label}: ${url}"
|
||||
if ! http_ok "$url"; then
|
||||
log_error "${label}不可访问: ${url}"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
verify_allow_lan_access() {
|
||||
local lan_ip=""
|
||||
|
||||
[ "$FRONTEND_LAN_ENABLED" -eq 1 ] || return 0
|
||||
|
||||
verify_http_endpoint "本机访问" "http://localhost:${FRONTEND_PORT}" || exit 1
|
||||
verify_http_endpoint "本机访问" "http://localhost:${BACKEND_PORT}/health" || exit 1
|
||||
verify_http_endpoint "本机访问" "http://localhost:${AI_PROVIDER_PORT}/health" || exit 1
|
||||
|
||||
if lan_ip="$(get_recommended_lan_ipv4)"; then
|
||||
verify_http_endpoint "局域网访问" "http://${lan_ip}:${FRONTEND_PORT}" || exit 1
|
||||
verify_http_endpoint "局域网访问" "http://${lan_ip}:${BACKEND_PORT}/health" || exit 1
|
||||
verify_http_endpoint "局域网访问" "http://${lan_ip}:${AI_PROVIDER_PORT}/health" || exit 1
|
||||
else
|
||||
log_warn "未能识别局域网 IP,跳过局域网端到端健康检查"
|
||||
fi
|
||||
}
|
||||
|
||||
# Top-level commands
|
||||
start() {
|
||||
parse_service_args "$@"
|
||||
cleanup_exit_containers
|
||||
prepare_allow_lan_public_ports
|
||||
|
||||
START_RUN_ACTIVE=1
|
||||
START_RUN_COMPLETED=0
|
||||
@@ -2617,7 +2913,7 @@ start() {
|
||||
|
||||
start_backend_service "$BACKEND_PORT" "$BACKEND_PORT_REQUESTED" "$AI_PROVIDER_PORT"
|
||||
STARTED_BACKEND_THIS_RUN=1
|
||||
start_frontend_service "$FRONTEND_PORT" "$FRONTEND_PORT_REQUESTED" "$FRONTEND_LAN_ENABLED"
|
||||
start_frontend_service "$FRONTEND_PORT" "$FRONTEND_PORT_REQUESTED" "$FRONTEND_LAN_ENABLED" "$BACKEND_PORT"
|
||||
STARTED_FRONTEND_THIS_RUN=1
|
||||
if [ "$MOTION_AGENT_REQUESTED" -eq 1 ]; then
|
||||
start_motion_agent_service "$MOTION_AGENT_PORT" "$MOTION_AGENT_DRY_RUN" "$FRONTEND_LAN_ENABLED"
|
||||
@@ -2625,6 +2921,7 @@ start() {
|
||||
fi
|
||||
|
||||
write_port_state "$BACKEND_PORT" "$FRONTEND_PORT" "$AI_PROVIDER_PORT" "$MOTION_AGENT_PORT"
|
||||
verify_allow_lan_access
|
||||
START_RUN_COMPLETED=1
|
||||
START_RUN_ACTIVE=0
|
||||
|
||||
@@ -2652,6 +2949,16 @@ stop() {
|
||||
log_success "已停止"
|
||||
}
|
||||
|
||||
stop_local_services_for_restart() {
|
||||
log_warn "正在停止本地服务"
|
||||
stop_backend_service
|
||||
stop_ai_provider_service
|
||||
stop_frontend_service
|
||||
stop_motion_agent_service
|
||||
stop_container_if_running "planet_postgres" "PostgreSQL"
|
||||
stop_container_if_running "planet_redis" "Redis"
|
||||
}
|
||||
|
||||
restart() {
|
||||
parse_service_args "$@"
|
||||
cleanup_exit_containers
|
||||
@@ -2661,7 +2968,7 @@ restart() {
|
||||
local state_motion_agent_port=""
|
||||
|
||||
if [ "$BACKEND_PORT_REQUESTED" -eq 0 ] && [ "$FRONTEND_PORT_REQUESTED" -eq 0 ] && [ "$AI_PROVIDER_REQUESTED" -eq 0 ] && [ "$MOTION_AGENT_REQUESTED" -eq 0 ] && [ "$DATABASE_REQUESTED" -eq 0 ]; then
|
||||
stop
|
||||
stop_local_services_for_restart
|
||||
sleep 1
|
||||
start "$@"
|
||||
return 0
|
||||
@@ -2676,6 +2983,9 @@ restart() {
|
||||
if [ "$AI_PROVIDER_REQUESTED" -eq 1 ]; then
|
||||
stop_ai_provider_service
|
||||
sleep 1
|
||||
if [ "$FRONTEND_LAN_ENABLED" -eq 1 ]; then
|
||||
kill_port_if_requested "$AI_PROVIDER_PORT" "AI Provider"
|
||||
fi
|
||||
start_ai_provider_service "$AI_PROVIDER_PORT"
|
||||
fi
|
||||
|
||||
@@ -2688,7 +2998,7 @@ restart() {
|
||||
if [ "$FRONTEND_PORT_REQUESTED" -eq 1 ]; then
|
||||
stop_frontend_service
|
||||
sleep 1
|
||||
start_frontend_service "$FRONTEND_PORT" 1 "$FRONTEND_LAN_ENABLED"
|
||||
start_frontend_service "$FRONTEND_PORT" 1 "$FRONTEND_LAN_ENABLED" "$BACKEND_PORT"
|
||||
fi
|
||||
|
||||
if [ "$MOTION_AGENT_REQUESTED" -eq 1 ]; then
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "planet"
|
||||
version = "0.53.0"
|
||||
version = "0.58.0"
|
||||
description = "智能星球计划 - 态势感知系统"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
|
||||
@@ -379,6 +379,9 @@ Editing `frontend/public/earth`, 3D Earth, canvas/Three.js rendering, BGP/vessel
|
||||
- Avoid one-off visual patches before checking render order, coordinate ownership, and data lifecycle.
|
||||
- Use Three.js for 3D elements.
|
||||
- Verify 3D/canvas work with real rendering, not only TypeScript build.
|
||||
- For concentric or near-concentric Earth surface shells, do not place overlay radii too close to `CONFIG.earthRadius`.
|
||||
Maintain explicit altitude offsets with enough separation for far-zoom depth-buffer precision, document them in `earth-render-layer-order.md`, and verify at zoomed-out views such as 50%.
|
||||
If snow, black blocks, or flicker appears on the globe, check for z-fighting between the base sphere, land/ocean fill, HD texture, terrain, clouds, and occluder before hiding layers or adding LOD workarounds.
|
||||
- Do not let loading messages, phase labels, or optimistic UI override real backend task state.
|
||||
- WebSocket data frames should include timestamps, type, and payload when streaming Earth state.
|
||||
- Default heartbeat for real-time streams is 30 seconds unless a protocol states otherwise.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a usable high-precision China-POV Earth boundary GeoJSON artifact."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--admin0-source", type=Path, required=True)
|
||||
parser.add_argument("--coastline-source", type=Path, required=True)
|
||||
parser.add_argument("--claims-source", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, default=Path("frontend/public/earth/data/boundaries/v1"))
|
||||
parser.add_argument("--build-input-hash", required=True)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def load_geojson(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if payload.get("type") == "Feature":
|
||||
payload = {"type": "FeatureCollection", "features": [payload]}
|
||||
if payload.get("type") != "FeatureCollection":
|
||||
raise ValueError(f"{path} must be a GeoJSON FeatureCollection or Feature")
|
||||
return payload
|
||||
|
||||
|
||||
def feature_collection(features: list[dict[str, Any]], **extra: Any) -> dict[str, Any]:
|
||||
return {"type": "FeatureCollection", **extra, "features": features}
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def apply_china_pov_admin0(admin0: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
out: list[dict[str, Any]] = []
|
||||
for feature in admin0.get("features") or []:
|
||||
props = dict(feature.get("properties") or {})
|
||||
name = props.get("ADMIN") or props.get("NAME") or props.get("NAME_EN")
|
||||
iso = props.get("ISO_A3") or props.get("ADM0_A3")
|
||||
|
||||
if iso == "TWN" or name == "Taiwan":
|
||||
props.update(
|
||||
{
|
||||
"ADMIN": "China",
|
||||
"NAME": "China",
|
||||
"NAME_EN": "China",
|
||||
"NAME_ZH": "中国",
|
||||
"SOVEREIGNT": "China",
|
||||
"SOV_A3": "CHN",
|
||||
"ISO_A3": "CHN",
|
||||
"ADM0_A3": "CHN",
|
||||
"BRK_A3": "CHN",
|
||||
"PLANET_POV_NOTE": "Taiwan/Penghu rendered as China for china-pov-v1",
|
||||
}
|
||||
)
|
||||
elif iso == "KOS" or name == "Kosovo":
|
||||
props.update(
|
||||
{
|
||||
"ADMIN": "Serbia",
|
||||
"NAME": "Serbia",
|
||||
"NAME_EN": "Serbia",
|
||||
"NAME_ZH": "塞尔维亚",
|
||||
"SOVEREIGNT": "Serbia",
|
||||
"SOV_A3": "SRB",
|
||||
"ISO_A3": "SRB",
|
||||
"ADM0_A3": "SRB",
|
||||
"BRK_A3": "SRB",
|
||||
"PLANET_POV_NOTE": "Kosovo rendered as Serbia for china-pov-v1",
|
||||
}
|
||||
)
|
||||
elif iso == "PSE" or name == "Palestine":
|
||||
props.update(
|
||||
{
|
||||
"ADMIN": "Palestine",
|
||||
"NAME": "Palestine",
|
||||
"NAME_EN": "Palestine",
|
||||
"NAME_ZH": "巴勒斯坦",
|
||||
"ISO_A3": "PSE",
|
||||
"ADM0_A3": "PSE",
|
||||
"BRK_A3": "PSE",
|
||||
"PLANET_POV_NOTE": "Gaza is rendered within Palestine for china-pov-v1",
|
||||
}
|
||||
)
|
||||
|
||||
out.append({**feature, "properties": props})
|
||||
return out
|
||||
|
||||
|
||||
def normalize_claim_features(claims: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
features = []
|
||||
for feature in claims.get("features") or []:
|
||||
if not feature.get("geometry"):
|
||||
continue
|
||||
props = dict(feature.get("properties") or {})
|
||||
props.setdefault("name", "九段线")
|
||||
props.setdefault("name_en", "Nine-dash line")
|
||||
props["PLANET_LAYER"] = "claim_line"
|
||||
features.append({**feature, "properties": props})
|
||||
return features
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
admin0 = load_geojson(args.admin0_source)
|
||||
coastline = load_geojson(args.coastline_source)
|
||||
claims = load_geojson(args.claims_source)
|
||||
|
||||
admin_features = apply_china_pov_admin0(admin0)
|
||||
coastline_features = [
|
||||
{**feature, "properties": {**(feature.get("properties") or {}), "PLANET_LAYER": "coastline"}}
|
||||
for feature in coastline.get("features") or []
|
||||
if feature.get("geometry")
|
||||
]
|
||||
claim_features = normalize_claim_features(claims)
|
||||
|
||||
hover_path = args.output_dir / "hover-index.geojson"
|
||||
base_path = args.output_dir / "base.geojson"
|
||||
claim_path = args.output_dir / "china-claims.geojson"
|
||||
manifest_path = args.output_dir / "manifest.json"
|
||||
|
||||
hover = feature_collection(admin_features, name="earth-boundaries-china-pov-hover")
|
||||
base = feature_collection(
|
||||
[*admin_features, *coastline_features],
|
||||
name="earth-boundaries-china-pov-base",
|
||||
)
|
||||
claim_fc = feature_collection(claim_features, name="earth-boundaries-china-pov-claims")
|
||||
|
||||
for path, payload in ((hover_path, hover), (base_path, base), (claim_path, claim_fc)):
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, ensure_ascii=False, separators=(",", ":"))
|
||||
f.write("\n")
|
||||
|
||||
manifest = {
|
||||
"version": "china-pov-v1",
|
||||
"builtAt": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(),
|
||||
"tileProvider": "geojson-high-precision",
|
||||
"format": "geojson",
|
||||
"buildInputHash": args.build_input_hash,
|
||||
"base": base_path.name,
|
||||
"hoverIndex": hover_path.name,
|
||||
"claimLine": claim_path.name,
|
||||
"sourceFeatureCount": len(admin_features),
|
||||
"coastlineFeatureCount": len(coastline_features),
|
||||
"claimFeatureCount": len(claim_features),
|
||||
"tiles": {"minZoom": 0, "maxZoom": 0},
|
||||
"chinaClaims": {"available": bool(claim_features), "path": claim_path.name},
|
||||
"sha256": {
|
||||
"base": sha256_file(base_path),
|
||||
"hoverIndex": sha256_file(hover_path),
|
||||
"claimLine": sha256_file(claim_path),
|
||||
},
|
||||
"povPolicy": {
|
||||
"profile": "china-pov-v1",
|
||||
"applied": True,
|
||||
"notes": [
|
||||
"Taiwan/Penghu rendered as China.",
|
||||
"Kosovo rendered as Serbia.",
|
||||
"Gaza rendered within Palestine.",
|
||||
"Nine-dash line rendered as a claim-line layer.",
|
||||
"Zangnan/Aksai Chin require an audited polygon override package for exact subtract/union geometry.",
|
||||
],
|
||||
},
|
||||
}
|
||||
with manifest_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "success",
|
||||
"provider": "geojson-high-precision",
|
||||
"manifest": str(manifest_path),
|
||||
"admin0_features": len(admin_features),
|
||||
"coastline_features": len(coastline_features),
|
||||
"claim_features": len(claim_features),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the production Earth boundary PMTiles artifact from collected sources."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--admin0-source", type=Path, required=True)
|
||||
parser.add_argument("--coastline-source", type=Path, required=True)
|
||||
parser.add_argument("--claims-source", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
parser.add_argument("--build-input-hash", required=True)
|
||||
parser.add_argument("--pov-policy", type=Path, default=None)
|
||||
parser.add_argument("--min-zoom", type=int, default=0)
|
||||
parser.add_argument("--max-zoom", type=int, default=10)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def require_tool(name: str) -> str:
|
||||
path = shutil.which(name)
|
||||
if not path:
|
||||
raise RuntimeError(f"required external tool not found in PATH: {name}")
|
||||
return path
|
||||
|
||||
|
||||
def load_geojson(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if payload.get("type") != "FeatureCollection":
|
||||
raise ValueError(f"{path} must be a GeoJSON FeatureCollection")
|
||||
return payload
|
||||
|
||||
|
||||
def iter_layer_features(payload: dict[str, Any], layer: str) -> list[dict[str, Any]]:
|
||||
out = []
|
||||
for feature in payload.get("features") or []:
|
||||
if not feature.get("geometry"):
|
||||
continue
|
||||
props = dict(feature.get("properties") or {})
|
||||
props["tippecanoe"] = {"layer": layer}
|
||||
out.append(
|
||||
{
|
||||
"type": "Feature",
|
||||
"geometry": feature["geometry"],
|
||||
"properties": props,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def write_ndjson(path: Path, features: list[dict[str, Any]]) -> None:
|
||||
with path.open("w", encoding="utf-8") as f:
|
||||
for feature in features:
|
||||
f.write(json.dumps(feature, ensure_ascii=False, separators=(",", ":")))
|
||||
f.write("\n")
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
tippecanoe = require_tool("tippecanoe")
|
||||
pmtiles = require_tool("pmtiles")
|
||||
|
||||
admin0 = load_geojson(args.admin0_source)
|
||||
coastline = load_geojson(args.coastline_source)
|
||||
claims = load_geojson(args.claims_source)
|
||||
features = [
|
||||
*iter_layer_features(admin0, "boundary_admin0"),
|
||||
*iter_layer_features(coastline, "coastline"),
|
||||
*iter_layer_features(claims, "claim_line"),
|
||||
]
|
||||
if not features:
|
||||
raise RuntimeError("no features available for PMTiles build")
|
||||
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.manifest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="planet-earth-boundaries-") as tmp:
|
||||
tmp_dir = Path(tmp)
|
||||
ndjson_path = tmp_dir / "earth-boundaries.ndjson"
|
||||
mbtiles_path = tmp_dir / "earth-boundaries.mbtiles"
|
||||
write_ndjson(ndjson_path, features)
|
||||
|
||||
subprocess.run(
|
||||
[
|
||||
tippecanoe,
|
||||
"--force",
|
||||
"--read-parallel",
|
||||
"--minimum-zoom",
|
||||
str(args.min_zoom),
|
||||
"--maximum-zoom",
|
||||
str(args.max_zoom),
|
||||
"--no-tile-compression",
|
||||
"--output",
|
||||
str(mbtiles_path),
|
||||
str(ndjson_path),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run([pmtiles, "convert", str(mbtiles_path), str(args.output)], check=True)
|
||||
|
||||
manifest = {
|
||||
"version": "china-pov-v1",
|
||||
"builtAt": dt.datetime.now(dt.UTC).replace(microsecond=0).isoformat(),
|
||||
"tileProvider": "pmtiles-mvt",
|
||||
"format": "pmtiles+mvt",
|
||||
"buildInputHash": args.build_input_hash,
|
||||
"pmtiles": {
|
||||
"path": os.path.relpath(args.output, args.manifest.parent),
|
||||
"sha256": sha256_file(args.output),
|
||||
},
|
||||
"tiles": {
|
||||
"minZoom": args.min_zoom,
|
||||
"maxZoom": args.max_zoom,
|
||||
},
|
||||
"layers": ["boundary_admin0", "boundary_disputed_internal", "coastline", "claim_line"],
|
||||
"povPolicy": {
|
||||
"path": str(args.pov_policy) if args.pov_policy else None,
|
||||
"applied": False,
|
||||
"note": "This builder packages collected sources. Full China POV geometry overlay is still a source-prep responsibility.",
|
||||
},
|
||||
"base": None,
|
||||
"hoverIndex": None,
|
||||
}
|
||||
with args.manifest.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "success",
|
||||
"output": str(args.output),
|
||||
"features": len(features),
|
||||
"format": "pmtiles+mvt",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check whether the Earth boundary pipeline is ready for PMTiles production.
|
||||
|
||||
This is intentionally a verifier, not a fake builder. It fails when the repo is
|
||||
still using seed data or when the external MVT/PMTiles toolchain is absent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
DEFAULT_CONFIG = Path("config/earth-boundary-sources.example.json")
|
||||
DEFAULT_ARTIFACT = Path("frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles")
|
||||
|
||||
|
||||
def load_json(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError(f"{path} must contain a JSON object")
|
||||
return payload
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
||||
parser.add_argument("--artifact", type=Path, default=DEFAULT_ARTIFACT)
|
||||
args = parser.parse_args()
|
||||
|
||||
config = load_json(args.config)
|
||||
policy = config.get("policy") or {}
|
||||
collector_configs = config.get("collectorConfigs") or {}
|
||||
failures: list[str] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
if policy.get("productionTileFormat") != "pmtiles+mvt":
|
||||
failures.append("policy.productionTileFormat must be pmtiles+mvt")
|
||||
if not policy.get("povPolicyPath"):
|
||||
failures.append("policy.povPolicyPath is required")
|
||||
required_kinds = {"admin0-boundaries", "coastline", "claim-lines"}
|
||||
configured_kinds = {str(source.get("sourceKind")) for source in collector_configs.values()}
|
||||
missing_kinds = sorted(required_kinds - configured_kinds)
|
||||
if missing_kinds:
|
||||
failures.append(f"missing production source kind(s): {', '.join(missing_kinds)}")
|
||||
for collector_name, source in collector_configs.items():
|
||||
endpoint = str(source.get("endpoint") or "")
|
||||
if not endpoint or endpoint.startswith("https://example.com/"):
|
||||
failures.append(f"{collector_name} endpoint must be configured to an audited production source")
|
||||
|
||||
for tool in ("tippecanoe", "pmtiles"):
|
||||
if shutil.which(tool) is None:
|
||||
failures.append(f"external tool not found in PATH: {tool}")
|
||||
|
||||
if not args.artifact.exists():
|
||||
warnings.append(f"PMTiles artifact does not exist yet: {args.artifact}")
|
||||
|
||||
result = {
|
||||
"ready": not failures,
|
||||
"failures": failures,
|
||||
"warnings": warnings,
|
||||
"artifact": str(args.artifact),
|
||||
}
|
||||
print(json.dumps(result, ensure_ascii=False, sort_keys=True))
|
||||
return 0 if not failures else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Collect versioned source files for the Earth boundary tile pipeline.
|
||||
|
||||
This is an offline ingestion helper, not a runtime service. It downloads or
|
||||
copies declared source packages, verifies optional sha256 checksums, and writes
|
||||
a manifest that the tile builder can reference during audited rebuilds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
DEFAULT_CONFIG = Path("config/earth-boundary-sources.example.json")
|
||||
DEFAULT_OUTPUT = Path("data/earth-boundary-sources")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
||||
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def load_config(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
payload = json.load(f)
|
||||
if not isinstance(payload.get("sources"), list):
|
||||
raise ValueError(f"{path} must contain a sources array")
|
||||
return payload
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def safe_filename(source: dict[str, Any]) -> str:
|
||||
name = str(source.get("name") or source.get("id") or "source")
|
||||
filename = source.get("filename")
|
||||
if filename:
|
||||
return Path(str(filename)).name
|
||||
suffix = Path(str(source.get("url") or source.get("path") or name)).suffix
|
||||
cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_") else "-" for ch in name).strip("-")
|
||||
return f"{cleaned or 'source'}{suffix or '.dat'}"
|
||||
|
||||
|
||||
def collect_source(source: dict[str, Any], output_dir: Path) -> dict[str, Any]:
|
||||
source_id = source.get("id")
|
||||
if not source_id:
|
||||
raise ValueError("each source requires an id")
|
||||
target = output_dir / safe_filename(source)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if source.get("url"):
|
||||
request = urllib.request.Request(
|
||||
str(source["url"]),
|
||||
headers={"User-Agent": "planet-earth-boundary-source-collector/1.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=60) as response, target.open("wb") as f:
|
||||
shutil.copyfileobj(response, f)
|
||||
elif source.get("path"):
|
||||
shutil.copy2(Path(str(source["path"])).expanduser(), target)
|
||||
else:
|
||||
raise ValueError(f"source {source_id} requires url or path")
|
||||
|
||||
actual_sha256 = sha256_file(target)
|
||||
expected_sha256 = source.get("sha256")
|
||||
if expected_sha256 and actual_sha256.lower() != str(expected_sha256).lower():
|
||||
target.unlink(missing_ok=True)
|
||||
raise ValueError(
|
||||
f"source {source_id} sha256 mismatch: expected {expected_sha256}, got {actual_sha256}"
|
||||
)
|
||||
|
||||
return {
|
||||
"id": source_id,
|
||||
"name": source.get("name") or source_id,
|
||||
"kind": source.get("kind") or "unknown",
|
||||
"license": source.get("license"),
|
||||
"pov": source.get("pov"),
|
||||
"path": str(target),
|
||||
"sha256": actual_sha256,
|
||||
"source": source.get("url") or source.get("path"),
|
||||
"notes": source.get("notes"),
|
||||
}
|
||||
|
||||
|
||||
def collect_policy(config: dict[str, Any]) -> dict[str, Any] | None:
|
||||
policy = config.get("policy") or {}
|
||||
policy_path_value = policy.get("povPolicyPath")
|
||||
if not policy_path_value:
|
||||
return None
|
||||
|
||||
policy_path = Path(str(policy_path_value)).expanduser()
|
||||
if not policy_path.exists():
|
||||
raise FileNotFoundError(f"POV policy file not found: {policy_path}")
|
||||
|
||||
with policy_path.open("r", encoding="utf-8") as f:
|
||||
policy_payload = json.load(f)
|
||||
|
||||
return {
|
||||
"profile": policy_payload.get("profile") or policy.get("profile"),
|
||||
"path": str(policy_path),
|
||||
"sha256": sha256_file(policy_path),
|
||||
"schema": policy_payload.get("schema"),
|
||||
"ruleCount": len(policy_payload.get("rules") or []),
|
||||
"productionTileFormat": policy.get("productionTileFormat"),
|
||||
"debugTileFormat": policy.get("debugTileFormat"),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
args = parse_args()
|
||||
config = load_config(args.config)
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
collected = [collect_source(source, args.output) for source in config["sources"]]
|
||||
pov_policy = collect_policy(config)
|
||||
manifest = {
|
||||
"schema": "planet-earth-boundary-sources/v1",
|
||||
"sources": collected,
|
||||
"povPolicy": pov_policy,
|
||||
"policy": config.get("policy", {}),
|
||||
}
|
||||
manifest_path = args.output / "manifest.json"
|
||||
with manifest_path.open("w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
print(json.dumps({"manifest": str(manifest_path), "sources": len(collected)}, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user