forked from linkong/planet
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f14ff6ec0f | ||
|
|
39854b9983 | ||
|
|
3b4347c87d | ||
|
|
d9efd98d26 |
No files matched your search
@@ -2,9 +2,14 @@
|
||||
|
||||
!pyproject.toml
|
||||
!uv.lock
|
||||
!VERSION
|
||||
!backend/
|
||||
!backend/**
|
||||
!aiprovider/
|
||||
!aiprovider/**
|
||||
|
||||
backend/.env
|
||||
backend/.env.*
|
||||
aiprovider/.env
|
||||
aiprovider/.env.*
|
||||
!aiprovider/.env.example
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
REGISTRY: gitea.rclaw.top
|
||||
IMAGE_NAMESPACE: linkong/planet
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install uv
|
||||
run: curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
- name: Sync Python dependencies
|
||||
run: ~/.local/bin/uv sync --group dev
|
||||
- name: Run backend smoke tests
|
||||
working-directory: backend
|
||||
run: PYTHONPATH=. "$GITHUB_WORKSPACE/.venv/bin/python" -m pytest -s tests/test_api.py tests/test_realtime_sources.py -q
|
||||
|
||||
frontend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Bun
|
||||
run: curl -fsSL https://bun.sh/install | bash
|
||||
- name: Build frontend
|
||||
working-directory: frontend
|
||||
run: |
|
||||
~/.bun/bin/bun install --frozen-lockfile
|
||||
~/.bun/bin/bun run build
|
||||
|
||||
delivery:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- backend
|
||||
- frontend
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Helm
|
||||
run: |
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
curl -fsSL https://get.helm.sh/helm-v3.15.4-linux-amd64.tar.gz -o /tmp/helm.tar.gz
|
||||
tar -xzf /tmp/helm.tar.gz -C /tmp
|
||||
mv /tmp/linux-amd64/helm "$HOME/.local/bin/helm"
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
- name: Docker build smoke
|
||||
run: |
|
||||
docker build -t "$REGISTRY/$IMAGE_NAMESPACE/frontend:${GITHUB_SHA}" ./frontend
|
||||
docker build -t "$REGISTRY/$IMAGE_NAMESPACE/backend:${GITHUB_SHA}" -f backend/Dockerfile .
|
||||
docker build -t "$REGISTRY/$IMAGE_NAMESPACE/aiprovider:${GITHUB_SHA}" -f aiprovider/Dockerfile .
|
||||
- name: Helm template smoke
|
||||
run: |
|
||||
helm lint deploy/helm/planet
|
||||
helm template planet-staging deploy/helm/planet \
|
||||
--namespace planet-staging \
|
||||
-f deploy/helm/planet/values.single-node.yaml \
|
||||
--set image.tag="${GITHUB_SHA}" >/tmp/planet-rendered.yaml
|
||||
@@ -0,0 +1,67 @@
|
||||
name: deploy-staging
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
env:
|
||||
REGISTRY: gitea.rclaw.top
|
||||
IMAGE_NAMESPACE: linkong/planet
|
||||
RELEASE_NAME: planet-staging
|
||||
NAMESPACE: planet-staging
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install deploy tools
|
||||
run: |
|
||||
mkdir -p "$HOME/.local/bin"
|
||||
curl -fsSL https://get.helm.sh/helm-v3.15.4-linux-amd64.tar.gz -o /tmp/helm.tar.gz
|
||||
tar -xzf /tmp/helm.tar.gz -C /tmp
|
||||
mv /tmp/linux-amd64/helm "$HOME/.local/bin/helm"
|
||||
curl -fsSL https://dl.k8s.io/release/v1.30.5/bin/linux/amd64/kubectl -o /tmp/kubectl
|
||||
install -m 0755 /tmp/kubectl "$HOME/.local/bin/kubectl"
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
- name: Configure kubeconfig
|
||||
run: |
|
||||
mkdir -p "$HOME/.kube"
|
||||
printf "%s" "${{ secrets.KUBE_CONFIG_STAGING }}" | base64 -d > "$HOME/.kube/config"
|
||||
chmod 600 "$HOME/.kube/config"
|
||||
- name: Deploy Helm release
|
||||
run: |
|
||||
kubectl create namespace "$NAMESPACE" --dry-run=client -o yaml | kubectl apply -f -
|
||||
helm upgrade --install "$RELEASE_NAME" deploy/helm/planet \
|
||||
--namespace "$NAMESPACE" \
|
||||
-f deploy/helm/planet/values.single-node.yaml \
|
||||
--set global.imageRegistry="$REGISTRY" \
|
||||
--set global.imageNamespace="$IMAGE_NAMESPACE" \
|
||||
--set image.tag="${GITHUB_SHA}"
|
||||
- name: Wait for rollout
|
||||
run: |
|
||||
kubectl rollout status deployment/planet-frontend -n "$NAMESPACE" --timeout=180s
|
||||
kubectl rollout status deployment/planet-backend -n "$NAMESPACE" --timeout=180s
|
||||
kubectl rollout status deployment/planet-aiprovider -n "$NAMESPACE" --timeout=180s
|
||||
- name: Smoke test services
|
||||
run: |
|
||||
kubectl run planet-smoke-${GITHUB_RUN_NUMBER} \
|
||||
--rm -i --restart=Never \
|
||||
--namespace "$NAMESPACE" \
|
||||
--image=curlimages/curl:8.11.1 \
|
||||
--command -- sh -c '
|
||||
set -eu
|
||||
curl -fsS http://planet-frontend:3000/ >/dev/null
|
||||
curl -fsS http://planet-frontend:3000/health >/dev/null
|
||||
curl -fsS http://planet-frontend:3000/api/health >/dev/null
|
||||
curl -fsS http://planet-backend:8000/health >/dev/null
|
||||
curl -fsS http://planet-aiprovider:8010/health >/dev/null
|
||||
'
|
||||
- name: Collect diagnostics on failure
|
||||
if: failure()
|
||||
run: |
|
||||
kubectl get all -n "$NAMESPACE" -o wide || true
|
||||
kubectl describe pods -n "$NAMESPACE" || true
|
||||
kubectl logs -n "$NAMESPACE" -l app.kubernetes.io/instance="$RELEASE_NAME" --all-containers --tail=200 || true
|
||||
@@ -0,0 +1,58 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: gitea.rclaw.top
|
||||
IMAGE_NAMESPACE: linkong/planet
|
||||
|
||||
jobs:
|
||||
images:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Resolve image tags
|
||||
id: meta
|
||||
run: |
|
||||
echo "sha_tag=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
if printf "%s" "${GITHUB_REF}" | grep -q '^refs/tags/v'; then
|
||||
echo "release_tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "release_tag=" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Login to registry
|
||||
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "$REGISTRY" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
|
||||
- name: Build and push images
|
||||
run: |
|
||||
for service in frontend backend aiprovider; do
|
||||
case "$service" in
|
||||
frontend)
|
||||
dockerfile="./frontend/Dockerfile"
|
||||
context="./frontend"
|
||||
;;
|
||||
backend)
|
||||
dockerfile="backend/Dockerfile"
|
||||
context="."
|
||||
;;
|
||||
aiprovider)
|
||||
dockerfile="aiprovider/Dockerfile"
|
||||
context="."
|
||||
;;
|
||||
esac
|
||||
|
||||
image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.sha_tag }}"
|
||||
docker build -t "$image" -f "$dockerfile" "$context"
|
||||
docker push "$image"
|
||||
|
||||
if [ -n "${{ steps.meta.outputs.release_tag }}" ]; then
|
||||
release_image="$REGISTRY/$IMAGE_NAMESPACE/$service:${{ steps.meta.outputs.release_tag }}"
|
||||
docker tag "$image" "$release_image"
|
||||
docker push "$release_image"
|
||||
fi
|
||||
done
|
||||
@@ -365,7 +365,7 @@ DATABASE_RETRY_INTERVAL=10 \
|
||||
- `AI_PROVIDER_START_MAX_RETRIES` / `AI_PROVIDER_RETRY_INTERVAL`: 控制 `aiprovider` 的构建/启动与容器重启自愈,默认 `3` 次、`5` 秒
|
||||
- `BACKEND_MAX_RETRIES`: 控制后端进程启动重试次数,默认 `3`
|
||||
- `FRONTEND_MAX_RETRIES`: 控制前端 dev server 启动重试次数,默认 `3`
|
||||
- `BACKEND_HEALTH_CHECK_ATTEMPTS` / `BACKEND_HEALTH_CHECK_INTERVAL`: 控制后端 HTTP 健康检查等待次数与间隔,默认 `10` 次、`2` 秒
|
||||
- `BACKEND_HEALTH_CHECK_ATTEMPTS` / `BACKEND_HEALTH_CHECK_INTERVAL`: 控制后端 HTTP 健康检查等待次数与间隔,默认 `60` 次、`2` 秒
|
||||
- `FRONTEND_HEALTH_CHECK_ATTEMPTS` / `FRONTEND_HEALTH_CHECK_INTERVAL`: 控制前端 HTTP 可访问检查等待次数与间隔,默认 `10` 次、`2` 秒
|
||||
- `AI_PROVIDER_HEALTH_CHECK_ATTEMPTS` / `AI_PROVIDER_HEALTH_CHECK_INTERVAL`: 控制 `aiprovider` HTTP 健康检查等待次数与间隔,默认 `10` 次、`2` 秒
|
||||
|
||||
|
||||
@@ -1,45 +1,71 @@
|
||||
# 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
|
||||
|
||||
- [ ] High-precision country boundaries: implement the source-faithful static vector tile pipeline described in [Earth High Precision Boundary Tiles Plan](/home/ray/dev/linkong/planet/docs/plans/earth-high-precision-boundary-tiles-plan.md). Highest zoom must preserve trusted source geometry instead of smoothing or hand-drawing borders.
|
||||
- [ ] 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, and the official dashed maritime claim line before implementing visual changes.
|
||||
- [ ] 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.
|
||||
@@ -27,4 +27,7 @@ COPY aiprovider /app/aiprovider
|
||||
|
||||
EXPOSE 8010
|
||||
|
||||
CMD ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "uvicorn", "aiprovider.main:app", "--host", "0.0.0.0", "--port", "8010", "--reload"]
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD curl -fsS http://127.0.0.1:8010/health >/dev/null || exit 1
|
||||
|
||||
CMD ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "uvicorn", "aiprovider.main:app", "--host", "0.0.0.0", "--port", "8010"]
|
||||
+5
-1
@@ -12,6 +12,7 @@ ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV UV_COMPILE_BYTECODE=1
|
||||
ENV UV_LINK_MODE=copy
|
||||
ENV PYTHONPATH=/app/backend
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
curl \
|
||||
@@ -25,4 +26,7 @@ COPY VERSION /app/VERSION
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD curl -fsS http://127.0.0.1:8000/health >/dev/null || exit 1
|
||||
|
||||
CMD ["uv", "run", "--frozen", "--no-dev", "--project", "/app", "python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -18,6 +18,7 @@ from app.api.v1 import (
|
||||
vessels,
|
||||
bgp,
|
||||
news,
|
||||
realtime_sources,
|
||||
system_control,
|
||||
tv,
|
||||
)
|
||||
@@ -50,3 +51,4 @@ api_router.include_router(vessels.router, prefix="/vessels", tags=["vessels"])
|
||||
api_router.include_router(bgp.router, prefix="/bgp", tags=["bgp"])
|
||||
api_router.include_router(tv.router, prefix="/tv", tags=["tv"])
|
||||
api_router.include_router(news.router, prefix="/news", tags=["news"])
|
||||
api_router.include_router(realtime_sources.router, prefix="/realtime-sources", tags=["realtime-sources"])
|
||||
@@ -18,6 +18,8 @@ from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.task import CollectionTask
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISRawObservation
|
||||
from app.services.vessel_ais_aggregation import VESSEL_AIS_SCHEMA
|
||||
from app.services.scheduler import (
|
||||
cancel_running_collector_now,
|
||||
get_latest_task_id_for_datasource,
|
||||
@@ -161,7 +163,26 @@ async def _load_collected_record_counts(
|
||||
.where(CollectedData.is_current.is_(True))
|
||||
.group_by(CollectedData.source)
|
||||
)
|
||||
return {source: int(count or 0) for source, count in result.all()}
|
||||
counts = {source: int(count or 0) for source, count in result.all()}
|
||||
|
||||
vessel_sources = [
|
||||
source
|
||||
for source in sources
|
||||
if datasource_metadata(source)["credential_provider"] in {"aisstream", "barentswatch"}
|
||||
or "vessel" in source
|
||||
or "ais" in source
|
||||
]
|
||||
if vessel_sources:
|
||||
raw_result = await db.execute(
|
||||
select(AISRawObservation.source, func.count(AISRawObservation.id))
|
||||
.where(AISRawObservation.target_schema == VESSEL_AIS_SCHEMA)
|
||||
.where(AISRawObservation.source.in_(vessel_sources))
|
||||
.group_by(AISRawObservation.source)
|
||||
)
|
||||
for source, count in raw_result.all():
|
||||
counts[source] = max(counts.get(source, 0), int(count or 0))
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
async def _load_datasource_endpoint_overrides(
|
||||
|
||||
@@ -117,7 +117,7 @@ async def get_vessel_layer_snapshot(
|
||||
bbox=parsed_bbox,
|
||||
zoom=zoom,
|
||||
limit=limit,
|
||||
vessel_type=vessel_type,
|
||||
type_filter=vessel_type,
|
||||
since_minutes=since_minutes,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
"""Realtime datasource operations and runtime statistics."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import distinct, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.data_sources import get_data_sources_config
|
||||
from app.core.security import get_current_user
|
||||
from app.core.time import to_iso8601_utc
|
||||
from app.db.session import get_db
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.user import User
|
||||
from app.models.vessel import AISRawObservation, AISSourceHealth
|
||||
from app.services.custom_datasource_runtime import (
|
||||
get_custom_stream_status,
|
||||
start_custom_stream,
|
||||
stop_custom_stream,
|
||||
)
|
||||
from app.services.scheduler import (
|
||||
cancel_running_collector_now,
|
||||
is_collector_running,
|
||||
run_collector_now,
|
||||
)
|
||||
from app.services.vessel_ais_aggregation import VESSEL_AIS_SCHEMA, update_ais_source_health
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
BUILTIN_REALTIME_SOURCES = {"aisstream_vessels"}
|
||||
REALTIME_SOURCE_TYPES = {"websocket", "ws"}
|
||||
|
||||
|
||||
def _is_realtime_config(config: DataSourceConfig) -> bool:
|
||||
return str(config.source_type or "").lower() in REALTIME_SOURCE_TYPES
|
||||
|
||||
|
||||
def _safe_config_dict(value: Any) -> dict[str, Any]:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _credential_configured(config: DataSourceConfig | None) -> bool:
|
||||
if config is not None:
|
||||
auth_config = _safe_config_dict(config.auth_config)
|
||||
config_payload = _safe_config_dict(config.config)
|
||||
if auth_config.get("api_key") or config_payload.get("api_key"):
|
||||
return True
|
||||
return bool(os.getenv("AISSTREAM_API_KEY"))
|
||||
|
||||
|
||||
async def _load_realtime_stats(db: AsyncSession, source: str) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
observed_24h = now - timedelta(hours=24)
|
||||
observed_1h = now - timedelta(hours=1)
|
||||
payload_mmsi = AISRawObservation.entity_key
|
||||
|
||||
result = await db.execute(
|
||||
select(
|
||||
func.count(AISRawObservation.id).label("total_observations"),
|
||||
func.count(AISRawObservation.id)
|
||||
.filter(AISRawObservation.observed_at >= observed_24h)
|
||||
.label("observations_24h"),
|
||||
func.count(AISRawObservation.id)
|
||||
.filter(AISRawObservation.observed_at >= observed_1h)
|
||||
.label("observations_1h"),
|
||||
func.count(distinct(payload_mmsi)).label("unique_mmsi_total"),
|
||||
func.count(distinct(payload_mmsi))
|
||||
.filter(AISRawObservation.observed_at >= observed_24h)
|
||||
.label("unique_mmsi_24h"),
|
||||
func.max(AISRawObservation.observed_at).label("latest_observed_at"),
|
||||
func.max(AISRawObservation.collected_at).label("latest_collected_at"),
|
||||
)
|
||||
.where(AISRawObservation.target_schema == VESSEL_AIS_SCHEMA)
|
||||
.where(AISRawObservation.source == source)
|
||||
)
|
||||
row = result.mappings().one()
|
||||
return {
|
||||
"total_observations": int(row["total_observations"] or 0),
|
||||
"observations_24h": int(row["observations_24h"] or 0),
|
||||
"observations_1h": int(row["observations_1h"] or 0),
|
||||
"unique_mmsi_total": int(row["unique_mmsi_total"] or 0),
|
||||
"unique_mmsi_24h": int(row["unique_mmsi_24h"] or 0),
|
||||
"latest_observed_at": to_iso8601_utc(row["latest_observed_at"]),
|
||||
"latest_collected_at": to_iso8601_utc(row["latest_collected_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _runtime_status_for_builtin(source: str) -> dict[str, Any]:
|
||||
running = is_collector_running(source)
|
||||
return {
|
||||
"running": running,
|
||||
"done": False,
|
||||
"runtime": "collector",
|
||||
}
|
||||
|
||||
|
||||
def _runtime_status_for_custom(config_id: int) -> dict[str, Any]:
|
||||
status = get_custom_stream_status(config_id)
|
||||
return {
|
||||
"running": bool(status.get("running")),
|
||||
"done": bool(status.get("done")),
|
||||
"runtime": "custom_stream",
|
||||
}
|
||||
|
||||
|
||||
async def _serialize_builtin_aisstream(
|
||||
db: AsyncSession,
|
||||
datasource: DataSource,
|
||||
config: DataSourceConfig | None,
|
||||
) -> dict[str, Any]:
|
||||
health = await db.get(AISSourceHealth, datasource.source)
|
||||
config_payload = _safe_config_dict(config.config if config else {})
|
||||
endpoint = (
|
||||
(config.endpoint if config else None)
|
||||
or get_data_sources_config().get_yaml_url(datasource.source)
|
||||
)
|
||||
return {
|
||||
"source": datasource.source,
|
||||
"name": datasource.name,
|
||||
"display_name": "AISStream 实时船舶",
|
||||
"kind": "builtin",
|
||||
"source_type": "websocket",
|
||||
"endpoint": endpoint,
|
||||
"is_active": bool(datasource.is_active),
|
||||
"credential_configured": _credential_configured(config),
|
||||
"message_types": config_payload.get("message_types") or ["PositionReport", "ShipStaticData"],
|
||||
"bounding_boxes": config_payload.get("bounding_boxes") or [[[-90, -180], [90, 180]]],
|
||||
"config": config_payload,
|
||||
"runtime": _runtime_status_for_builtin(datasource.source),
|
||||
"health": health.to_dict() if health else None,
|
||||
"stats": await _load_realtime_stats(db, datasource.source),
|
||||
}
|
||||
|
||||
|
||||
async def _serialize_custom_stream(
|
||||
db: AsyncSession,
|
||||
config: DataSourceConfig,
|
||||
) -> dict[str, Any]:
|
||||
health = await db.get(AISSourceHealth, config.name)
|
||||
config_payload = _safe_config_dict(config.config)
|
||||
return {
|
||||
"source": config.name,
|
||||
"name": config.name,
|
||||
"display_name": config.description or config.name,
|
||||
"kind": "custom",
|
||||
"config_id": config.id,
|
||||
"source_type": config.source_type,
|
||||
"endpoint": config.endpoint,
|
||||
"is_active": bool(config.is_active),
|
||||
"credential_configured": config.auth_type == "none" or bool(_safe_config_dict(config.auth_config)),
|
||||
"message_types": config_payload.get("message_types") or [],
|
||||
"bounding_boxes": config_payload.get("bounding_boxes") or [],
|
||||
"config": config_payload,
|
||||
"runtime": _runtime_status_for_custom(config.id),
|
||||
"health": health.to_dict() if health else None,
|
||||
"stats": await _load_realtime_stats(db, config.name),
|
||||
}
|
||||
|
||||
|
||||
async def _load_builtin_aisstream(db: AsyncSession) -> tuple[DataSource | None, DataSourceConfig | None]:
|
||||
result = await db.execute(select(DataSource).where(DataSource.source == "aisstream_vessels"))
|
||||
datasource = result.scalar_one_or_none()
|
||||
config_result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == "aisstream_vessels")
|
||||
.where(DataSourceConfig.is_active.is_(True))
|
||||
.order_by(DataSourceConfig.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return datasource, config_result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def _load_custom_realtime_config(db: AsyncSession, source: str) -> DataSourceConfig | None:
|
||||
result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(DataSourceConfig.name == source)
|
||||
.order_by(DataSourceConfig.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
config = result.scalar_one_or_none()
|
||||
return config if config is not None and _is_realtime_config(config) else None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_realtime_sources(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
sources: list[dict[str, Any]] = []
|
||||
datasource, builtin_config = await _load_builtin_aisstream(db)
|
||||
if datasource is not None:
|
||||
sources.append(await _serialize_builtin_aisstream(db, datasource, builtin_config))
|
||||
|
||||
custom_result = await db.execute(
|
||||
select(DataSourceConfig)
|
||||
.where(func.lower(DataSourceConfig.source_type).in_(REALTIME_SOURCE_TYPES))
|
||||
.order_by(DataSourceConfig.name)
|
||||
)
|
||||
for config in custom_result.scalars().all():
|
||||
if config.name in BUILTIN_REALTIME_SOURCES:
|
||||
continue
|
||||
sources.append(await _serialize_custom_stream(db, config))
|
||||
|
||||
return {"total": len(sources), "data": sources}
|
||||
|
||||
|
||||
async def _ensure_builtin_startable(db: AsyncSession) -> DataSourceConfig | None:
|
||||
datasource, config = await _load_builtin_aisstream(db)
|
||||
if datasource is None:
|
||||
raise HTTPException(status_code=404, detail="Realtime source not found")
|
||||
if not datasource.is_active:
|
||||
raise HTTPException(status_code=400, detail="Realtime source is disabled")
|
||||
if not _credential_configured(config):
|
||||
raise HTTPException(status_code=400, detail="AISStream API key is not configured")
|
||||
return config
|
||||
|
||||
|
||||
@router.post("/{source}/start")
|
||||
async def start_realtime_source(
|
||||
source: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
if source == "aisstream_vessels":
|
||||
await _ensure_builtin_startable(db)
|
||||
if is_collector_running(source):
|
||||
return {"status": "already_running", "source": source, "runtime": _runtime_status_for_builtin(source)}
|
||||
if not run_collector_now(source):
|
||||
raise HTTPException(status_code=409, detail="Realtime source could not be started")
|
||||
return {"status": "started", "source": source, "runtime": _runtime_status_for_builtin(source)}
|
||||
|
||||
config = await _load_custom_realtime_config(db, source)
|
||||
if config is None:
|
||||
raise HTTPException(status_code=404, detail="Realtime source not found")
|
||||
if not config.is_active:
|
||||
raise HTTPException(status_code=400, detail="Realtime source is disabled")
|
||||
started = start_custom_stream(config.id)
|
||||
return {
|
||||
"status": "started" if started else "already_running",
|
||||
"source": source,
|
||||
"runtime": _runtime_status_for_custom(config.id),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source}/stop")
|
||||
async def stop_realtime_source(
|
||||
source: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
if source == "aisstream_vessels":
|
||||
stopped = await cancel_running_collector_now(source)
|
||||
await update_ais_source_health(db, source=source, connection_state="disconnected", last_error=None)
|
||||
await db.commit()
|
||||
return {"status": "stopped" if stopped else "not_running", "source": source, "runtime": _runtime_status_for_builtin(source)}
|
||||
|
||||
config = await _load_custom_realtime_config(db, source)
|
||||
if config is None:
|
||||
raise HTTPException(status_code=404, detail="Realtime source not found")
|
||||
stopped = await stop_custom_stream(config.id)
|
||||
await update_ais_source_health(db, source=source, connection_state="disconnected", last_error=None)
|
||||
await db.commit()
|
||||
return {
|
||||
"status": "stopped" if stopped else "not_running",
|
||||
"source": source,
|
||||
"runtime": _runtime_status_for_custom(config.id),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source}/restart")
|
||||
async def restart_realtime_source(
|
||||
source: str,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
await stop_realtime_source(source, current_user=current_user, db=db)
|
||||
return await start_realtime_source(source, current_user=current_user, db=db)
|
||||
@@ -68,6 +68,7 @@ TERRAIN_TILE_BATCH_MAX_ITEMS = 128
|
||||
TERRAIN_TILE_BATCH_CONCURRENCY = 16
|
||||
_terrain_tile_cache: OrderedDict[tuple[int, int, int], tuple[bytes, str, dict[str, str]]] = OrderedDict()
|
||||
VESSEL_NAME_FALLBACK_PATTERN = re.compile(r"^mmsi\s*\d+$", re.IGNORECASE)
|
||||
VESSEL_SNAPSHOT_LEGACY_FALLBACK_ENABLED = True
|
||||
|
||||
|
||||
class TerrariumTileRequest(BaseModel):
|
||||
@@ -941,6 +942,39 @@ def _merge_vessel_features(
|
||||
}
|
||||
|
||||
|
||||
async def _load_legacy_vessel_snapshot_features(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
bbox: tuple[float, float, float, float] | None,
|
||||
limit: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
latest_positions = select(
|
||||
VesselPosition.mmsi.label("mmsi"),
|
||||
func.max(VesselPosition.received_at).label("received_at"),
|
||||
)
|
||||
if bbox is not None:
|
||||
lon_min, lat_min, lon_max, lat_max = bbox
|
||||
latest_positions = latest_positions.where(VesselPosition.lon >= lon_min)
|
||||
latest_positions = latest_positions.where(VesselPosition.lon <= lon_max)
|
||||
latest_positions = latest_positions.where(VesselPosition.lat >= lat_min)
|
||||
latest_positions = latest_positions.where(VesselPosition.lat <= lat_max)
|
||||
|
||||
latest_positions = latest_positions.group_by(VesselPosition.mmsi).subquery()
|
||||
result = await db.execute(
|
||||
select(VesselPosition, VesselStatic)
|
||||
.join(
|
||||
latest_positions,
|
||||
(VesselPosition.mmsi == latest_positions.c.mmsi)
|
||||
& (VesselPosition.received_at == latest_positions.c.received_at),
|
||||
)
|
||||
.outerjoin(VesselStatic, VesselStatic.mmsi == VesselPosition.mmsi)
|
||||
.order_by(VesselPosition.received_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
legacy_geojson = convert_vessels_to_geojson(list(result.all()))
|
||||
return legacy_geojson.get("features", [])[:limit]
|
||||
|
||||
|
||||
def _build_vessel_stats(features: List[dict[str, Any]]) -> dict[str, Any]:
|
||||
by_type: dict[str, int] = {}
|
||||
underway = 0
|
||||
@@ -2073,33 +2107,6 @@ async def _load_compute_center_record(db: AsyncSession, source_id: str) -> Colle
|
||||
return result.scalars().first()
|
||||
|
||||
|
||||
@router.get("/geo/vessels")
|
||||
async def get_vessels_geojson(
|
||||
bbox: Optional[str] = Query(
|
||||
None,
|
||||
description="Viewport bbox as lon_min,lat_min,lon_max,lat_max",
|
||||
),
|
||||
type: Optional[str] = Query(
|
||||
None,
|
||||
description="Comma-separated vessel types: cargo,tanker,passenger,fishing,military,other",
|
||||
),
|
||||
limit: Optional[int] = Query(
|
||||
None,
|
||||
ge=0,
|
||||
description="Maximum vessel features to return. Omit or pass 0 for no limit.",
|
||||
),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Legacy vessel endpoint removed in favor of /api/v1/vessels/snapshot."""
|
||||
raise HTTPException(
|
||||
status_code=410,
|
||||
detail=(
|
||||
"Legacy vessel GeoJSON endpoint has been removed. "
|
||||
"Use /api/v1/vessels/snapshot with bbox, zoom, and limit."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
async def _load_raw_vessel_snapshot_features(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
@@ -2121,18 +2128,38 @@ async def _load_raw_vessel_snapshot_features(
|
||||
observed_since=observed_since,
|
||||
)
|
||||
raw_geojson = convert_aggregated_vessels_to_geojson(aggregated_vessels)
|
||||
features = raw_geojson.get("features", [])
|
||||
raw_features = raw_geojson.get("features", [])
|
||||
features = raw_features
|
||||
legacy_features: list[dict[str, Any]] = []
|
||||
legacy_fallback_used = False
|
||||
if not raw_features and VESSEL_SNAPSHOT_LEGACY_FALLBACK_ENABLED:
|
||||
legacy_features = await _load_legacy_vessel_snapshot_features(
|
||||
db,
|
||||
bbox=bbox,
|
||||
limit=limit,
|
||||
)
|
||||
features, _merge_diagnostics = _merge_vessel_features(raw_features, legacy_features)
|
||||
legacy_fallback_used = bool(legacy_features)
|
||||
|
||||
return features, {
|
||||
"raw_feature_count": len(features),
|
||||
"raw_feature_count": len(raw_features),
|
||||
"raw_unique_mmsi": len(
|
||||
{
|
||||
key
|
||||
for key in (_feature_mmsi_key(feature) for feature in features)
|
||||
for key in (_feature_mmsi_key(feature) for feature in raw_features)
|
||||
if key is not None
|
||||
}
|
||||
),
|
||||
"legacy_feature_count": 0,
|
||||
"legacy_backfilled_mmsi": 0,
|
||||
"legacy_feature_count": len(legacy_features),
|
||||
"legacy_backfilled_mmsi": len(
|
||||
{
|
||||
key
|
||||
for key in (_feature_mmsi_key(feature) for feature in legacy_features)
|
||||
if key is not None
|
||||
}
|
||||
),
|
||||
"legacy_fallback_enabled": VESSEL_SNAPSHOT_LEGACY_FALLBACK_ENABLED,
|
||||
"legacy_fallback_used": legacy_fallback_used,
|
||||
"final_unique_mmsi": len(
|
||||
{
|
||||
key
|
||||
@@ -2466,7 +2493,12 @@ async def get_visualization_geo_summary(db: AsyncSession = Depends(get_db)):
|
||||
select(func.count(func.distinct(VesselPosition.mmsi)))
|
||||
)
|
||||
legacy_unique_mmsi = int(legacy_unique_result.scalar() or 0)
|
||||
vessel_count = max(raw_unique_mmsi, legacy_unique_mmsi)
|
||||
legacy_fallback_active = (
|
||||
VESSEL_SNAPSHOT_LEGACY_FALLBACK_ENABLED
|
||||
and raw_unique_mmsi == 0
|
||||
and legacy_unique_mmsi > 0
|
||||
)
|
||||
vessel_count = legacy_unique_mmsi if legacy_fallback_active else raw_unique_mmsi
|
||||
aisstream_health = await db.get(AISSourceHealth, "aisstream_vessels")
|
||||
|
||||
return {
|
||||
@@ -2477,6 +2509,8 @@ async def get_visualization_geo_summary(db: AsyncSession = Depends(get_db)):
|
||||
"satellite_count": satellite_count,
|
||||
"compute_center_count": compute_center_count,
|
||||
"vessel_count": vessel_count,
|
||||
"vessel_count_source": "legacy_fallback" if legacy_fallback_active else "raw_recent",
|
||||
"vessel_legacy_fallback_enabled": VESSEL_SNAPSHOT_LEGACY_FALLBACK_ENABLED,
|
||||
"vessel_raw_unique_mmsi": raw_unique_mmsi,
|
||||
"vessel_raw_unique_window_hours": raw_unique_window_hours,
|
||||
"vessel_legacy_unique_mmsi": legacy_unique_mmsi,
|
||||
|
||||
@@ -374,6 +374,11 @@ def run_collector_now(collector_name: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def is_collector_running(collector_name: str) -> bool:
|
||||
task = get_running_collector_task(collector_name)
|
||||
return bool(task is not None and not task.done())
|
||||
|
||||
|
||||
async def cancel_running_collector_now(collector_name: str) -> bool:
|
||||
task = get_running_collector_task(collector_name)
|
||||
if task is None or task.done():
|
||||
|
||||
+47
-11
@@ -18,6 +18,17 @@ from app.schemas.ai import (
|
||||
)
|
||||
|
||||
|
||||
class _FakeRedisClient:
|
||||
def sismember(self, *_args, **_kwargs):
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_token_blacklist(monkeypatch):
|
||||
"""Keep API auth tests independent from an external Redis service."""
|
||||
monkeypatch.setattr("app.core.security.redis_client", _FakeRedisClient())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_headers():
|
||||
"""Create authentication headers"""
|
||||
@@ -62,20 +73,43 @@ async def test_dashboard_stats_without_auth():
|
||||
@pytest.mark.asyncio
|
||||
async def test_dashboard_stats_with_auth(auth_headers):
|
||||
"""Test dashboard stats with authentication"""
|
||||
with patch("app.api.v1.dashboard.cache.get", return_value=None):
|
||||
with patch("app.api.v1.dashboard.cache.set", return_value=True):
|
||||
with patch("app.db.session.get_db") as mock_get_db:
|
||||
mock_session = AsyncMock()
|
||||
mock_result = AsyncMock()
|
||||
mock_result.scalar.return_value = 0
|
||||
mock_result.fetchall.return_value = []
|
||||
mock_session.execute.return_value = mock_result
|
||||
class _StatsResult:
|
||||
def __init__(self, row):
|
||||
self._row = row
|
||||
|
||||
async def mock_db_context():
|
||||
yield mock_session
|
||||
def one(self):
|
||||
return self._row
|
||||
|
||||
mock_get_db.return_value = mock_db_context()
|
||||
class _FakeStatsSession:
|
||||
def __init__(self):
|
||||
self._rows = [
|
||||
type("DatasourceStats", (), {"custom_count": 0, "custom_active": 0})(),
|
||||
type("TaskStats", (), {"tasks_today": 0, "success_tasks": 0})(),
|
||||
type(
|
||||
"AlertStats",
|
||||
(),
|
||||
{"critical_alerts": 0, "warning_alerts": 0, "info_alerts": 0},
|
||||
)(),
|
||||
]
|
||||
|
||||
async def execute(self, _query):
|
||||
return _StatsResult(self._rows.pop(0))
|
||||
|
||||
def override_get_current_user():
|
||||
return User(id=1, username="testuser", email="test@example.com", role="admin", is_active=True)
|
||||
|
||||
async def override_get_db():
|
||||
yield _FakeStatsSession()
|
||||
|
||||
app.dependency_overrides.update(
|
||||
{
|
||||
__import__("app.core.security", fromlist=["get_current_user"]).get_current_user: override_get_current_user,
|
||||
get_db: override_get_db,
|
||||
}
|
||||
)
|
||||
try:
|
||||
with patch("app.api.v1.dashboard.cache.get", return_value=None):
|
||||
with patch("app.api.v1.dashboard.cache.set", return_value=True):
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get(
|
||||
@@ -85,6 +119,8 @@ async def test_dashboard_stats_with_auth(auth_headers):
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "total_datasources" in data
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from fastapi import HTTPException
|
||||
import pytest
|
||||
|
||||
from app.api.v1 import layers
|
||||
|
||||
@@ -42,3 +43,28 @@ def test_layer_guard_filters_bbox_and_clamps_low_zoom_limit():
|
||||
assert result["diagnostics"]["limit"] == layers.LOW_ZOOM_FEATURE_LIMIT
|
||||
assert result["diagnostics"]["limit_clamped"] is True
|
||||
assert result["diagnostics"]["degraded"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_vessel_layer_snapshot_passes_type_filter(monkeypatch):
|
||||
captured = {}
|
||||
|
||||
async def fake_build_vessel_snapshot_response(db, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return {"type": "FeatureCollection", "features": []}
|
||||
|
||||
monkeypatch.setattr(layers, "build_vessel_snapshot_response", fake_build_vessel_snapshot_response)
|
||||
|
||||
result = await layers.get_vessel_layer_snapshot(
|
||||
bbox="10,59,11,60",
|
||||
zoom=12,
|
||||
limit=1000,
|
||||
vessel_type="cargo",
|
||||
since_minutes=30,
|
||||
db=object(),
|
||||
)
|
||||
|
||||
assert result["features"] == []
|
||||
assert captured["bbox"] == (10.0, 59.0, 11.0, 60.0)
|
||||
assert captured["type_filter"] == "cargo"
|
||||
assert "vessel_type" not in captured
|
||||
@@ -0,0 +1,101 @@
|
||||
from datetime import UTC, datetime
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from app.api.v1 import realtime_sources
|
||||
from app.models.datasource import DataSource
|
||||
from app.models.datasource_config import DataSourceConfig
|
||||
from app.models.vessel import AISSourceHealth
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_serialize_builtin_aisstream_includes_health_config_and_stats(monkeypatch):
|
||||
datasource = DataSource(
|
||||
id=28,
|
||||
name="AISStream Vessels",
|
||||
source="aisstream_vessels",
|
||||
module="L4",
|
||||
priority="P1",
|
||||
collector_class="aisstream_vessels",
|
||||
is_active=True,
|
||||
)
|
||||
config = DataSourceConfig(
|
||||
id=3,
|
||||
name="aisstream_vessels",
|
||||
source_type="websocket",
|
||||
endpoint="wss://stream.aisstream.io/v0/stream",
|
||||
auth_type="api_key",
|
||||
auth_config={"api_key": "test-key"},
|
||||
config={
|
||||
"message_types": ["PositionReport"],
|
||||
"bounding_boxes": [[[-10, 50], [35, 75]]],
|
||||
},
|
||||
is_active=True,
|
||||
)
|
||||
health = AISSourceHealth(
|
||||
source="aisstream_vessels",
|
||||
connection_state="connected",
|
||||
last_seen_at=datetime(2026, 5, 13, 1, 0, tzinfo=UTC),
|
||||
)
|
||||
|
||||
class _Session:
|
||||
async def get(self, _model, key):
|
||||
assert key == "aisstream_vessels"
|
||||
return health
|
||||
|
||||
monkeypatch.setattr(
|
||||
realtime_sources,
|
||||
"_load_realtime_stats",
|
||||
AsyncMock(
|
||||
return_value={
|
||||
"total_observations": 10,
|
||||
"observations_24h": 4,
|
||||
"observations_1h": 1,
|
||||
"unique_mmsi_total": 8,
|
||||
"unique_mmsi_24h": 3,
|
||||
"latest_observed_at": "2026-05-13T01:00:00Z",
|
||||
"latest_collected_at": "2026-05-13T01:00:01Z",
|
||||
}
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(realtime_sources, "is_collector_running", lambda source: False)
|
||||
|
||||
payload = await realtime_sources._serialize_builtin_aisstream(_Session(), datasource, config)
|
||||
|
||||
assert payload["source"] == "aisstream_vessels"
|
||||
assert payload["kind"] == "builtin"
|
||||
assert payload["credential_configured"] is True
|
||||
assert payload["message_types"] == ["PositionReport"]
|
||||
assert payload["runtime"]["running"] is False
|
||||
assert payload["health"]["connection_state"] == "connected"
|
||||
assert payload["stats"]["total_observations"] == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_builtin_realtime_source_rejects_disabled(monkeypatch):
|
||||
datasource = DataSource(
|
||||
id=28,
|
||||
name="AISStream Vessels",
|
||||
source="aisstream_vessels",
|
||||
module="L4",
|
||||
priority="P1",
|
||||
collector_class="aisstream_vessels",
|
||||
is_active=False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
realtime_sources,
|
||||
"_load_builtin_aisstream",
|
||||
AsyncMock(return_value=(datasource, None)),
|
||||
)
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
await realtime_sources.start_realtime_source(
|
||||
"aisstream_vessels",
|
||||
current_user=object(),
|
||||
db=object(),
|
||||
)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert "disabled" in excinfo.value.detail
|
||||
@@ -574,13 +574,12 @@ async def test_vessel_snapshot_filters_type_and_bbox(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_vessels_geojson_endpoint_is_gone():
|
||||
async def test_legacy_vessels_geojson_route_is_not_registered():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/visualization/geo/vessels")
|
||||
|
||||
assert response.status_code == 410
|
||||
assert "/api/v1/vessels/snapshot" in response.json()["detail"]
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -669,15 +668,49 @@ async def test_vessel_snapshot_filters_bbox_and_caps_limit(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_legacy_vessels_geojson_rejects_even_with_bbox():
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get(
|
||||
"/api/v1/visualization/geo/vessels",
|
||||
params={"bbox": "10,59,11,60", "type": "cargo", "limit": 1000},
|
||||
)
|
||||
async def test_vessel_snapshot_uses_legacy_fallback_when_raw_window_is_empty(monkeypatch):
|
||||
now = datetime(2026, 4, 28, 1, 0, tzinfo=timezone.utc)
|
||||
monkeypatch.setattr(
|
||||
visualization,
|
||||
"get_aggregated_vessels_snapshot",
|
||||
AsyncMock(return_value=[]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
visualization,
|
||||
"_load_legacy_vessel_snapshot_features",
|
||||
AsyncMock(
|
||||
return_value=[
|
||||
{
|
||||
"type": "Feature",
|
||||
"id": 257123000,
|
||||
"geometry": {"type": "Point", "coordinates": [10.73, 59.91]},
|
||||
"properties": {
|
||||
"mmsi": 257123000,
|
||||
"name": "OSLO TRADER",
|
||||
"vessel_type": 70,
|
||||
"vessel_type_name": "Cargo",
|
||||
"received_at": now.isoformat(),
|
||||
},
|
||||
}
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == 410
|
||||
result = await visualization.build_vessel_snapshot_response(
|
||||
object(),
|
||||
bbox=(10.0, 59.0, 11.0, 60.0),
|
||||
zoom=12,
|
||||
type_filter=None,
|
||||
limit=1000,
|
||||
since_minutes=60,
|
||||
)
|
||||
|
||||
assert result["count"] == 1
|
||||
assert result["features"][0]["properties"]["name"] == "OSLO TRADER"
|
||||
assert result["diagnostics"]["raw_feature_count"] == 0
|
||||
assert result["diagnostics"]["legacy_feature_count"] == 1
|
||||
assert result["diagnostics"]["legacy_backfilled_mmsi"] == 1
|
||||
assert result["diagnostics"]["legacy_fallback_used"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
apiVersion: v2
|
||||
name: planet
|
||||
description: Planet situational awareness platform
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "0.52.0"
|
||||
@@ -0,0 +1,33 @@
|
||||
{{- define "planet.name" -}}
|
||||
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "planet.fullname" -}}
|
||||
{{- if .Values.fullnameOverride -}}
|
||||
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
{{- $name := include "planet.name" . -}}
|
||||
{{- if contains $name .Release.Name -}}
|
||||
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- else -}}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "planet.labels" -}}
|
||||
app.kubernetes.io/name: {{ include "planet.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
|
||||
app.kubernetes.io/managed-by: {{ .Release.Service }}
|
||||
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "planet.selectorLabels" -}}
|
||||
app.kubernetes.io/name: {{ include "planet.name" . }}
|
||||
app.kubernetes.io/instance: {{ .Release.Name }}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "planet.image" -}}
|
||||
{{- printf "%s/%s/%s:%s" .root.Values.global.imageRegistry .root.Values.global.imageNamespace .repository .root.Values.image.tag -}}
|
||||
{{- end -}}
|
||||
@@ -0,0 +1,66 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-aiprovider
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: aiprovider
|
||||
spec:
|
||||
replicas: {{ .Values.aiprovider.replicaCount }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: aiprovider
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: aiprovider
|
||||
spec:
|
||||
{{- with .Values.global.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: aiprovider
|
||||
image: {{ include "planet.image" (dict "root" . "repository" .Values.aiprovider.image.repository) | quote }}
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8010
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: {{ include "planet.fullname" . }}-config
|
||||
- secretRef:
|
||||
name: {{ include "planet.fullname" . }}-secrets
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 30
|
||||
periodSeconds: 20
|
||||
resources:
|
||||
{{- toYaml .Values.aiprovider.resources | nindent 12 }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-aiprovider
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: aiprovider
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: {{ .Values.aiprovider.service.port }}
|
||||
targetPort: http
|
||||
selector:
|
||||
{{- include "planet.selectorLabels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: aiprovider
|
||||
@@ -0,0 +1,66 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-backend
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: backend
|
||||
spec:
|
||||
replicas: {{ .Values.backend.replicaCount }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: backend
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: backend
|
||||
spec:
|
||||
{{- with .Values.global.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: backend
|
||||
image: {{ include "planet.image" (dict "root" . "repository" .Values.backend.image.repository) | quote }}
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8000
|
||||
envFrom:
|
||||
- configMapRef:
|
||||
name: {{ include "planet.fullname" . }}-config
|
||||
- secretRef:
|
||||
name: {{ include "planet.fullname" . }}-secrets
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 10
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 30
|
||||
periodSeconds: 20
|
||||
resources:
|
||||
{{- toYaml .Values.backend.resources | nindent 12 }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-backend
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: backend
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: {{ .Values.backend.service.port }}
|
||||
targetPort: http
|
||||
selector:
|
||||
{{- include "planet.selectorLabels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: backend
|
||||
@@ -0,0 +1,27 @@
|
||||
{{- $postgresHost := .Values.postgresql.external.host -}}
|
||||
{{- if .Values.postgresql.internal.enabled -}}
|
||||
{{- $postgresHost = printf "%s-postgresql" (include "planet.fullname" .) -}}
|
||||
{{- end -}}
|
||||
{{- $redisHost := .Values.redis.external.host -}}
|
||||
{{- if .Values.redis.internal.enabled -}}
|
||||
{{- $redisHost = printf "%s-redis" (include "planet.fullname" .) -}}
|
||||
{{- end -}}
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-config
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
data:
|
||||
DATABASE_URL: "postgresql+asyncpg://{{ .Values.postgresql.external.username }}:{{ .Values.postgresql.external.password }}@{{ $postgresHost }}:{{ .Values.postgresql.external.port }}/{{ .Values.postgresql.external.database }}"
|
||||
REDIS_SERVER: {{ $redisHost | quote }}
|
||||
REDIS_PORT: {{ .Values.redis.external.port | quote }}
|
||||
REDIS_DB: {{ .Values.redis.external.db | quote }}
|
||||
AI_BASE_URL: "http://{{ include "planet.fullname" . }}-aiprovider:{{ .Values.aiprovider.service.port }}"
|
||||
AI_PROVIDER_API: "http://{{ include "planet.fullname" . }}-aiprovider:{{ .Values.aiprovider.service.port }}"
|
||||
{{- range $key, $value := .Values.backend.env }}
|
||||
{{ $key }}: {{ $value | quote }}
|
||||
{{- end }}
|
||||
{{- range $key, $value := .Values.aiprovider.env }}
|
||||
{{ $key }}: {{ $value | quote }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,61 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-frontend
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
replicas: {{ .Values.frontend.replicaCount }}
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: frontend
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
{{- with .Values.global.imagePullSecrets }}
|
||||
imagePullSecrets:
|
||||
{{- toYaml . | nindent 8 }}
|
||||
{{- end }}
|
||||
containers:
|
||||
- name: frontend
|
||||
image: {{ include "planet.image" (dict "root" . "repository" .Values.frontend.image.repository) | quote }}
|
||||
imagePullPolicy: {{ .Values.image.pullPolicy }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 3000
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
initialDelaySeconds: 20
|
||||
periodSeconds: 20
|
||||
resources:
|
||||
{{- toYaml .Values.frontend.resources | nindent 12 }}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-frontend
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: frontend
|
||||
spec:
|
||||
type: ClusterIP
|
||||
ports:
|
||||
- name: http
|
||||
port: {{ .Values.frontend.service.port }}
|
||||
targetPort: http
|
||||
selector:
|
||||
{{- include "planet.selectorLabels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: frontend
|
||||
@@ -0,0 +1,29 @@
|
||||
{{- if .Values.frontend.ingress.enabled }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
{{- with .Values.frontend.ingress.annotations }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
ingressClassName: {{ .Values.frontend.ingress.className | quote }}
|
||||
{{- with .Values.frontend.ingress.tls }}
|
||||
tls:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
rules:
|
||||
- host: {{ .Values.frontend.ingress.host | quote }}
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: {{ include "planet.fullname" . }}-frontend
|
||||
port:
|
||||
name: http
|
||||
{{- end }}
|
||||
@@ -0,0 +1,14 @@
|
||||
apiVersion: v1
|
||||
kind: Secret
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-secrets
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
type: Opaque
|
||||
stringData:
|
||||
{{- range $key, $value := .Values.backend.secretEnv }}
|
||||
{{ $key }}: {{ $value | quote }}
|
||||
{{- end }}
|
||||
{{- range $key, $value := .Values.aiprovider.secretEnv }}
|
||||
{{ $key }}: {{ $value | quote }}
|
||||
{{- end }}
|
||||
@@ -0,0 +1,116 @@
|
||||
{{- if .Values.postgresql.internal.enabled }}
|
||||
apiVersion: apps/v1
|
||||
kind: StatefulSet
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-postgresql
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgresql
|
||||
spec:
|
||||
serviceName: {{ include "planet.fullname" . }}-postgresql
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: postgresql
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: postgresql
|
||||
spec:
|
||||
containers:
|
||||
- name: postgresql
|
||||
image: postgres:15
|
||||
ports:
|
||||
- name: postgres
|
||||
containerPort: 5432
|
||||
env:
|
||||
- name: POSTGRES_USER
|
||||
value: {{ .Values.postgresql.external.username | quote }}
|
||||
- name: POSTGRES_PASSWORD
|
||||
value: {{ .Values.postgresql.external.password | quote }}
|
||||
- name: POSTGRES_DB
|
||||
value: {{ .Values.postgresql.external.database | quote }}
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: ["pg_isready", "-U", {{ .Values.postgresql.external.username | quote }}]
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /var/lib/postgresql/data
|
||||
volumeClaimTemplates:
|
||||
- metadata:
|
||||
name: data
|
||||
spec:
|
||||
accessModes: ["ReadWriteOnce"]
|
||||
resources:
|
||||
requests:
|
||||
storage: 8Gi
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-postgresql
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgresql
|
||||
spec:
|
||||
ports:
|
||||
- name: postgres
|
||||
port: 5432
|
||||
targetPort: postgres
|
||||
selector:
|
||||
{{- include "planet.selectorLabels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: postgresql
|
||||
{{- end }}
|
||||
{{- if .Values.redis.internal.enabled }}
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-redis
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: redis
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "planet.selectorLabels" . | nindent 6 }}
|
||||
app.kubernetes.io/component: redis
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
{{- include "planet.selectorLabels" . | nindent 8 }}
|
||||
app.kubernetes.io/component: redis
|
||||
spec:
|
||||
containers:
|
||||
- name: redis
|
||||
image: redis:7-alpine
|
||||
ports:
|
||||
- name: redis
|
||||
containerPort: 6379
|
||||
readinessProbe:
|
||||
exec:
|
||||
command: ["redis-cli", "ping"]
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "planet.fullname" . }}-redis
|
||||
labels:
|
||||
{{- include "planet.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: redis
|
||||
spec:
|
||||
ports:
|
||||
- name: redis
|
||||
port: 6379
|
||||
targetPort: redis
|
||||
selector:
|
||||
{{- include "planet.selectorLabels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: redis
|
||||
{{- end }}
|
||||
@@ -0,0 +1,29 @@
|
||||
global:
|
||||
imageRegistry: gitea.rclaw.top
|
||||
imageNamespace: linkong/planet
|
||||
|
||||
image:
|
||||
tag: latest
|
||||
|
||||
frontend:
|
||||
ingress:
|
||||
enabled: true
|
||||
host: planet.local
|
||||
|
||||
postgresql:
|
||||
internal:
|
||||
enabled: true
|
||||
external:
|
||||
host: planet-postgresql
|
||||
port: 5432
|
||||
database: planet_db
|
||||
username: postgres
|
||||
password: postgres
|
||||
|
||||
redis:
|
||||
internal:
|
||||
enabled: true
|
||||
external:
|
||||
host: planet-redis
|
||||
port: 6379
|
||||
db: 0
|
||||
@@ -0,0 +1,73 @@
|
||||
global:
|
||||
imageRegistry: gitea.rclaw.top
|
||||
imageNamespace: linkong/planet
|
||||
imagePullSecrets: []
|
||||
|
||||
fullnameOverride: planet
|
||||
|
||||
image:
|
||||
tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
frontend:
|
||||
replicaCount: 1
|
||||
image:
|
||||
repository: frontend
|
||||
service:
|
||||
port: 3000
|
||||
ingress:
|
||||
enabled: true
|
||||
className: nginx
|
||||
host: planet.example.com
|
||||
annotations: {}
|
||||
tls: []
|
||||
resources: {}
|
||||
|
||||
backend:
|
||||
replicaCount: 1
|
||||
image:
|
||||
repository: backend
|
||||
service:
|
||||
port: 8000
|
||||
env:
|
||||
PROJECT_NAME: Planet
|
||||
CORS_ORIGINS: '["*"]'
|
||||
secretEnv:
|
||||
SECRET_KEY: change-me
|
||||
resources: {}
|
||||
|
||||
aiprovider:
|
||||
replicaCount: 1
|
||||
image:
|
||||
repository: aiprovider
|
||||
service:
|
||||
port: 8010
|
||||
env:
|
||||
AI_PROVIDER: openai
|
||||
AI_MODEL: gpt-4o-mini
|
||||
secretEnv:
|
||||
AI_API_KEY: ""
|
||||
resources: {}
|
||||
|
||||
postgresql:
|
||||
internal:
|
||||
enabled: false
|
||||
external:
|
||||
host: postgres.example.com
|
||||
port: 5432
|
||||
database: planet_db
|
||||
username: postgres
|
||||
password: postgres
|
||||
|
||||
redis:
|
||||
internal:
|
||||
enabled: false
|
||||
external:
|
||||
host: redis.example.com
|
||||
port: 6379
|
||||
db: 0
|
||||
|
||||
smoke:
|
||||
frontendPath: /
|
||||
backendHealthPath: /health
|
||||
aiProviderHealthPath: /health
|
||||
@@ -8,6 +8,71 @@ This project follows the repository versioning rule:
|
||||
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
|
||||
- `bugfix` -> `+0.0.1`
|
||||
|
||||
## [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
|
||||
|
||||
### Highlights
|
||||
- 新增正式交付基线:Gitea Actions CI、镜像发布、staging 自动部署,以及 Kubernetes Helm chart。
|
||||
- 前端生产镜像改为 `vite build` 静态产物 + nginx 托管,后端与 AI Provider 镜像移除开发 reload 并加入容器健康检查。
|
||||
- 明确 `planet.sh` 只作为开发启动入口,生产环境交给 Kubernetes Service、Ingress、readiness/liveness probe 和 rollout 管理。
|
||||
|
||||
### Added / Fixed / Improved
|
||||
- 新增 frontend/backend/aiprovider 镜像 build smoke、Helm lint/template、staging rollout 与 HTTP smoke test 流水线。
|
||||
- 新增 Helm values、single-node 演示依赖、ConfigMap/Secret 引用、ClusterIP 服务和 frontend Ingress。
|
||||
- 更新运维文档与交付计划,保留 Vite 生产构建路线,不新增 Webpack 双构建链,Electron 暂不进入主线。
|
||||
- 继续收口启动脚本风险:状态目录、健康检查端口默认值、PID 校验、端口诊断和开发环境跨平台边界说明。
|
||||
|
||||
---
|
||||
|
||||
## [0.52.0] — 2026-05-12
|
||||
|
||||
Released: 2026-05-12
|
||||
|
||||
@@ -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,132 @@
|
||||
# Earth High Precision Boundary Tiles Plan
|
||||
|
||||
## Status
|
||||
|
||||
Planning revised after visual review. The previous hand-authored China claim-line / point-buffer approach is rejected and must not be implemented.
|
||||
|
||||
Implemented separately:
|
||||
|
||||
- 地表 hover 三模式已实现。
|
||||
|
||||
Still planned:
|
||||
|
||||
- 权威 China POV 数据包。
|
||||
- OSM / coastline 高精度离线构建。
|
||||
- 版本化静态矢量瓦片输出。
|
||||
- 前端 bbox/tile/LRU 高精度加载器。
|
||||
|
||||
## Summary
|
||||
|
||||
Earth 国界线目标从“明显提升”升级为 **最高精度档按真实地图源一比一还原**:
|
||||
|
||||
- 高缩放时不能使用当前 `countries-admin0.min.geojson` 这种低精度简化线。
|
||||
- 最高 tile zoom 必须忠实保留选定权威矢量源的原始折点,不做视觉平滑,不做人工凭感觉补线。
|
||||
- 藏南、阿克赛钦等争议陆地直接作为中国国家面的一部分表达;hover 只显示普通 `中国 / CHN`,不显示特殊区域名。
|
||||
- 九段线 / 十段线必须来自官方标准地图口径或经地理配准校核后的权威矢量数据;不能手工目测画线,不能把马来西亚、菲律宾等周边陆地或近岸底盘划入中国面。
|
||||
|
||||
方案仍采用 **离线构建 + 静态矢量瓦片**。低缩放加载简化 base line;高缩放按当前视野 bbox 加载高精度 boundary tiles。第一版不使用 Redis,依靠 Nginx 静态服务、浏览器 HTTP cache 和前端 LRU。
|
||||
|
||||
## Data Source and Policy
|
||||
|
||||
- 基础陆地国界使用 OSM `boundary=administrative` + `admin_level=2`,并补充高精度 coastline,避免只靠粗糙国家面导致海岸线缺失。
|
||||
- China POV 覆盖数据必须独立成包,构建时优先级高于 OSM 原始归属:
|
||||
- 藏南 union 到中国面,同时从印度面 subtract。
|
||||
- 阿克赛钦 union 到中国面,同时从相关邻接面 subtract。
|
||||
- 台湾、澎湖、钓鱼岛及附属岛屿、赤尾屿、东沙、西沙、中沙、南沙等作为中国国家面/岛礁面的一部分进入 hover index。
|
||||
- 岛礁很小时可有最小可交互面,但 tooltip 仍是 `中国 / CHN`,不展示“某特殊区域归属”标签。
|
||||
- 九段线 / 十段线是独立 maritime claim line 图层:
|
||||
- 只渲染 dashed line,不参与国家陆地面。
|
||||
- 不用于吞并周边国家陆地或近岸水域。
|
||||
- 坐标必须来自官方标准地图、权威矢量数据,或从官方示意图配准后人工复核,不接受手工猜测坐标。
|
||||
- 必须保留 OSM 数据归因:`© OpenStreetMap contributors, ODbL`。
|
||||
|
||||
## Precision Requirements
|
||||
|
||||
- 最高精度档的验收口径是 **source-faithful**,不是“看起来更细”:
|
||||
- 对高精度源线,最高 zoom tile 不允许 Douglas-Peucker 简化。
|
||||
- 坐标量化精度至少保留到 `1e-5` 度级别,构建时不得把经纬度粗暴四舍五入到低精度。
|
||||
- 球面渲染只允许 densify 长边来贴合地球曲率;不允许 CatmullRom、Bezier 或任何会改变边界走向的平滑。
|
||||
- 海岸/边界红框类区域必须与源地图折线逐点对齐;若有偏差,只能追溯并替换数据源,不能靠渲染平滑掩盖。
|
||||
- 低缩放允许简化,但必须有误差预算:
|
||||
- base line 只服务远景识别。
|
||||
- 中 zoom tile 可简化到屏幕误差低于 `0.5px`。
|
||||
- 最高 zoom tile 使用无简化或近零误差版本。
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### 1. Data pipeline
|
||||
|
||||
新增边界构建脚本,使用 `/home/ray/.local/bin/uv` 运行:
|
||||
|
||||
1. 读取 OSM PBF 或预处理后的 admin-0 边界 / coastline GeoJSON。
|
||||
2. 读取 China POV override package。
|
||||
3. 使用可靠几何库做 union / difference / validity repair,禁止手写 polygon overlay。
|
||||
4. 生成中国国家面时直接合并藏南、阿克赛钦和相关岛礁;从相邻国家面扣除同一区域。
|
||||
5. 单独读取官方口径九段线 / 十段线矢量,生成 claim-line tiles。
|
||||
6. 输出:
|
||||
- 低精度 global base line。
|
||||
- 无简化 high-precision hover polygon index。
|
||||
- 高精度静态瓦片:`frontend/public/earth/data/boundaries/v1/{z}/{x}/{y}.geojson`。
|
||||
- 海上断续线瓦片:`frontend/public/earth/data/boundaries/v1/china-claims/{z}/{x}/{y}.geojson`。
|
||||
- manifest,记录数据源、覆盖规则版本、构建时间、简化误差和 attribution。
|
||||
|
||||
### 2. Tile levels and size budget
|
||||
|
||||
- Earth zoom `< 1.6`:只显示 global base line 和低精度 claim line。
|
||||
- Earth zoom `1.6-2.8`:加载 tile zoom `4-5`。
|
||||
- Earth zoom `2.8-4.0`:加载 tile zoom `6-7`。
|
||||
- Earth zoom `> 4.0`:加载 tile zoom `8-10`,使用最高精度无简化折线。
|
||||
- 单 tile gzip 目标 `20-80KB`,但最高精度档优先保证几何真实性;若超限,优先提高 tile zoom 或拆 tile,而不是简化真实线。
|
||||
|
||||
### 3. Frontend loading model
|
||||
|
||||
`country-boundaries.js` 拆成 base layer、tile layer 和 China claim layer:
|
||||
|
||||
- 首屏加载 base line + hover index,不阻塞 Earth 初始化。
|
||||
- 高缩放时根据 camera 可见范围计算经纬 bbox,再转换为 Web Mercator tile keys。
|
||||
- bbox 由屏幕中心、四角和边中点 raycast 得到,并扩张 `10-20%` 作为预取范围。
|
||||
- 处理反经线,必要时拆成两个 bbox。
|
||||
- 视野变化请求 debounce `150-250ms`。
|
||||
- 拖拽/惯性旋转中不每帧请求;缩放档或 tile key 集合没变时不刷新。
|
||||
- 加载当前视野 tile,并预取一圈邻接 tile。
|
||||
- base line 在高精度 tile 到达后降低 opacity,避免双线。
|
||||
|
||||
### 4. Caching and memory control
|
||||
|
||||
- 前端维护 `tileCache`、`inFlightTiles` 和 LRU 使用顺序。
|
||||
- tile cache 上限建议 `120-180` 个 tile;超过后释放最旧 tile 的 `BufferGeometry`。
|
||||
- Nginx 为 `/earth/data/boundaries/` 设置长缓存:
|
||||
- `Cache-Control: public, max-age=31536000, immutable`
|
||||
- gzip 包含 JSON。
|
||||
- tile URL 包含版本目录,例如 `v1`;数据更新时改版本目录破浏览器缓存。
|
||||
- 第一版不使用 Redis。只有改成动态裁剪 API、多 POV 同 URL、或压测证明静态服务成为瓶颈时再考虑 Redis。
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
1. 最高 zoom 的海岸线和国界线与选定源地图逐点一致,不再只是“明显提升”。
|
||||
2. 红框类海岸/边界细节在最高 zoom 下不能出现肉眼可见的低精度折线、直线切边或圆滑失真。
|
||||
3. 藏南、阿克赛钦 hover 命中普通 `中国 / CHN`;印度或其他邻接国家不再包含这些区域。
|
||||
4. 钓鱼岛、赤尾屿、南海诸岛代表点 hover 命中普通 `中国 / CHN`。
|
||||
5. 九段线 / 十段线位置与权威来源一致,不压入马来西亚、菲律宾等周边陆地或错误包围近岸底盘。
|
||||
6. 首屏不加载全球超高精度整包。
|
||||
7. 高缩放只请求当前视野附近 tile,快速旋转不会出现请求风暴。
|
||||
8. 回到已访问区域命中前端 cache 或浏览器 cache。
|
||||
9. 国界图层开关、hover 高亮、移动端中心国家高亮、悬停提示三模式保持可用。
|
||||
|
||||
## Verification
|
||||
|
||||
- 构建阶段:
|
||||
- 几何 validity check 全通过。
|
||||
- China POV 代表点测试全部返回 `CHN`。
|
||||
- 相邻国家代表点不得被 China override 误吞。
|
||||
- 最高 zoom tile 抽样与源数据做坐标级 diff,确认未简化。
|
||||
- 前端阶段:
|
||||
- 在 `frontend` 运行 `/home/ray/.bun/bin/bun run build`。
|
||||
- 浏览器 DevTools 验证低缩放无高精度 tile 请求,高缩放请求数量受控,重复视野走 cache。
|
||||
- 用截图中的红框区域、南海断续线、藏南、钓鱼岛、赤尾屿、南海诸岛做手动视觉验收。
|
||||
|
||||
## Sources and Assumptions
|
||||
|
||||
- 产品默认采用中国标准地图/公开地图合规口径;若后续支持多 POV,必须通过版本化数据目录隔离,不能让同一 URL 返回不同政治口径。
|
||||
- 当前仓库没有足够权威和足够精细的 China POV / 九段线矢量源,因此不能直接凭现有低精度 GeoJSON 完成“一比一还原”。
|
||||
- 实施前必须先引入或生成可审计的高精度源数据包;没有源数据时,只能实现加载框架,不能伪造边界。
|
||||
@@ -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 图标层规范
|
||||
|
||||
@@ -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。
|
||||
@@ -176,7 +176,7 @@ freshness:
|
||||
|
||||
## 聚合接口
|
||||
|
||||
状态更新:开发期已直接切换到新船只快照接口。旧 `/api/v1/visualization/geo/vessels` 不再兼容返回数据,而是返回 `410 Gone`;新的 Earth 船只首屏应调用 `/api/v1/vessels/snapshot`,实时更新走 `/ws` 的 `vessels` 订阅。
|
||||
状态更新:开发期已直接切换到新船只快照接口。旧 `/api/v1/visualization/geo/vessels` 路由已移除;新的 Earth 船只首屏应调用 `/api/v1/vessels/snapshot`,实时更新走 `/ws` 的 `vessels` 订阅。
|
||||
|
||||
现有展示接口应逐步改为消费聚合服务,而不是自己直接拼 `VesselPosition + VesselStatic`。
|
||||
|
||||
@@ -346,11 +346,11 @@ VesselFinder 等服务里的船只图片不属于 AIS 实时数据本身。图
|
||||
5. 船名标准化会读取 AISStream `MetaData.ShipName`;船型展示会从 `vessel_type_name` 和 AIS 数字 `vessel_type` 共同归一化,保证 marker 颜色、详情卡、hover 和搜索结果一致。
|
||||
6. 当前实现已转向 `/api/v1/vessels/snapshot`:必须带 bbox / zoom,默认 `limit=1000`,最大 `limit=5000`,不再支持旧 `/geo/vessels` 全量返回。
|
||||
|
||||
### v3.1 — 聚合完整性修复(已被新快照接口取代)
|
||||
### v3.1 — 聚合完整性修复(已被受控 fallback 取代)
|
||||
|
||||
原目标是先保证“所有已采集到的船都能显示”,BarentsWatch 不因为接入 AISStream 而被 raw observation 聚合结果遮蔽。开发期产品尚未上线后,决策调整为直接淘汰 legacy 船只表兜底:船只快照只读取 `ais_raw_observations` 聚合结果,旧 `vessel_position + vessel_static` 不再合并进 `/api/v1/vessels/snapshot`。
|
||||
原目标是先保证“所有已采集到的船都能显示”,BarentsWatch 不因为接入 AISStream 而被 raw observation 聚合结果遮蔽。当前实现已经移除旧 `/geo/vessels` 路由,船只入口统一为 `/api/v1/vessels/snapshot`。snapshot 优先读取 `ais_raw_observations` 聚合结果;当当前 raw 窗口为空时,才受控回退到 `vessel_position + vessel_static` 最新点,并通过 `diagnostics.legacy_fallback_used` 标记。
|
||||
|
||||
因此以下 legacy merge 要求作废,保留在文档中只作为历史决策记录:
|
||||
因此以下旧 `/geo/vessels` 全量 merge 要求作废,保留在文档中只作为历史决策记录:
|
||||
|
||||
1. `/geo/vessels` 必须合并 raw observation 聚合结果和 legacy latest position 结果。
|
||||
2. raw 与 legacy 同一 MMSI 同时存在时只显示一艘,优先使用 raw 聚合结果及其 `field_sources` / `selected_reasons`。
|
||||
@@ -462,8 +462,8 @@ REST collector 的自然状态是 `fetch -> transform -> save -> progress 0..100
|
||||
- 明显异常位置不会进入默认展示轨迹,并会留下 `quality_flags`。
|
||||
- 同一时间窗口内多来源相近轨迹点只展示一个点。
|
||||
- AISStream 重连或回放导致的重复消息不会重复进入聚合结果。
|
||||
- `/api/v1/vessels/snapshot` 只读取 AIS raw observation 聚合结果;legacy latest position 不再参与船只快照。
|
||||
- `/api/v1/visualization/geo/vessels` 返回 `410 Gone`,客户端必须迁移到新 snapshot API。
|
||||
- `/api/v1/vessels/snapshot` 优先读取 AIS raw observation 聚合结果;当当前 raw 窗口为空时,允许受控 fallback 到 legacy latest position。
|
||||
- `/api/v1/visualization/geo/vessels` 路由已移除,客户端必须迁移到新 snapshot API。
|
||||
- AISStream 长连接收到新船、位置变化和航向变化后,会通过内部 `/ws` 的 `vessels` channel 推送增量。
|
||||
- AISStream streaming 状态不会显示成固定百分比完成进度条,也不会在收到一批消息后误报采集完成。
|
||||
- `mmsi`、`imo`、`callsign` 等身份编号在前端不显示千分位符。
|
||||
|
||||
@@ -216,7 +216,7 @@ hover、locked、dimmed 可通过更新少量 instance attribute 实现,不再
|
||||
|
||||
### 1. 请求视口范围
|
||||
|
||||
前端请求 `/api/v1/vessels/snapshot` 时必须带上当前视口 `bbox`、`zoom` 和受控 `limit`,减少无关船只。旧 `/api/v1/visualization/geo/vessels` 已下线并返回 `410 Gone`。
|
||||
前端请求 `/api/v1/vessels/snapshot` 时必须带上当前视口 `bbox`、`zoom` 和受控 `limit`,减少无关船只。旧 `/api/v1/visualization/geo/vessels` 路由已移除。
|
||||
|
||||
### 2. 后端排序策略
|
||||
|
||||
|
||||
@@ -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)。
|
||||
|
||||
@@ -120,11 +113,12 @@ CREATE UNIQUE INDEX ON vessel_latest(mmsi);
|
||||
|
||||
#### 1.3 API 端点
|
||||
|
||||
```
|
||||
GET /api/v1/visualization/geo/vessels
|
||||
?bbox=lon_min,lat_min,lon_max,lat_max # 视口裁剪
|
||||
```http
|
||||
GET /api/v1/vessels/snapshot
|
||||
?bbox=lon_min,lat_min,lon_max,lat_max # 必填,视口裁剪
|
||||
?zoom=12 # 必填,当前缩放
|
||||
?type=cargo,tanker,passenger # 船型过滤
|
||||
?limit=0 # 可选;不传或 0 表示不裁剪数量
|
||||
?limit=1000 # 默认 1000,最大 5000
|
||||
→ GeoJSON FeatureCollection(Point)
|
||||
|
||||
GET /api/v1/visualization/vessels/{mmsi} # 单船详情
|
||||
@@ -163,7 +157,7 @@ GeoJSON Feature 格式:
|
||||
- 后端 BarentsWatch collector 继续以 HTTP polling 方式采集
|
||||
- AISStream 等实时源以独立 WebSocket collector 写入原始观测层
|
||||
- 展示接口从聚合服务读取当前船只视图,而不是由单个 collector 决定最终展示值
|
||||
- 前端默认不再给 `/geo/vessels` 传 `limit=5000`,`VESSEL_CONFIG.maxRenderedMarkers = 0` 表示不做前端数量裁剪;后续如性能不足再引入显式 LOD 上限
|
||||
- 旧 `/api/v1/visualization/geo/vessels` 路由已移除,前端必须使用受控 snapshot 接口。
|
||||
- marker 颜色、详情卡、hover 和搜索结果必须共享 `vessel_type_display` 船型归一化结果,避免 AIS 数字类型码已驱动颜色但卡片仍显示 `Other`
|
||||
- 前端是否升级为 WebSocket delta push 是独立优化,不影响后端采集器可以使用 WebSocket 接上游实时源
|
||||
|
||||
@@ -251,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,55 @@
|
||||
# Planet 正式交付与 CI/CD 稳定化计划
|
||||
|
||||
## Summary
|
||||
|
||||
- CI/CD 平台采用 Gitea Actions,由自托管 `act_runner` 执行。
|
||||
- 正式交付目标采用 Kubernetes,端口、健康检查、重启和滚动发布交给 Service、Ingress、readiness/liveness probe。
|
||||
- Vite 继续保留,但只作为开发服务器和生产构建工具;生产运行 nginx 托管 `vite build` 产物。
|
||||
- 不新增 Webpack 双构建链。Electron 仅在离线桌面交付成为明确目标后再评估。
|
||||
|
||||
## Key Changes
|
||||
|
||||
- 生产镜像:
|
||||
- frontend 多阶段构建,`bun install` + `bun run build`,最终 nginx 托管 `dist`。
|
||||
- backend/aiprovider 移除 `--reload`,加入容器健康检查。
|
||||
- 镜像标签使用 `<registry>/<namespace>/<service>:<git-sha>`,发布 tag 额外推 `vX.Y.Z`。
|
||||
- Kubernetes:
|
||||
- 新增 Helm chart:`deploy/helm/planet`。
|
||||
- frontend 暴露 Ingress;backend/aiprovider 默认 ClusterIP。
|
||||
- PostgreSQL/Redis 默认外部依赖,`values.single-node.yaml` 提供演示/测试内置依赖。
|
||||
- Gitea Actions:
|
||||
- `ci.yaml`:后端测试、前端构建、Docker build smoke、Helm render。
|
||||
- `release.yaml`:构建并推送三类镜像。
|
||||
- `deploy-staging.yaml`:部署 staging、等待 rollout、执行 smoke tests。
|
||||
- 开发脚本边界:
|
||||
- `planet.sh` 保留为本地开发便利脚本。
|
||||
- CI/CD 与正式部署不调用 `planet.sh start`。
|
||||
|
||||
## Vite / Webpack / Electron Decision
|
||||
|
||||
中肯结论:不要因为“企业生产环境”这件事去做 Webpack 版本;继续用 Vite,但把“开发服务器”和“生产构建/部署”分清楚。Electron 也不要现在做,除非正式版目标明确是离线桌面软件。
|
||||
|
||||
Vite 可以用于生产构建。生产环境运行的是 `vite build` 产出的静态资源,不是 Vite dev server。当前项目已经使用 React + Vite + Bun、`import.meta.env`、`public/earth` 静态资产路径和大量 Three.js/ES module 资源引用。维护 Webpack 双构建链会显著增加路径、资源、环境变量和回归测试成本。
|
||||
|
||||
如果未来客户环境确实要求更接近 Webpack 生态,优先做 Rsbuild/Rspack 技术 spike,而不是直接维护 Webpack 并行构建。Electron 适合离线运行、本地硬件/文件访问、系统托盘、自动更新和安装包分发;但 Planet 目前还包含 backend、database、Redis、AI Provider、Motion Agent 等服务编排,桌面壳不能解决正式交付的核心问题。
|
||||
|
||||
## Test Plan
|
||||
|
||||
- CI gates:
|
||||
- `uv sync --group dev`
|
||||
- `uv run pytest backend/tests/test_api.py backend/tests/test_realtime_sources.py -q`
|
||||
- `cd frontend && bun install --frozen-lockfile && bun run build`
|
||||
- Docker build frontend/backend/aiprovider
|
||||
- `helm lint deploy/helm/planet`
|
||||
- `helm template planet-staging deploy/helm/planet -f deploy/helm/planet/values.single-node.yaml`
|
||||
- Staging deployment:
|
||||
- `helm upgrade --install planet-staging deploy/helm/planet --namespace planet-staging`
|
||||
- 等待 frontend/backend/aiprovider rollout。
|
||||
- smoke test frontend `/`、frontend `/health`、backend `/health`、aiprovider `/health`。
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- main/dev 提交能通过 CI。
|
||||
- 发布 workflow 能生成可追踪镜像。
|
||||
- staging 可从零部署并完成滚动升级。
|
||||
- 正式部署不依赖本机端口清理,也不运行 Vite dev server。
|
||||
@@ -299,6 +299,17 @@ State semantics:
|
||||
|
||||
AISStream connectivity validation reads the saved collector configuration, environment variables, and `AISSTREAM_API_KEY` in `~/.zshrc` through `datasource_connectivity.py`. For actual collection, the most reliable path is saving the API key in `Settings -> Collector Settings -> AISStream Vessels`; if the key only lives in `~/.zshrc`, confirm that the backend process inherited it.
|
||||
|
||||
The console manages AISStream from `/datasources -> Realtime Streams`, not from the normal finite collection progress bar. The realtime stream API aggregates runtime state, health, configuration preview, and raw observation counters:
|
||||
|
||||
```http
|
||||
GET /api/v1/realtime-sources
|
||||
POST /api/v1/realtime-sources/{source}/start
|
||||
POST /api/v1/realtime-sources/{source}/stop
|
||||
POST /api/v1/realtime-sources/{source}/restart
|
||||
```
|
||||
|
||||
`aisstream_vessels` and custom `source_type=websocket` sources appear in that API. They do not participate in one-click collection percentages; the UI interprets them as long-lived services with message counters, lag, last success, and last error.
|
||||
|
||||
### AIS Raw Observations And Aggregation
|
||||
|
||||
AIS observations do not directly replace final vessel records. They are first saved as raw observations:
|
||||
@@ -318,7 +329,7 @@ GET /api/v1/visualization/vessels/{mmsi}/track
|
||||
GET /api/v1/visualization/vessels/{mmsi}/conflicts
|
||||
```
|
||||
|
||||
`/api/v1/vessels/snapshot` requires `bbox` and `zoom`, defaults to `limit=1000`, and caps `limit` at `5000`. It reads only aggregated `ais_raw_observations`; it no longer merges legacy `vessel_position` / `vessel_static` rows. The old `/api/v1/visualization/geo/vessels` endpoint has been removed and returns `410 Gone`.
|
||||
`/api/v1/vessels/snapshot` requires `bbox` and `zoom`, defaults to `limit=1000`, and caps `limit` at `5000`. It prefers aggregated `ais_raw_observations`; when the current raw window is empty, it can fall back to the latest legacy `vessel_position` / `vessel_static` rows and marks that path with `diagnostics.legacy_fallback_used`. The old `/api/v1/visualization/geo/vessels` route has been removed.
|
||||
|
||||
Realtime deltas are sent through the `/ws` `vessels` channel. Clients must subscribe with the current viewport:
|
||||
|
||||
|
||||
@@ -288,7 +288,7 @@ Normalization:
|
||||
|
||||
Connectivity validation reads saved configuration, environment variables, and `AISSTREAM_API_KEY` from `~/.zshrc`. For actual collection, prefer saving the API key in collector settings. If the key only lives in `~/.zshrc`, confirm that the backend process inherited it; otherwise validation may pass while the collector runtime cannot read the key.
|
||||
|
||||
Connectivity validation and actual collection are separate actions. A banner such as `AISStream credentials configured, WebSocket endpoint format valid` only means the saved settings can be used for a connection attempt; runtime status may still be `disconnected`. Global AIS data is written locally only while the `aisstream_vessels` collector is `streaming` / `connected` and its message count plus `last_seen_at` keep advancing.
|
||||
Connectivity validation and actual collection are separate actions. A banner such as `AISStream credentials configured, WebSocket endpoint format valid` only means the saved settings can be used for a connection attempt; runtime status may still be `disconnected`. Global AIS data is written locally only while `aisstream_vessels` is `streaming` / `connected` and its realtime stream counters plus `last_seen_at` keep advancing. Start, stop, reconnect, health, and counters are exposed through `/datasources -> Realtime Streams` and `/api/v1/realtime-sources`; AISStream is not counted in normal one-click collection progress.
|
||||
|
||||
The new vessel list entry point is no longer the legacy `/api/v1/visualization/geo/vessels` route. Earth initial state should call:
|
||||
|
||||
@@ -296,7 +296,7 @@ The new vessel list entry point is no longer the legacy `/api/v1/visualization/g
|
||||
GET /api/v1/vessels/snapshot?bbox=lon_min,lat_min,lon_max,lat_max&zoom=12&limit=1000
|
||||
```
|
||||
|
||||
That endpoint reads local aggregated `ais_raw_observations` only. Realtime updates use the `/ws` `vessels` channel; subscriptions must include `bbox`, `zoom`, and `limit`. The server filters updates per connection and merges collector broadcasts every second, keeping only the latest position per MMSI.
|
||||
That endpoint prefers local aggregated `ais_raw_observations`; when the current raw window is empty, it can fall back to the latest legacy `vessel_position` / `vessel_static` rows and exposes that through `diagnostics.legacy_fallback_used`. Realtime updates use the `/ws` `vessels` channel; subscriptions must include `bbox`, `zoom`, and `limit`. The server filters updates per connection and merges collector broadcasts every second, keeping only the latest position per MMSI.
|
||||
|
||||
## Custom REST / WebSocket Mapping Runtime
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -154,7 +154,7 @@ The `earth:compute-center-location-saved` reconciliation pipeline is deliberatel
|
||||
|
||||
The vessel layer now uses `/api/v1/vessels/snapshot` for the initial viewport snapshot and the `/ws` `vessels` channel for realtime deltas. Snapshot requests must include `bbox`, `zoom`, and a bounded `limit`; the backend defaults to `limit=1000` and caps it at `5000`. WebSocket subscriptions must include the same viewport fields so the server can filter updates per connection.
|
||||
|
||||
The legacy `/api/v1/visualization/geo/vessels` endpoint has been removed and returns `410 Gone`. Frontend code should fetch a snapshot for the current viewport when the layer opens, then subscribe to `vessels` deltas. After map pan or zoom, reload the snapshot and send a fresh vessels subscription. The backend no longer merges legacy `vessel_position` / `vessel_static` rows into vessel snapshots, so the frontend must not depend on old BarentsWatch-only fallback rows.
|
||||
The legacy `/api/v1/visualization/geo/vessels` route has been removed. Frontend code should fetch a snapshot for the current viewport when the layer opens, then subscribe to `vessels` deltas. After map pan or zoom, reload the snapshot and send a fresh vessels subscription. The backend only falls back to legacy `vessel_position` / `vessel_static` rows when the current raw window is empty; frontend code can detect that state through `diagnostics.legacy_fallback_used`.
|
||||
|
||||
The new layer API family is `/api/v1/layers/*`, which separates map rendering payloads from aggregate panel statistics. Layer requests must include `bbox`, `zoom`, and a bounded `limit`; responses include `visible_count`, `returned_count`, and `diagnostics`, where `degraded`, `truncated`, and `limit_clamped` are the frontend signals for fallback UI. Right-side aggregate panels should not sum the layer response. They should read `/api/v1/data-products` or `/api/v1/data-products/{product_id}/status`, because those statistics stay global and do not change with the viewport.
|
||||
|
||||
@@ -205,7 +205,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
|
||||
|
||||
|
||||
@@ -160,10 +160,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 +233,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
|
||||
|
||||
@@ -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,7 @@ 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. |
|
||||
|
||||
## Interaction Rules
|
||||
|
||||
|
||||
@@ -321,6 +321,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.
|
||||
|
||||
@@ -130,11 +130,12 @@ Steps:
|
||||
3. Keep the default endpoint `wss://stream.aisstream.io/v0/stream`
|
||||
4. Click the plug icon to test; confirm it reports `Reachable`
|
||||
5. Save collector settings
|
||||
6. Trigger the `aisstream_vessels` collector from the collection scheduler
|
||||
7. Watch the `AISStream Runtime` panel:
|
||||
6. Open the `Realtime Streams` tab on `/datasources` and find `AISStream Realtime Vessels`
|
||||
7. Use `Start`, `Stop`, or `Reconnect` there. The normal `Collection Tasks` tab does not count AISStream in one-click collection or percentage progress
|
||||
8. Watch the realtime stream panel:
|
||||
- `streaming` / `connected` means the live stream is being consumed
|
||||
- `messages this round` should keep growing
|
||||
- `disconnected` with `ConnectionResetError` means the upstream or network dropped; re-trigger or wait for reconnect
|
||||
- `total stored`, `last 24h`, `last 1h`, and `unique MMSI` show historical collection volume
|
||||
- `disconnected` with a recent error means the upstream or network dropped; click `Reconnect`
|
||||
|
||||
## Configure AI Credentials
|
||||
|
||||
@@ -203,7 +204,7 @@ To let a regular user read developer or operations docs, add `docs_developer` or
|
||||
|
||||
## Data Exploration
|
||||
|
||||
- `/datasources`: source directory. It can be filtered by product domain, layer/module, enabled state, last run status, whether collected records exist, and search text. Selecting rows triggers only those sources; with no selected rows, `Collect current filter` triggers the filtered scope. Clicking a name opens an info drawer showing endpoint, headers, base config, and built-in flag; endpoint/credentials editing happens at `/settings -> Collector Settings`. The `Collecting N` tag under the overall progress can be clicked to expand the current collection task list
|
||||
- `/datasources`: source directory. The `Collection Tasks` tab is for one-shot, scheduled, and finite collectors; it can be filtered by product domain, layer/module, enabled state, last run status, whether collected records exist, and search text. Selecting rows triggers only those sources; with no selected rows, `Collect current filter` triggers the filtered scope. The `Realtime Streams` tab is for AISStream / WebSocket long connections and shows connection health, stored totals, time-window counters, and Start / Stop / Reconnect actions. Clicking a name opens an info drawer showing endpoint, headers, base config, and built-in flag; endpoint/credentials editing happens at `/settings -> Collector Settings`. The `Collecting N` tag under the overall progress can be clicked to expand the current collection task list
|
||||
- `/data`: collected data table — used to verify "did data arrive", "is the freshness right", "does a source emit valid records"
|
||||
- `/bgp`: BGP detail page with list + detail + analysis; complements the BGP layer on Earth
|
||||
- `/alerts/system`, `/alerts/bgp`, `/alerts/situational`: system, BGP, and situational alerts
|
||||
@@ -228,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:
|
||||
|
||||
@@ -254,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.
|
||||
|
||||
@@ -309,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
|
||||
|
||||
|
||||
@@ -22,10 +22,10 @@ image_exists AND stamp_non_empty AND fingerprint_match
|
||||
|
||||
### Fix
|
||||
|
||||
The stamp file moved to a persistent cache path:
|
||||
The stamp file moved from a temporary location to a persistent cache path:
|
||||
|
||||
```bash
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="$HOME/.cache/planet/aiprovider_build.sha256"
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/planet/aiprovider_build.sha256"
|
||||
```
|
||||
|
||||
Writing the stamp creates the directory first:
|
||||
@@ -92,7 +92,7 @@ COPY aiprovider /app/aiprovider
|
||||
|
||||
### Runtime Configuration
|
||||
|
||||
Before starting AI Provider, `planet.sh` generates a temporary env-file and passes it to Compose or the manual `docker run` fallback. Configuration priority:
|
||||
Before starting AI Provider, `planet.sh` generates a current-user runtime env-file and passes it to Compose or the manual `docker run` fallback. The default path is `${XDG_STATE_HOME:-$HOME/.local/state}/planet/aiprovider_runtime.env`. Configuration priority:
|
||||
|
||||
1. `aiprovider/.env`
|
||||
2. simple `export AI_...=...` or `AI_...=...` lines from `~/.zshrc`
|
||||
@@ -188,6 +188,62 @@ Before the stamp path fix:
|
||||
|
||||
After moving the stamp file, plain `restart` uses the same `stop + start` behavior and the same fingerprint check as `restart -b`.
|
||||
|
||||
## State Files, Logs, and Failed-Start Cleanup
|
||||
|
||||
`planet.sh` no longer writes PID files, logs, or runtime env-files to fixed `/tmp/planet_*` paths. The default state directory is:
|
||||
|
||||
```bash
|
||||
${XDG_STATE_HOME:-$HOME/.local/state}/planet
|
||||
```
|
||||
|
||||
At startup the script creates this directory and tries to set it to `700`. The current files include:
|
||||
|
||||
- `backend.pid` / `frontend.pid` / `motion_agent.pid`
|
||||
- `backend.log` / `frontend.log` / `motion_agent.log`
|
||||
- `aiprovider_build.log`
|
||||
- `aiprovider_runtime.env`
|
||||
- `ports.env`
|
||||
|
||||
PID writes validate that the PID is a positive integer, include a trailing newline, and try to set file mode `600`. PID reads ignore invalid content instead of passing it to `kill`.
|
||||
|
||||
After a successful `start`, the script records the ports in `ports.env`. Later `./planet.sh health` calls prefer the last started ports; if the state file is missing, health checks fall back to the defaults `8000`, `3000`, `8010`, and `8765`. This avoids checking default ports after starting with custom ports.
|
||||
|
||||
Startup now has light failed-start cleanup. If `start` exits before completing, the script only cleans local processes that this run already started: backend, frontend, and Motion Agent. It does not stop services after a successful start. AI Provider, PostgreSQL, and Redis keep their existing container lifecycle behavior.
|
||||
|
||||
## Health Checks and Hardening
|
||||
|
||||
HTTP readiness checks now use `curl -fsS --max-time`, so 4xx and 5xx responses are no longer treated as healthy.
|
||||
|
||||
Process termination now validates:
|
||||
|
||||
- signal names are limited to `TERM`, `KILL`, `INT`, and `HUP`;
|
||||
- PIDs must be positive integers;
|
||||
- process group IDs must be positive integers.
|
||||
|
||||
This prevents bad PID files or invalid signals from reaching `kill`.
|
||||
|
||||
Frontend and Motion Agent startup failures now call `print_port_listener_details()`, matching backend port diagnostics. The Windows-side listener and cleanup path still only runs when WSL is detected.
|
||||
|
||||
## Cross-Platform Notes
|
||||
|
||||
The script is currently Linux-first with WSL enhancements. Normal Linux runs do not execute the PowerShell path; WSL gets extra Windows listener, portproxy, and camera guidance.
|
||||
|
||||
To make this single script fully portable across Linux, macOS, and WSL, the remaining platform differences should be wrapped behind compatibility helpers:
|
||||
|
||||
- `stat --format`, `sort -V`, and `xargs -r` are GNU-style and are not fully compatible with default macOS BSD tools.
|
||||
- `hostname -I`, `ss`, `fuser`, and `systemctl` are usually unavailable on macOS.
|
||||
- `tac` may be missing on macOS; use `awk` or Python as a fallback.
|
||||
- Docker Desktop on macOS does not use `systemctl` daemon diagnostics.
|
||||
- Camera auto-detection relies on `/dev/video*` / `v4l2-ctl`, which is Linux-specific; macOS should use explicit camera URLs or a separate AVFoundation detector.
|
||||
|
||||
The recommended direction is a small platform compatibility layer for port listener detection, version comparison, file metadata, reverse tail, LAN IP discovery, and Docker daemon diagnostics, instead of scattering more platform branches throughout service startup logic.
|
||||
|
||||
## Production Delivery Boundary
|
||||
|
||||
`planet.sh` is a local development convenience script, not the production startup entrypoint. Production delivery should use Kubernetes `Deployment`, `Service`, `Ingress`, and readiness/liveness probes for ports, health checks, restarts, and rolling upgrades. This removes the need for a host script to reclaim local ports and avoids running the Vite dev server in production.
|
||||
|
||||
The production frontend shape is `vite build` static output served by nginx/Caddy or an equivalent HTTP server. Do not use `bun run dev` or `vite preview` in production. The project does not maintain a parallel Webpack build chain; if a future enterprise requirement needs closer Webpack-ecosystem compatibility, run an Rsbuild/Rspack spike first. Electron should only be evaluated when the official target becomes an offline desktop application.
|
||||
|
||||
## Optional Motion Agent Startup
|
||||
|
||||
`planet.sh` can now manage the local Motion Capture Agent. It is disabled by default so ordinary development machines do not fail startup when cameras, OpenCV, or MediaPipe are unavailable.
|
||||
|
||||
@@ -34,7 +34,7 @@ After landing on the `/admin` dashboard, here's a recommended walk-through:
|
||||
|
||||
1. `/settings?tab=collector_credentials`: pick a collector and click the plug icon to test connectivity. Free collectors (e.g. open BGP) usually work right away; credential-bearing ones like `AISStream` or `BarentsWatch` need an API key / client secret first
|
||||
2. `/ai?tab=providers`: fill an LLM provider (e.g. `minimax` / `openai`), model, base URL, API key, and click the plug at the end of the base URL to test. WebSearch / OCR tools are optional
|
||||
3. `/datasources` or `/data`: check whether the collectors have produced data
|
||||
3. `/datasources` or `/data`: check whether collectors have produced data. Use `/datasources -> Collection Tasks` for finite collectors, and `/datasources -> Realtime Streams` for AISStream / WebSocket health and counters
|
||||
4. `/alerts/system`: verify system alerts look right
|
||||
5. `/users` (super_admin only): open accounts for teammates or adjust their groups
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -326,6 +326,17 @@ AISStream 使用 `wss://stream.aisstream.io/v0/stream` WebSocket endpoint。默
|
||||
|
||||
AISStream 连接验证会通过 `datasource_connectivity.py` 读取保存的采集器配置、环境变量和 `~/.zshrc` 中的 `AISSTREAM_API_KEY`。正式采集时,最稳妥的方式是把 API Key 保存到“设置 -> 采集器设置 -> AISStream 实时船舶”;如果只放在 `~/.zshrc`,需要确认后端进程实际继承到了该环境变量。
|
||||
|
||||
控制台通过 `/datasources -> 实时流` 管理 AISStream,而不是把它放进普通有限采集任务的进度条。实时流 API 会聚合运行态、健康状态、配置摘要和 raw observation 计数:
|
||||
|
||||
```http
|
||||
GET /api/v1/realtime-sources
|
||||
POST /api/v1/realtime-sources/{source}/start
|
||||
POST /api/v1/realtime-sources/{source}/stop
|
||||
POST /api/v1/realtime-sources/{source}/restart
|
||||
```
|
||||
|
||||
`aisstream_vessels` 和自定义 `source_type=websocket` 数据源会出现在该接口中。它们不参与一键采集百分比;前端按长连接服务展示消息计数、延迟、最近成功和最近错误。
|
||||
|
||||
### AIS 原始观测与聚合
|
||||
|
||||
AIS 观测写入后不会直接替换最终船只记录,而是先保存为 raw observation:
|
||||
@@ -345,7 +356,7 @@ GET /api/v1/visualization/vessels/{mmsi}/track
|
||||
GET /api/v1/visualization/vessels/{mmsi}/conflicts
|
||||
```
|
||||
|
||||
`/api/v1/vessels/snapshot` 必须携带 `bbox` 和 `zoom`,默认 `limit=1000`,最大 `limit=5000`。它只消费 `ais_raw_observations` 聚合结果,不再读取 legacy `vessel_position` / `vessel_static` 作为兜底。旧 `/api/v1/visualization/geo/vessels` 已下线并返回 `410 Gone`。
|
||||
`/api/v1/vessels/snapshot` 必须携带 `bbox` 和 `zoom`,默认 `limit=1000`,最大 `limit=5000`。它优先消费 `ais_raw_observations` 聚合结果;当当前 raw 窗口为空时,会受控回退到 legacy `vessel_position` / `vessel_static` 最新点,并在 `diagnostics.legacy_fallback_used` 中标明。旧 `/api/v1/visualization/geo/vessels` 路由已移除。
|
||||
|
||||
实时增量通过 `/ws` 的 `vessels` channel 推送。客户端订阅时必须带当前视口:
|
||||
|
||||
|
||||
@@ -290,7 +290,7 @@ AISStream 使用 WebSocket 实时流,采集器只写入 `ais_raw_observations`
|
||||
|
||||
连接验证会读取保存配置、环境变量和 `~/.zshrc` 中的 `AISSTREAM_API_KEY`。正式采集时,推荐把 API Key 保存到采集器设置;如果只写在 `~/.zshrc`,需要确认后端进程实际继承了该变量,否则连接验证可能可用但 collector 运行时拿不到 key。
|
||||
|
||||
连接验证和正式采集是两个不同动作。设置页出现 `AISStream 凭证已配置,WebSocket endpoint 格式有效` 只说明配置可以用于连接;运行状态仍可能是 `disconnected`。只有 `aisstream_vessels` collector 任务处于 `streaming` / `connected`,并且 `本轮消息数`、`last_seen_at` 持续更新时,全球 AIS 数据才会不断写入本地库。
|
||||
连接验证和正式采集是两个不同动作。设置页出现 `AISStream 凭证已配置,WebSocket endpoint 格式有效` 只说明配置可以用于连接;运行状态仍可能是 `disconnected`。只有 `aisstream_vessels` 处于 `streaming` / `connected`,并且实时流计数、`last_seen_at` 持续更新时,全球 AIS 数据才会不断写入本地库。启动、停止、重连、健康状态和计数统一从 `/datasources -> 实时流` 和 `/api/v1/realtime-sources` 查看;AISStream 不再参与普通一键采集进度。
|
||||
|
||||
新版本不再使用 legacy `/api/v1/visualization/geo/vessels` 作为船只列表入口。Earth 初始状态应调用:
|
||||
|
||||
@@ -298,7 +298,7 @@ AISStream 使用 WebSocket 实时流,采集器只写入 `ais_raw_observations`
|
||||
GET /api/v1/vessels/snapshot?bbox=lon_min,lat_min,lon_max,lat_max&zoom=12&limit=1000
|
||||
```
|
||||
|
||||
该接口只查询本地 `ais_raw_observations` 聚合结果。实时更新走 `/ws` 的 `vessels` channel,订阅时必须提供 `bbox`、`zoom` 和 `limit`。服务端按连接过滤 bbox,并对 collector 广播做 1 秒合并,同一 MMSI 只推送最新位置。
|
||||
该接口优先查询本地 `ais_raw_observations` 聚合结果;当当前 raw 窗口为空时,会受控回退到 legacy `vessel_position` / `vessel_static` 最新点,并通过 `diagnostics.legacy_fallback_used` 暴露。实时更新走 `/ws` 的 `vessels` channel,订阅时必须提供 `bbox`、`zoom` 和 `limit`。服务端按连接过滤 bbox,并对 collector 广播做 1 秒合并,同一 MMSI 只推送最新位置。
|
||||
|
||||
## 自定义 REST / WebSocket 映射运行时
|
||||
|
||||
|
||||
@@ -157,6 +157,7 @@ BGP 模块正在从一个只展示异常的演示功能,演进为分层观测
|
||||
- 由符号驱动的事件核心
|
||||
- 向外扩散的环形脉冲
|
||||
- 相比旧版 Earth 更少的弥散 glow
|
||||
- 事件区域 halo、collector coverage halo 和雷达 pulse 从各自图标色派生浅色调,而不是使用固定青绿色;红色高危事件、橙色活跃 collector 和蓝色 idle collector 保持各自色相一致,面状光晕则比图标更轻
|
||||
7. 右侧统计现在显示:
|
||||
- BGP events
|
||||
- collector count
|
||||
|
||||
@@ -311,7 +311,7 @@ AIS 船只图层入口:
|
||||
|
||||
AISStream 的 `PositionReport` 常带实时位置和 `MetaData.ShipName`,但船型通常来自低频 `ShipStaticData.Type`。后端会把 `MetaData.ShipName` 补进船名,并将类型码映射为 Cargo / Tanker / Passenger / Fishing / Military;仍缺失的船型需要等待静态 AIS 消息或后续船舶资料 enrichment,不能在前端凭颜色之外的信息臆造细分类。
|
||||
|
||||
旧 `/api/v1/visualization/geo/vessels` 已下线并返回 `410 Gone`。前端打开船只图层时应先按当前视口拉一次 `/api/v1/vessels/snapshot`,再用 WebSocket 接收同一视口内的 upsert 增量;地图拖动或缩放后应重新拉取 snapshot 并重发 vessels 订阅。后端不再把 legacy `vessel_position` / `vessel_static` 合并进船只快照,前端也不应依赖旧表里的 BarentsWatch-only 兜底数据。
|
||||
旧 `/api/v1/visualization/geo/vessels` 路由已移除。前端打开船只图层时应先按当前视口拉一次 `/api/v1/vessels/snapshot`,再用 WebSocket 接收同一视口内的 upsert 增量;地图拖动或缩放后应重新拉取 snapshot 并重发 vessels 订阅。后端只在当前 raw 窗口为空时受控回退到 legacy `vessel_position` / `vessel_static`,前端可通过 `diagnostics.legacy_fallback_used` 识别该状态。
|
||||
|
||||
新的图层接口族是 `/api/v1/layers/*`,用于把地图渲染数据和聚合面板统计分开。地图层请求必须带 `bbox`、`zoom` 和受控 `limit`,响应会返回 `visible_count`、`returned_count` 和 `diagnostics`,其中 `degraded/truncated/limit_clamped` 用于前端提示降级。右侧聚合统计不要从图层响应累加,应读取 `/api/v1/data-products` 或 `/api/v1/data-products/{product_id}/status`,因为这些统计保持全量/全局口径,不随当前视口变化。
|
||||
|
||||
@@ -419,11 +419,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 当成恒定纬度。
|
||||
|
||||
## 当前地形链路
|
||||
|
||||
真实地形首次启用会慢,原因不只是一个:
|
||||
|
||||
@@ -166,10 +166,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 +252,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;轨迹和地形是依赖/可选显示层,不参与常规启动数据加载。 |
|
||||
|
||||
## 地表图层栈
|
||||
@@ -32,9 +32,9 @@
|
||||
| 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,7 @@
|
||||
| 地形 on | 显示在高清材质之上,但低于国界 hover、footprint、卫星等强调层。 |
|
||||
| 大气云图 | 只控制云图 mesh 显隐。 |
|
||||
| 国界线 off | 只隐藏可交互国界线和 hover,高亮状态会清除;海陆基座填充仍作为 Earth 底图保留。 |
|
||||
| 真实卫星高度 off | 卫星点、轨迹和预测轨道都使用旧版同层球面;缺失 TLE 或传播失败的卫星也使用同一 fallback 高度。 |
|
||||
|
||||
## 交互规则
|
||||
|
||||
|
||||
@@ -323,6 +323,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,调试面板会显示浏览器本机摄像头实时预览,并在画面上绘制骨架。如果勾选了 `只显示骨骼`,视频预览会被隐藏,只显示深色背景和红/绿骨架。
|
||||
|
||||
@@ -133,11 +133,12 @@
|
||||
3. Endpoint 保持默认 `wss://stream.aisstream.io/v0/stream`
|
||||
4. 点击插头图标进行连接测试,确认显示 `可用`
|
||||
5. 保存采集器设置
|
||||
6. 到采集调度入口运行 `aisstream_vessels` collector
|
||||
7. 在 `AISStream 运行状态` 中观察:
|
||||
- `streaming` / `connected` 表示正在接收实时流
|
||||
- `本轮消息数` 应持续增长
|
||||
- 如果显示 `disconnected` 且错误为 `ConnectionResetError`,需要重新触发或等待重连
|
||||
6. 打开 `/datasources` 的 `实时流` tab,找到 `AISStream 实时船舶`
|
||||
7. 点击 `启动`、`停止` 或 `重连` 管理长连接;这里不显示百分比进度
|
||||
8. 在实时流卡片中观察:
|
||||
- `connected` 表示正在接收实时流
|
||||
- `累计入库`、`近 24h`、`近 1h` 和 `唯一 MMSI` 用于判断历史采集量
|
||||
- 如果显示 `disconnected` 且有最近错误,可以点击 `重连`
|
||||
|
||||
## 配置 AI 凭证
|
||||
|
||||
@@ -206,7 +207,7 @@ Base URL 输入框尾端的插头图标会触发连接测试。测试通过会
|
||||
|
||||
## 数据探索
|
||||
|
||||
- `/datasources`:数据源目录。可以按产品域、层级、启用状态、最近执行状态、是否已有采集数据和关键词筛选;勾选多行后可批量采集选中项,未勾选时“采集当前筛选”只触发当前筛选范围。点击名称打开信息抽屉查看 endpoint、请求头、基础配置和是否内置;接口、凭证、请求头的编辑统一在 `/settings` 的"采集器设置"。总体进度下方的 `采集中 N` 标签可点击,展开当前采集任务列表
|
||||
- `/datasources`:数据源目录。`采集任务` tab 面向一次性/定时采集器,可以按产品域、层级、启用状态、最近执行状态、是否已有采集数据和关键词筛选;勾选多行后可批量采集选中项,未勾选时“一键采集”触发当前筛选范围。`实时流` tab 面向 AISStream / WebSocket 长连接,展示连接健康、累计入库、时间窗统计和启动 / 停止 / 重连操作。点击名称打开信息抽屉查看 endpoint、请求头、基础配置和是否内置;接口、凭证、请求头的编辑统一在 `/settings` 的"采集器设置"。总体进度下方的 `采集中 N` 标签可点击,展开当前采集任务列表
|
||||
- `/data`:采集后数据表,适合排查"数据是否已经进入系统"、"更新时间是否符合预期"、"某个数据源是否产出有效记录"
|
||||
- `/bgp`:BGP 专题页面,列表 + 详情 + 研判,与 Earth 的 BGP 图层互补
|
||||
- `/alerts/system`、`/alerts/bgp`、`/alerts/situational`:系统、BGP、态势告警
|
||||
@@ -231,7 +232,7 @@ Earth `http://localhost:3000/earth` 是公开 3D 态势页面,不需要登录
|
||||
|
||||
### 图层控制
|
||||
|
||||
右侧图层面板用于打开或关闭图层。常见图层:经纬线、国界线、高清材质、大气云图、海缆、算力中心、BGP 观测、卫星、AIS 船只、轨迹、地形。
|
||||
右侧图层面板用于打开或关闭图层。常见图层:经纬线、国界线、高清材质、大气云图、海缆、算力中心、BGP 观测、卫星、AIS 船只、地形。卫星轨迹不再作为单独图层出现在图层列表中,改在设置面板里控制。
|
||||
|
||||
依赖关系:
|
||||
|
||||
@@ -257,7 +258,11 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军
|
||||
|
||||
### 设置
|
||||
|
||||
设置面板包含:旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼、地球默认大小、地形透明度、重置设置。
|
||||
设置面板包含:旋转模式 / 巡航模式 / 动捕模式、巡航模块(BGP/新闻/算力中心/船只/海缆/卫星)、视图设置(卫星显示风格、悬停提示、卫星呼吸闪烁、真实卫星高度、轨迹显示、低缩放圆点、日夜模式、面板显示开关)、动捕调试模式 / 输入源 / 只显示骨骼、地球默认大小、地形透明度、重置设置。
|
||||
|
||||
“真实卫星高度”默认开启:卫星会按 TLE/SGP4 算出的真实轨道高度做压缩分层显示,低轨仍靠近地球,高轨会更远但不会脱离当前视图。高轨显示高度会被压到地球半径外约四分之一以内,这样 GEO / MEO 仍能和 LEO 分层,但不会把视线、轨迹和选择操作拉得过散;关闭后恢复旧版所有卫星位于同一显示球面的效果。“轨迹显示”控制卫星轨迹线显隐,卫星图层关闭时轨迹也不可见。
|
||||
|
||||
“悬停提示”控制鼠标悬停地表时的 tooltip 内容:`国家` 只在陆地命中国家时显示国家信息,太平洋等海洋区域不弹出地表提示;`位置` 在陆地和海洋都显示纬度、经度和海拔;`完整` 是默认模式,陆地显示国家 + 位置,海洋显示位置。
|
||||
|
||||
这些设置保存在浏览器本地存储,换浏览器或清理站点数据后会恢复默认值。
|
||||
|
||||
@@ -312,6 +317,7 @@ Earth 预留了动作捕捉控制入口。实时链路两种输入源:
|
||||
- **Earth 打不开**:先确认前端服务是否在线;如果端口不是 `3000`,使用启动输出的实际端口
|
||||
- **图层没有数据**:进 `/datasources` 看数据源状态、是否已采集和最近执行结果,再到 `/data` 或 `/bgp` 看是否有记录
|
||||
- **卫星 / BGP / 海缆加载慢**:这些图层依赖后端接口和外部数据源,首次加载需要等启动任务完成
|
||||
- **卫星看起来不在同一层**:这是默认的真实高度压缩显示。想回到旧版同层球面,可在设置中关闭“真实卫星高度”
|
||||
|
||||
## Docs 文档站
|
||||
|
||||
|
||||
@@ -22,10 +22,10 @@ image_exists AND stamp_non_empty AND fingerprint_match
|
||||
|
||||
### 修复
|
||||
|
||||
将戳文件路径从 `/tmp/` 改到持久路径:
|
||||
将戳文件路径从临时目录改到持久缓存路径:
|
||||
|
||||
```bash
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="$HOME/.cache/planet/aiprovider_build.sha256"
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="${XDG_CACHE_HOME:-$HOME/.cache}/planet/aiprovider_build.sha256"
|
||||
```
|
||||
|
||||
写入时确保目录存在:
|
||||
@@ -94,7 +94,7 @@ COPY aiprovider /app/aiprovider
|
||||
|
||||
### 运行期配置来源
|
||||
|
||||
`planet.sh` 启动 AI Provider 前会生成临时 env-file,并把它传给 Compose 或手动 `docker run` fallback。配置优先来自:
|
||||
`planet.sh` 启动 AI Provider 前会生成受当前用户保护的运行期 env-file,并把它传给 Compose 或手动 `docker run` fallback。默认路径位于 `${XDG_STATE_HOME:-$HOME/.local/state}/planet/aiprovider_runtime.env`。配置优先来自:
|
||||
|
||||
1. `aiprovider/.env`
|
||||
2. `~/.zshrc` 中简单的 `export AI_...=...` 或 `AI_...=...` 行
|
||||
@@ -202,6 +202,62 @@ PY
|
||||
|
||||
修复戳文件路径后,无参 `restart` 同样使用 `stop + start`,fingerprint 检查正常生效,行为与 `restart -b` 完全一致。无需额外代码变更。
|
||||
|
||||
## 状态文件、日志与失败清理
|
||||
|
||||
`planet.sh` 不再把 PID、日志和运行期 env-file 写入固定 `/tmp/planet_*` 路径。默认状态目录为:
|
||||
|
||||
```bash
|
||||
${XDG_STATE_HOME:-$HOME/.local/state}/planet
|
||||
```
|
||||
|
||||
脚本启动时会创建该目录并尽量设置为 `700`。当前使用的文件包括:
|
||||
|
||||
- `backend.pid` / `frontend.pid` / `motion_agent.pid`
|
||||
- `backend.log` / `frontend.log` / `motion_agent.log`
|
||||
- `aiprovider_build.log`
|
||||
- `aiprovider_runtime.env`
|
||||
- `ports.env`
|
||||
|
||||
PID 文件写入前会校验 PID 为正整数,写入时带换行并尽量设置为 `600`。读取 PID 文件时,如果内容不是数字,脚本会忽略该文件,不会把垃圾内容传给 `kill`。
|
||||
|
||||
`start` 成功后会把本次端口写入 `ports.env`。后续执行 `./planet.sh health` 时,会优先检查上次启动端口;如果没有状态文件,则回退到默认端口 `8000`、`3000`、`8010`、`8765`。这避免了用自定义端口启动后,健康检查仍只看默认端口的问题。
|
||||
|
||||
启动过程有轻量失败清理:如果 `start` 中途失败,脚本只清理本轮已经拉起的本地进程(backend、frontend、Motion Agent),不会在正常启动完成后停止服务。AI Provider、PostgreSQL 和 Redis 容器仍按原有容器生命周期管理。
|
||||
|
||||
## 健康检查与安全加固
|
||||
|
||||
HTTP 健康检查统一使用 `curl -fsS --max-time`。因此 `/health` 返回 4xx/5xx 不再被视为在线。
|
||||
|
||||
进程终止路径现在会校验:
|
||||
|
||||
- signal 只允许 `TERM`、`KILL`、`INT`、`HUP`;
|
||||
- PID 必须是正整数;
|
||||
- 进程组 PGID 必须是正整数。
|
||||
|
||||
这可以避免坏 PID 文件或错误 signal 造成不可预期的 `kill` 行为。
|
||||
|
||||
前端和 Motion Agent 启动失败时,现在也会调用 `print_port_listener_details()`,输出与后端一致的端口监听诊断。WSL 下如果端口看起来被 Windows 侧占用,脚本仍只在检测到 WSL 时才调用 PowerShell 诊断或清理路径。
|
||||
|
||||
## 跨平台注意事项
|
||||
|
||||
当前脚本是 Linux-first,并带有 WSL 增强。普通 Linux 不会执行 WSL PowerShell 逻辑;WSL 下会额外提供 Windows listener、portproxy 和摄像头提示。
|
||||
|
||||
如果要把同一份脚本扩展为 Linux、macOS、WSL 三平台通用,还需要继续封装这些命令差异:
|
||||
|
||||
- `stat --format`、`sort -V`、`xargs -r` 是 GNU 风格,macOS 默认 BSD 工具不完全兼容。
|
||||
- `hostname -I`、`ss`、`fuser`、`systemctl` 在 macOS 上通常不可用。
|
||||
- `tac` 在 macOS 上不一定存在,可用 `awk` 或 Python 兜底。
|
||||
- Docker Desktop on macOS 不适用 `systemctl` daemon 诊断。
|
||||
- 摄像头自动发现依赖 `/dev/video*` / `v4l2-ctl`,这是 Linux 路线;macOS 应显式使用 camera URL 或另做 AVFoundation 检测。
|
||||
|
||||
维护方向是增加一个小的 platform compatibility 层,把端口监听检测、版本比较、文件元信息、反向 tail、LAN IP 获取和 Docker daemon 诊断集中处理,而不是在业务启动流程里继续散落平台判断。
|
||||
|
||||
## 正式交付边界
|
||||
|
||||
`planet.sh` 是本地开发便利脚本,不作为正式生产启动入口。正式交付应通过 Kubernetes 的 `Deployment`、`Service`、`Ingress`、readiness/liveness probe 管理端口、健康检查、重启和滚动发布。这样生产环境不需要脚本抢占宿主机端口,也不会依赖 Vite dev server。
|
||||
|
||||
前端生产形态是 `vite build` 生成静态资源,再由 nginx/Caddy 等 HTTP 服务器托管。不要在生产中使用 `bun run dev` 或 `vite preview`。当前不维护 Webpack 双构建链;如果未来需要评估更企业化的构建生态,优先做 Rsbuild/Rspack spike。Electron 仅在正式目标变成离线桌面软件时再单独评估。
|
||||
|
||||
## Motion Agent 可选启动
|
||||
|
||||
`planet.sh` 现在可以管理本地动作捕捉 Agent,但默认不会启动它,避免普通开发机因为没有摄像头、OpenCV 或 MediaPipe 而影响后端/前端启动。
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
1. `/settings?tab=collector_credentials`:选一个采集器,点插头图标做连接测试。免费 collector(开源 BGP 等)通常直接可用;像 `AISStream`、`BarentsWatch` 这类需要凭证的,需要先填 API Key/Client Secret
|
||||
2. `/ai?tab=providers`:填一个 LLM provider(例如 `minimax` / `openai`)、模型名、Base URL、API Key,点 Base URL 末端的插头测试连接。WebSearch / OCR 工具可选
|
||||
3. `/datasources` 或 `/data`:看采集器是否已经产出数据
|
||||
3. `/datasources` 或 `/data`:看采集器是否已经产出数据。有限采集器看 `/datasources -> 采集任务`,AISStream / WebSocket 长连接看 `/datasources -> 实时流` 的健康状态和计数
|
||||
4. `/alerts/system`:看系统告警是否正常
|
||||
5. `/users`(仅 `super_admin`):根据需要给同事开账号或调权限组
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
- 搜索可以查找海缆、卫星、算力中心、BGP 事件
|
||||
- 算力中心和 BGP 观测站详情卡可以自动采集坐标候选,并能在 Earth 上预览
|
||||
- 鼠标拖动、滚轮缩放、缩放百分比提示工作正常
|
||||
- 设置面板的旋转 / 巡航 / 动捕模式可以切换
|
||||
- 设置面板的旋转 / 巡航 / 动捕模式可以切换;视图设置里可以切换悬停提示,卫星相关设置里可以打开或关闭真实高度分层和轨迹显示
|
||||
|
||||
## 5. 找回密码
|
||||
|
||||
|
||||
@@ -16,12 +16,16 @@
|
||||
## Current Version
|
||||
|
||||
- `main` 当前主线历史推导到:`0.16.5`
|
||||
- `dev` 当前开发分支历史推导到:`0.52.0`
|
||||
- `dev` 当前开发分支历史推导到:`0.56.0`
|
||||
|
||||
## Timeline
|
||||
|
||||
| Version | Type | Branch | Commit | Summary |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `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 本地字体加载,避免部署路径变化或外部字体不可用时图标/边界资源失效 |
|
||||
| `0.51.0` | feature | `dev` | `pending` | 新增 AI Settings 控制台与 ai_tools 工具层;重写算力中心候选预览/保存交互(呼吸圈 + 即时图标);动作捕捉 zoom 改为 mirror-safe trend + pose hold 双通道,支持持续触发 |
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
dist
|
||||
.vite
|
||||
*.log
|
||||
coverage
|
||||
.DS_Store
|
||||
+11
-2
@@ -1,4 +1,4 @@
|
||||
FROM oven/bun:1-alpine
|
||||
FROM oven/bun:1-alpine AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -6,7 +6,16 @@ COPY package.json bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
RUN bun run build
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["bun", "run", "dev", "--", "--host", "0.0.0.0"]
|
||||
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
|
||||
CMD wget -qO- http://127.0.0.1:3000/health >/dev/null || exit 1
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
@@ -0,0 +1,56 @@
|
||||
server {
|
||||
listen 3000;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
|
||||
|
||||
location = /health {
|
||||
add_header Content-Type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location = /api/health {
|
||||
proxy_pass http://planet-backend:8000/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://planet-backend:8000/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /ws {
|
||||
proxy_pass http://planet-backend:8000/ws;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location = /index.html {
|
||||
add_header Cache-Control "no-store";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "planet-frontend",
|
||||
"version": "0.52.0",
|
||||
"version": "0.56.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1",
|
||||
"dependencies": {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -199,16 +199,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 +513,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 +529,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 +564,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 +573,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 +886,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 +907,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 +1218,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 +1260,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 +1350,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 +1360,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,
|
||||
@@ -331,7 +340,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 +352,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 +440,8 @@ export const BGP_CONFIG = {
|
||||
collectorScale: 11.5,
|
||||
collectorPulseScale: 16.5,
|
||||
collectorCoverageScale: 22.5,
|
||||
tintNeutralColor: 0xffffff,
|
||||
tintBlend: 0.72,
|
||||
},
|
||||
sizeStabilization: {
|
||||
enabled: true,
|
||||
|
||||
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;
|
||||
|
||||
@@ -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 {
|
||||
@@ -224,6 +225,7 @@ import {
|
||||
setDayNightInteractable,
|
||||
applyDeferredLayerVisibilitySettings,
|
||||
scheduleTerrainPrefetch,
|
||||
getSurfaceHoverInfoMode,
|
||||
} from "./controls.js";
|
||||
import {
|
||||
createLayerStartupTaskMap,
|
||||
@@ -276,6 +278,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 +397,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 +1412,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 +1437,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 +1564,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 =
|
||||
@@ -4648,9 +4697,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 +4732,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();
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
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;
|
||||
|
||||
let initialized = false;
|
||||
let refreshPromise = null;
|
||||
@@ -18,6 +22,8 @@ let lastFocus = null;
|
||||
let lastFetchAt = 0;
|
||||
let lastRegionSwitchAt = 0;
|
||||
let selectedCruiseStoryId = null;
|
||||
let morphTimer = null;
|
||||
|
||||
function getElements() {
|
||||
const isMobile = document.body.classList.contains("layout-mode-mobile");
|
||||
return {
|
||||
@@ -31,6 +37,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 +68,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 +323,7 @@ function renderEmptyState(message) {
|
||||
status.textContent = "等待聚合新闻源";
|
||||
}
|
||||
if (openBtn) openBtn.disabled = true;
|
||||
renderTicker({ items: [], focus: payload?.focus || { region: "global" } });
|
||||
}
|
||||
|
||||
function renderPayload(nextPayload) {
|
||||
@@ -87,6 +343,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.
|
||||
@@ -338,21 +596,24 @@ 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();
|
||||
|
||||
["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);
|
||||
}
|
||||
|
||||
@@ -259,9 +259,10 @@ const vesselIconLayer = createInteractableLayer({
|
||||
});
|
||||
|
||||
const DEFAULT_VESSEL_VIEWPORT = {
|
||||
bbox: [-180, -90, 180, 90],
|
||||
zoom: 2,
|
||||
bbox: [-10, 50, 35, 75],
|
||||
zoom: 4,
|
||||
};
|
||||
const MAX_VESSEL_SUBSCRIPTION_BBOX_AREA = 2500;
|
||||
|
||||
export function getVesselMarkers() {
|
||||
return vesselIconLayer.getMarkers();
|
||||
@@ -353,8 +354,34 @@ export async function loadVessels(_scene, earth, options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export function startVesselRealtime(earth, { onUpdate } = {}) {
|
||||
function normalizeVesselViewportOptions(options = {}) {
|
||||
const bbox = Array.isArray(options.bbox) && options.bbox.length === 4
|
||||
? options.bbox.map(Number)
|
||||
: DEFAULT_VESSEL_VIEWPORT.bbox;
|
||||
const [lonA, latA, lonB, latB] = bbox;
|
||||
const normalizedBbox = [
|
||||
Math.max(-180, Math.min(lonA, lonB)),
|
||||
Math.max(-90, Math.min(latA, latB)),
|
||||
Math.min(180, Math.max(lonA, lonB)),
|
||||
Math.min(90, Math.max(latA, latB)),
|
||||
];
|
||||
const area = (normalizedBbox[2] - normalizedBbox[0]) * (normalizedBbox[3] - normalizedBbox[1]);
|
||||
const safeBbox = Number.isFinite(area) && area <= MAX_VESSEL_SUBSCRIPTION_BBOX_AREA
|
||||
? normalizedBbox
|
||||
: DEFAULT_VESSEL_VIEWPORT.bbox;
|
||||
const zoom = Number.isFinite(Number(options.zoom))
|
||||
? Number(options.zoom)
|
||||
: DEFAULT_VESSEL_VIEWPORT.zoom;
|
||||
return {
|
||||
bbox: safeBbox,
|
||||
zoom: Math.max(1, Math.min(20, Math.round(zoom))),
|
||||
limit: options.limit ?? VESSEL_CONFIG.maxRenderedMarkers,
|
||||
};
|
||||
}
|
||||
|
||||
export function startVesselRealtime(earth, { onUpdate, bbox, zoom, limit } = {}) {
|
||||
if (vesselStreamSocket || typeof WebSocket === "undefined") return;
|
||||
const subscriptionOptions = normalizeVesselViewportOptions({ bbox, zoom, limit });
|
||||
const connect = () => {
|
||||
if (!showVessels || vesselStreamSocket) return;
|
||||
const socket = new WebSocket(getVesselStreamUrl());
|
||||
@@ -369,9 +396,9 @@ export function startVesselRealtime(earth, { onUpdate } = {}) {
|
||||
type: "subscribe",
|
||||
data: {
|
||||
channel: "vessels",
|
||||
bbox: DEFAULT_VESSEL_VIEWPORT.bbox,
|
||||
zoom: DEFAULT_VESSEL_VIEWPORT.zoom,
|
||||
limit: VESSEL_CONFIG.maxRenderedMarkers,
|
||||
bbox: subscriptionOptions.bbox,
|
||||
zoom: subscriptionOptions.zoom,
|
||||
limit: subscriptionOptions.limit,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
+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;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
@@ -84,6 +85,50 @@ interface CustomDataSourceOverride {
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
interface RealtimeSourceHealth {
|
||||
connection_state: string
|
||||
last_seen_at: string | null
|
||||
last_success_at: string | null
|
||||
last_error: string | null
|
||||
message_rate: number | null
|
||||
lag_seconds: number | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
interface RealtimeSourceStats {
|
||||
total_observations: number
|
||||
observations_24h: number
|
||||
observations_1h: number
|
||||
unique_mmsi_total: number
|
||||
unique_mmsi_24h: number
|
||||
latest_observed_at: string | null
|
||||
latest_collected_at: string | null
|
||||
}
|
||||
|
||||
interface RealtimeSourceRuntime {
|
||||
running: boolean
|
||||
done: boolean
|
||||
runtime: string
|
||||
}
|
||||
|
||||
interface RealtimeSource {
|
||||
source: string
|
||||
name: string
|
||||
display_name: string
|
||||
kind: 'builtin' | 'custom'
|
||||
config_id?: number
|
||||
source_type: string
|
||||
endpoint?: string
|
||||
is_active: boolean
|
||||
credential_configured: boolean
|
||||
message_types: string[]
|
||||
bounding_boxes: unknown[]
|
||||
config: Record<string, any>
|
||||
runtime: RealtimeSourceRuntime
|
||||
health: RealtimeSourceHealth | null
|
||||
stats: RealtimeSourceStats
|
||||
}
|
||||
|
||||
interface EditableDataSourceConfig {
|
||||
id: number
|
||||
name: string
|
||||
@@ -200,6 +245,10 @@ const PRODUCT_TAG_COLORS: Record<string, string> = {
|
||||
other: 'default',
|
||||
}
|
||||
|
||||
function isRealtimeBuiltinSource(source: BuiltInDataSource | UnifiedDataSource) {
|
||||
return source.source === 'aisstream_vessels'
|
||||
}
|
||||
|
||||
function normalizeBuiltin(source: BuiltInDataSource): UnifiedDataSource {
|
||||
return {
|
||||
key: `builtin:${source.id}`,
|
||||
@@ -242,7 +291,11 @@ function DataSources() {
|
||||
const [modal, modalContextHolder] = Modal.useModal()
|
||||
const [builtInSources, setBuiltInSources] = useState<BuiltInDataSource[]>([])
|
||||
const [customOverrides, setCustomOverrides] = useState<CustomDataSourceOverride[]>([])
|
||||
const [realtimeSources, setRealtimeSources] = useState<RealtimeSource[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [realtimeLoading, setRealtimeLoading] = useState(false)
|
||||
const [realtimeActionSource, setRealtimeActionSource] = useState<string | null>(null)
|
||||
const [activeTab, setActiveTab] = useState('tasks')
|
||||
const [triggerAllLoading, setTriggerAllLoading] = useState(false)
|
||||
const [forceTriggerAll, setForceTriggerAll] = useState(false)
|
||||
const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])
|
||||
@@ -259,7 +312,11 @@ function DataSources() {
|
||||
const [tableHeight, setTableHeight] = useState(360)
|
||||
const tableRegionRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
const allSources = useMemo(() => builtInSources.map(normalizeBuiltin), [builtInSources])
|
||||
const taskBuiltInSources = useMemo(
|
||||
() => builtInSources.filter((source) => !isRealtimeBuiltinSource(source)),
|
||||
[builtInSources],
|
||||
)
|
||||
const allSources = useMemo(() => taskBuiltInSources.map(normalizeBuiltin), [taskBuiltInSources])
|
||||
const selectedSourceIds = useMemo(
|
||||
() => selectedRowKeys
|
||||
.map((key) => allSources.find((source) => source.key === key)?.id)
|
||||
@@ -267,13 +324,13 @@ function DataSources() {
|
||||
[allSources, selectedRowKeys],
|
||||
)
|
||||
|
||||
const activeBuiltInCount = builtInSources.filter((source) => source.is_active).length
|
||||
const collectedBuiltInCount = builtInSources.filter((source) => source.has_collected_data).length
|
||||
const runningBuiltInSources = builtInSources.filter((source) => source.is_running)
|
||||
const activeBuiltInCount = taskBuiltInSources.filter((source) => source.is_active).length
|
||||
const collectedBuiltInCount = taskBuiltInSources.filter((source) => source.has_collected_data).length
|
||||
const runningBuiltInSources = taskBuiltInSources.filter((source) => source.is_running)
|
||||
const runningBuiltInCount = runningBuiltInSources.length
|
||||
const aggregateProgress = runningBuiltInCount > 0
|
||||
? Math.round(
|
||||
builtInSources
|
||||
taskBuiltInSources
|
||||
.filter((source) => source.is_running)
|
||||
.reduce((sum, source) => sum + (source.progress || 0), 0) / runningBuiltInCount,
|
||||
)
|
||||
@@ -304,10 +361,27 @@ function DataSources() {
|
||||
}
|
||||
}, [activeFilter, collectedFilter, messageApi, moduleFilter, productFilter, searchQuery, statusFilter])
|
||||
|
||||
const fetchRealtimeSources = useCallback(async () => {
|
||||
setRealtimeLoading(true)
|
||||
try {
|
||||
const response = await axios.get('/api/v1/realtime-sources')
|
||||
setRealtimeSources(response.data.data || [])
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch realtime sources:', error)
|
||||
messageApi.error('获取实时流状态失败')
|
||||
} finally {
|
||||
setRealtimeLoading(false)
|
||||
}
|
||||
}, [messageApi])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchData()
|
||||
}, [fetchData])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchRealtimeSources()
|
||||
}, [fetchRealtimeSources])
|
||||
|
||||
useEffect(() => {
|
||||
const visibleKeys = new Set(allSources.map((source) => source.key))
|
||||
setSelectedRowKeys((keys) => keys.filter((key) => visibleKeys.has(String(key))))
|
||||
@@ -324,6 +398,20 @@ function DataSources() {
|
||||
return () => observer.disconnect()
|
||||
}, [allSources.length])
|
||||
|
||||
const runRealtimeAction = async (source: string, action: 'start' | 'stop' | 'restart') => {
|
||||
try {
|
||||
setRealtimeActionSource(`${source}:${action}`)
|
||||
await axios.post(`/api/v1/realtime-sources/${encodeURIComponent(source)}/${action}`)
|
||||
messageApi.success(action === 'start' ? '实时流已启动' : action === 'stop' ? '实时流已停止' : '实时流已重连')
|
||||
await Promise.all([fetchRealtimeSources(), fetchData()])
|
||||
} catch (error: unknown) {
|
||||
const err = error as { response?: { data?: { detail?: string } } }
|
||||
messageApi.error(err.response?.data?.detail || '实时流操作失败')
|
||||
} finally {
|
||||
setRealtimeActionSource(null)
|
||||
}
|
||||
}
|
||||
|
||||
const fetchDatasourceTaskStatus = async (id: number) => {
|
||||
const res = await axios.get<DatasourceTaskStatus>(`/api/v1/datasources/${id}/task-status`)
|
||||
return res.data
|
||||
@@ -481,6 +569,160 @@ function DataSources() {
|
||||
}
|
||||
}
|
||||
|
||||
const formatCount = (value?: number | null) => Number(value || 0).toLocaleString()
|
||||
const formatLagSeconds = (value?: number | null) => {
|
||||
if (value === null || value === undefined || !Number.isFinite(Number(value))) return '-'
|
||||
const seconds = Number(value)
|
||||
if (seconds < 60) return `${Math.round(seconds)} 秒`
|
||||
if (seconds < 3600) return `${Math.round(seconds / 60)} 分钟`
|
||||
return `${Math.round(seconds / 3600)} 小时`
|
||||
}
|
||||
const getConnectionColor = (state?: string | null) => {
|
||||
if (state === 'connected') return 'success'
|
||||
if (state === 'connecting' || state === 'reconnecting') return 'processing'
|
||||
if (state === 'disconnected') return 'default'
|
||||
return 'warning'
|
||||
}
|
||||
const renderConfigPreview = (value: unknown) => {
|
||||
if (!Array.isArray(value) || value.length === 0) return '-'
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
const realtimeTotals = realtimeSources.reduce(
|
||||
(acc, source) => ({
|
||||
running: acc.running + (source.runtime?.running ? 1 : 0),
|
||||
total: acc.total + (source.stats?.total_observations || 0),
|
||||
recent24h: acc.recent24h + (source.stats?.observations_24h || 0),
|
||||
}),
|
||||
{ running: 0, total: 0, recent24h: 0 },
|
||||
)
|
||||
|
||||
const renderRealtimeSource = (source: RealtimeSource) => {
|
||||
const state = source.health?.connection_state || (source.runtime?.running ? 'running' : 'disconnected')
|
||||
const actionBusyPrefix = `${source.source}:`
|
||||
return (
|
||||
<Card
|
||||
key={source.source}
|
||||
size="small"
|
||||
title={(
|
||||
<Space wrap>
|
||||
<Text strong>{source.display_name || source.name}</Text>
|
||||
<Tag color={source.kind === 'builtin' ? 'blue' : 'purple'}>{source.kind === 'builtin' ? '内置' : '自定义'}</Tag>
|
||||
<Tag color={source.is_active ? 'success' : 'default'}>{source.is_active ? '启用' : '禁用'}</Tag>
|
||||
<Tag color={source.credential_configured ? 'success' : 'warning'}>
|
||||
{source.credential_configured ? '凭证已配置' : '缺少凭证'}
|
||||
</Tag>
|
||||
<Tag color={source.runtime?.running ? 'processing' : 'default'}>
|
||||
{source.runtime?.running ? '运行中' : '未运行'}
|
||||
</Tag>
|
||||
</Space>
|
||||
)}
|
||||
extra={(
|
||||
<Space size={6}>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<PlayCircleOutlined />}
|
||||
disabled={!source.is_active || source.runtime?.running}
|
||||
loading={realtimeActionSource === `${source.source}:start`}
|
||||
onClick={() => { void runRealtimeAction(source.source, 'start') }}
|
||||
>
|
||||
启动
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<PauseCircleOutlined />}
|
||||
disabled={!source.runtime?.running}
|
||||
loading={realtimeActionSource === `${source.source}:stop`}
|
||||
onClick={() => { void runRealtimeAction(source.source, 'stop') }}
|
||||
>
|
||||
停止
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
icon={<SyncOutlined />}
|
||||
loading={realtimeActionSource === `${source.source}:restart` || Boolean(realtimeActionSource?.startsWith(actionBusyPrefix))}
|
||||
onClick={() => { void runRealtimeAction(source.source, 'restart') }}
|
||||
>
|
||||
重连
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
>
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">连接状态</Text>
|
||||
<div><Tag color={getConnectionColor(source.health?.connection_state)}>{state}</Tag></div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">累计入库</Text>
|
||||
<div>{formatCount(source.stats?.total_observations)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">近 24h</Text>
|
||||
<div>{formatCount(source.stats?.observations_24h)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">近 1h</Text>
|
||||
<div>{formatCount(source.stats?.observations_1h)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">唯一 MMSI</Text>
|
||||
<div>{formatCount(source.stats?.unique_mmsi_total)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">近 24h MMSI</Text>
|
||||
<div>{formatCount(source.stats?.unique_mmsi_24h)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">最近收到</Text>
|
||||
<div>{formatDateTimeZhCN(source.health?.last_seen_at)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">数据延迟</Text>
|
||||
<div>{formatLagSeconds(source.health?.lag_seconds)}</div>
|
||||
</Col>
|
||||
</Row>
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={24} md={12}>
|
||||
<Text type="secondary">Endpoint</Text>
|
||||
<Input value={source.endpoint || '-'} readOnly />
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Text type="secondary">Message Types</Text>
|
||||
<Input value={source.message_types?.length ? source.message_types.join(', ') : '-'} readOnly />
|
||||
</Col>
|
||||
<Col xs={24}>
|
||||
<Text type="secondary">Bounding Boxes</Text>
|
||||
<Input value={renderConfigPreview(source.bounding_boxes)} readOnly />
|
||||
</Col>
|
||||
</Row>
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">最近成功</Text>
|
||||
<div>{formatDateTimeZhCN(source.health?.last_success_at)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">状态更新时间</Text>
|
||||
<div>{formatDateTimeZhCN(source.health?.updated_at)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">最近观测</Text>
|
||||
<div>{formatDateTimeZhCN(source.stats?.latest_observed_at)}</div>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Text type="secondary">最近入库</Text>
|
||||
<div>{formatDateTimeZhCN(source.stats?.latest_collected_at)}</div>
|
||||
</Col>
|
||||
</Row>
|
||||
{source.health?.last_error ? (
|
||||
<Alert showIcon type="error" message="最近错误" description={source.health.last_error} />
|
||||
) : null}
|
||||
</Space>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: '名称',
|
||||
@@ -591,8 +833,18 @@ function DataSources() {
|
||||
<div className="page-shell__header">
|
||||
<h2 style={{ margin: 0 }}>数据源</h2>
|
||||
</div>
|
||||
<div className="page-shell__body data-source-builtin-tab">
|
||||
<div className="data-source-bulk-toolbar">
|
||||
<div className="page-shell__body data-source-tabs-shell">
|
||||
<Tabs
|
||||
className="data-source-tabs"
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={[
|
||||
{
|
||||
key: 'tasks',
|
||||
label: '采集任务',
|
||||
children: (
|
||||
<div className="page-shell__body data-source-builtin-tab">
|
||||
<div className="data-source-bulk-toolbar">
|
||||
<div className="data-source-bulk-toolbar__meta">
|
||||
<div className="data-source-bulk-toolbar__title">采集实时进度</div>
|
||||
<div className="data-source-bulk-toolbar__progress">
|
||||
@@ -609,7 +861,7 @@ function DataSources() {
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">内置</span>
|
||||
<strong>{builtInSources.length}</strong>
|
||||
<strong>{taskBuiltInSources.length}</strong>
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">已启用</span>
|
||||
@@ -646,10 +898,10 @@ function DataSources() {
|
||||
<InfoCircleOutlined style={{ fontSize: 16, color: '#8c8c8c', cursor: 'default' }} />
|
||||
</Tooltip>
|
||||
<Checkbox checked={forceTriggerAll} onChange={(event) => setForceTriggerAll(event.target.checked)}>
|
||||
强制全部采集
|
||||
强制重新采集
|
||||
</Checkbox>
|
||||
<Button type="primary" size="middle" icon={<SyncOutlined />} loading={triggerAllLoading} onClick={handleTriggerAll}>
|
||||
{selectedSourceIds.length ? '采集选中项' : '采集当前筛选'}
|
||||
{selectedSourceIds.length ? '采集选中项' : '一键采集'}
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
@@ -741,6 +993,65 @@ function DataSources() {
|
||||
/>
|
||||
<ScrollbarOverlay containerRef={tableRegionRef} targetSelector=".ant-table-body" />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'realtime',
|
||||
label: '实时流',
|
||||
children: (
|
||||
<div className="page-shell__body data-source-builtin-tab">
|
||||
<div className="data-source-bulk-toolbar">
|
||||
<div className="data-source-bulk-toolbar__meta">
|
||||
<div className="data-source-bulk-toolbar__title">实时流健康</div>
|
||||
<div className="data-source-bulk-toolbar__progress">
|
||||
<div className="data-source-bulk-toolbar__progress-copy">
|
||||
<span>运行中</span>
|
||||
<strong>{realtimeTotals.running}</strong>
|
||||
</div>
|
||||
<Progress
|
||||
percent={realtimeSources.length ? Math.round((realtimeTotals.running / realtimeSources.length) * 100) : 0}
|
||||
size="small"
|
||||
status={realtimeTotals.running > 0 ? 'active' : 'normal'}
|
||||
showInfo={false}
|
||||
strokeColor="#1677ff"
|
||||
/>
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stats">
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">实时源</span>
|
||||
<strong>{realtimeSources.length}</strong>
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">运行中</span>
|
||||
<strong>{realtimeTotals.running}</strong>
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">累计入库</span>
|
||||
<strong>{formatCount(realtimeTotals.total)}</strong>
|
||||
</div>
|
||||
<div className="data-source-bulk-toolbar__stat-pill">
|
||||
<span className="data-source-bulk-toolbar__stat-label">近 24h</span>
|
||||
<strong>{formatCount(realtimeTotals.recent24h)}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button icon={<SyncOutlined />} loading={realtimeLoading} onClick={() => { void fetchRealtimeSources() }}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
{realtimeSources.length ? realtimeSources.map(renderRealtimeSource) : (
|
||||
<Card size="small">
|
||||
<Text type="secondary">当前没有实时流数据源。</Text>
|
||||
</Card>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env zsh
|
||||
|
||||
set -e
|
||||
set -o pipefail
|
||||
|
||||
SCRIPT_PATH="${(%):-%N}"
|
||||
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
|
||||
@@ -81,10 +82,12 @@ VERBOSE=0
|
||||
WAIT_VERBOSE_LOG_FILE=""
|
||||
WAIT_VERBOSE_LINE_COUNT="${WAIT_VERBOSE_LINE_COUNT:-5}"
|
||||
WAIT_VERBOSE_TAIL_LINE_COUNT="${WAIT_VERBOSE_TAIL_LINE_COUNT:-40}"
|
||||
HTTP_CHECK_MAX_TIME="${HTTP_CHECK_MAX_TIME:-0.2}"
|
||||
WAIT_VERBOSE_LAST_LOG_FILE=""
|
||||
WAIT_VERBOSE_EMITTED_LINES=0
|
||||
HTTP_CHECK_MAX_TIME="${HTTP_CHECK_MAX_TIME:-2}"
|
||||
|
||||
BACKEND_MAX_RETRIES="${BACKEND_MAX_RETRIES:-3}"
|
||||
BACKEND_HEALTH_CHECK_ATTEMPTS="${BACKEND_HEALTH_CHECK_ATTEMPTS:-10}"
|
||||
BACKEND_HEALTH_CHECK_ATTEMPTS="${BACKEND_HEALTH_CHECK_ATTEMPTS:-60}"
|
||||
BACKEND_HEALTH_CHECK_INTERVAL="${BACKEND_HEALTH_CHECK_INTERVAL:-2}"
|
||||
DEPENDENCY_INSTALL_MAX_RETRIES="${DEPENDENCY_INSTALL_MAX_RETRIES:-3}"
|
||||
DEPENDENCY_INSTALL_RETRY_INTERVAL="${DEPENDENCY_INSTALL_RETRY_INTERVAL:-5}"
|
||||
@@ -94,6 +97,8 @@ AI_PROVIDER_START_MAX_RETRIES="${AI_PROVIDER_START_MAX_RETRIES:-3}"
|
||||
AI_PROVIDER_RETRY_INTERVAL="${AI_PROVIDER_RETRY_INTERVAL:-5}"
|
||||
DATABASE_START_MAX_RETRIES="${DATABASE_START_MAX_RETRIES:-3}"
|
||||
DATABASE_RETRY_INTERVAL="${DATABASE_RETRY_INTERVAL:-5}"
|
||||
DATABASE_HEALTH_CHECK_ATTEMPTS="${DATABASE_HEALTH_CHECK_ATTEMPTS:-10}"
|
||||
DATABASE_HEALTH_CHECK_INTERVAL="${DATABASE_HEALTH_CHECK_INTERVAL:-$DATABASE_RETRY_INTERVAL}"
|
||||
FRONTEND_MAX_RETRIES="${FRONTEND_MAX_RETRIES:-3}"
|
||||
FRONTEND_HEALTH_CHECK_ATTEMPTS="${FRONTEND_HEALTH_CHECK_ATTEMPTS:-10}"
|
||||
FRONTEND_HEALTH_CHECK_INTERVAL="${FRONTEND_HEALTH_CHECK_INTERVAL:-2}"
|
||||
@@ -107,16 +112,27 @@ DEFAULT_AI_PROVIDER_PORT="${DEFAULT_AI_PROVIDER_PORT:-8010}"
|
||||
DEFAULT_MOTION_AGENT_PORT="${DEFAULT_MOTION_AGENT_PORT:-8765}"
|
||||
FRONTEND_RUNTIME_BIN="${FRONTEND_RUNTIME_BIN:-}"
|
||||
FRONTEND_RUNTIME_SOURCE="${FRONTEND_RUNTIME_SOURCE:-}"
|
||||
FRONTEND_PID_FILE="/tmp/planet_frontend.pid"
|
||||
PLANET_STATE_DIR="${PLANET_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/planet}"
|
||||
PLANET_CACHE_DIR="${PLANET_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/planet}"
|
||||
BACKEND_PID_FILE="$PLANET_STATE_DIR/backend.pid"
|
||||
BACKEND_LOG_FILE="$PLANET_STATE_DIR/backend.log"
|
||||
FRONTEND_PID_FILE="$PLANET_STATE_DIR/frontend.pid"
|
||||
FRONTEND_LOG_FILE="$PLANET_STATE_DIR/frontend.log"
|
||||
PLANET_PORT_STATE_FILE="$PLANET_STATE_DIR/ports.env"
|
||||
FRONTEND_VITE_ENTRY="$SCRIPT_DIR/frontend/node_modules/vite/bin/vite.js"
|
||||
MOTION_AGENT_PID_FILE="/tmp/planet_motion_agent.pid"
|
||||
MOTION_AGENT_LOG_FILE="/tmp/planet_motion_agent.log"
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="$HOME/.cache/planet/aiprovider_build.sha256"
|
||||
AI_PROVIDER_BUILD_LOG_FILE="/tmp/planet_aiprovider_build.log"
|
||||
MOTION_AGENT_PID_FILE="$PLANET_STATE_DIR/motion_agent.pid"
|
||||
MOTION_AGENT_LOG_FILE="$PLANET_STATE_DIR/motion_agent.log"
|
||||
AI_PROVIDER_BUILD_STAMP_FILE="$PLANET_CACHE_DIR/aiprovider_build.sha256"
|
||||
AI_PROVIDER_BUILD_LOG_FILE="$PLANET_STATE_DIR/aiprovider_build.log"
|
||||
AI_PROVIDER_IMAGE_NAME="${AI_PROVIDER_IMAGE_NAME:-planet_aiprovider:latest}"
|
||||
AI_PROVIDER_CONTAINER_NAME="${AI_PROVIDER_CONTAINER_NAME:-planet_aiprovider}"
|
||||
PLANET_AI_PROVIDER_RUNTIME_ENV_FILE="${PLANET_AI_PROVIDER_RUNTIME_ENV_FILE:-/tmp/planet_aiprovider_runtime.env}"
|
||||
PLANET_AI_PROVIDER_RUNTIME_ENV_FILE="${PLANET_AI_PROVIDER_RUNTIME_ENV_FILE:-$PLANET_STATE_DIR/aiprovider_runtime.env}"
|
||||
AI_PROVIDER_RECREATE_REQUIRED=0
|
||||
START_RUN_ACTIVE=0
|
||||
START_RUN_COMPLETED=0
|
||||
STARTED_BACKEND_THIS_RUN=0
|
||||
STARTED_FRONTEND_THIS_RUN=0
|
||||
STARTED_MOTION_AGENT_THIS_RUN=0
|
||||
AI_PROVIDER_RUNTIME_ENV_NAMES=(
|
||||
SERVICE_NAME
|
||||
SERVICE_VERSION
|
||||
@@ -133,6 +149,9 @@ AI_PROVIDER_RUNTIME_ENV_NAMES=(
|
||||
AI_PROVIDER_SERVICE_TOKEN
|
||||
)
|
||||
|
||||
mkdir -p "$PLANET_STATE_DIR" "$PLANET_CACHE_DIR"
|
||||
chmod 700 "$PLANET_STATE_DIR" "$PLANET_CACHE_DIR" 2>/dev/null || true
|
||||
|
||||
prepend_path_once() {
|
||||
local path_entry="$1"
|
||||
[ -n "$path_entry" ] || return 0
|
||||
@@ -152,6 +171,98 @@ ensure_local_runtime_bins_on_path() {
|
||||
ensure_local_runtime_bins_on_path
|
||||
|
||||
# Shell / Docker helpers
|
||||
is_pid() {
|
||||
[[ "${1:-}" =~ ^[0-9]+$ ]] && [ "$1" -gt 0 ]
|
||||
}
|
||||
|
||||
is_safe_signal() {
|
||||
case "${1:-}" in
|
||||
TERM|KILL|INT|HUP)
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
read_pid_file() {
|
||||
local pid_file="$1"
|
||||
local pid=""
|
||||
|
||||
[ -f "$pid_file" ] || return 1
|
||||
pid="$(head -n 1 "$pid_file" 2>/dev/null | tr -d '[:space:]' || true)"
|
||||
is_pid "$pid" || return 1
|
||||
printf "%s\n" "$pid"
|
||||
}
|
||||
|
||||
write_pid_file() {
|
||||
local pid_file="$1"
|
||||
local pid="$2"
|
||||
|
||||
is_pid "$pid" || return 1
|
||||
mkdir -p "$(dirname "$pid_file")"
|
||||
printf "%s\n" "$pid" > "$pid_file"
|
||||
chmod 600 "$pid_file" 2>/dev/null || true
|
||||
}
|
||||
|
||||
remove_pid_file() {
|
||||
local pid_file="$1"
|
||||
|
||||
rm -f "$pid_file"
|
||||
}
|
||||
|
||||
http_ok() {
|
||||
local url="$1"
|
||||
|
||||
curl -fsS --max-time "$HTTP_CHECK_MAX_TIME" "$url" > /dev/null 2>&1
|
||||
}
|
||||
|
||||
log_matches() {
|
||||
local log_file="$1"
|
||||
shift
|
||||
|
||||
[ -f "$log_file" ] || return 1
|
||||
[ "$#" -gt 0 ] || return 1
|
||||
grep -Eiq "$*" "$log_file" 2>/dev/null
|
||||
}
|
||||
|
||||
read_port_state_value() {
|
||||
local key="$1"
|
||||
local fallback="$2"
|
||||
local value=""
|
||||
|
||||
if [ -f "$PLANET_PORT_STATE_FILE" ]; then
|
||||
value="$(sed -nE "s/^${key}=([0-9]+)$/\\1/p" "$PLANET_PORT_STATE_FILE" | tail -n 1)"
|
||||
fi
|
||||
|
||||
if [ -n "$value" ]; then
|
||||
printf "%s" "$value"
|
||||
else
|
||||
printf "%s" "$fallback"
|
||||
fi
|
||||
}
|
||||
|
||||
write_port_state() {
|
||||
local backend_port="$1"
|
||||
local frontend_port="$2"
|
||||
local ai_provider_port="$3"
|
||||
local motion_agent_port="$4"
|
||||
|
||||
validate_port "$backend_port"
|
||||
validate_port "$frontend_port"
|
||||
validate_port "$ai_provider_port"
|
||||
validate_port "$motion_agent_port"
|
||||
|
||||
{
|
||||
printf "BACKEND_PORT=%s\n" "$backend_port"
|
||||
printf "FRONTEND_PORT=%s\n" "$frontend_port"
|
||||
printf "AI_PROVIDER_PORT=%s\n" "$ai_provider_port"
|
||||
printf "MOTION_AGENT_PORT=%s\n" "$motion_agent_port"
|
||||
} > "$PLANET_PORT_STATE_FILE"
|
||||
chmod 600 "$PLANET_PORT_STATE_FILE" 2>/dev/null || true
|
||||
}
|
||||
|
||||
compose_available() {
|
||||
docker compose version >/dev/null 2>&1
|
||||
}
|
||||
@@ -253,36 +364,10 @@ render_wait_spinner() {
|
||||
local frame_index=$(( (step - 1) % ${#WAIT_SPINNER_FRAMES[@]} ))
|
||||
local frame="${WAIT_SPINNER_FRAMES[$frame_index]}"
|
||||
local detail="${WAIT_SPINNER_DETAIL:- }"
|
||||
local verbose_line=""
|
||||
local verbose_lines=()
|
||||
local line_count=0
|
||||
local cursor_up=1
|
||||
|
||||
if [ "$VERBOSE" -eq 1 ] && [ -n "$WAIT_VERBOSE_LOG_FILE" ] && [ -f "$WAIT_VERBOSE_LOG_FILE" ]; then
|
||||
while IFS= read -r verbose_line; do
|
||||
verbose_line="$(sanitize_wait_detail "$verbose_line")"
|
||||
[ -n "$verbose_line" ] || continue
|
||||
verbose_lines+=("$verbose_line")
|
||||
done < <(tail -n "$WAIT_VERBOSE_TAIL_LINE_COUNT" "$WAIT_VERBOSE_LOG_FILE" 2>/dev/null)
|
||||
|
||||
while [ "${#verbose_lines[@]}" -gt "$WAIT_VERBOSE_LINE_COUNT" ]; do
|
||||
verbose_lines=("${verbose_lines[@]:1}")
|
||||
done
|
||||
fi
|
||||
flush_wait_verbose_log
|
||||
|
||||
printf "\r${DIM}·${NC} ${CYAN}%-2s${NC} ${WHITE}%s${NC}\033[K\n${DIM} %s${NC}\033[K" "$frame" "$message" "$detail" >&2
|
||||
|
||||
if [ "$VERBOSE" -eq 1 ]; then
|
||||
line_count=1
|
||||
while [ "$line_count" -le "$WAIT_VERBOSE_LINE_COUNT" ]; do
|
||||
verbose_line="${verbose_lines[$line_count]:- }"
|
||||
printf "\n${DIM} %s${NC}\033[K" "$verbose_line" >&2
|
||||
line_count=$((line_count + 1))
|
||||
done
|
||||
cursor_up=$((WAIT_VERBOSE_LINE_COUNT + 1))
|
||||
fi
|
||||
|
||||
printf "\033[%sA\r" "$cursor_up" >&2
|
||||
printf "\033[1A\r" >&2
|
||||
}
|
||||
|
||||
animate_wait_spinner() {
|
||||
@@ -305,11 +390,6 @@ animate_wait_spinner() {
|
||||
|
||||
clear_wait_spinner() {
|
||||
local line_count=0
|
||||
local clear_verbose_lines=0
|
||||
|
||||
if [ "$VERBOSE" -eq 1 ] && { [ "$WAIT_SESSION_ACTIVE" -eq 1 ] || [ -n "$WAIT_VERBOSE_LOG_FILE" ]; }; then
|
||||
clear_verbose_lines=1
|
||||
fi
|
||||
|
||||
printf "\r\033[K" >&2
|
||||
line_count=0
|
||||
@@ -318,15 +398,8 @@ clear_wait_spinner() {
|
||||
line_count=$((line_count + 1))
|
||||
done
|
||||
|
||||
if [ "$clear_verbose_lines" -eq 1 ]; then
|
||||
line_count=0
|
||||
while [ "$line_count" -lt "$WAIT_VERBOSE_LINE_COUNT" ]; do
|
||||
printf "\n\033[K" >&2
|
||||
line_count=$((line_count + 1))
|
||||
done
|
||||
fi
|
||||
|
||||
printf "\033[%sA\r" "$((clear_verbose_lines == 1 ? WAIT_VERBOSE_LINE_COUNT + 1 : 1))" >&2
|
||||
printf "\033[1A\r" >&2
|
||||
flush_wait_verbose_log
|
||||
}
|
||||
|
||||
start_wait_session() {
|
||||
@@ -366,6 +439,8 @@ reset_wait_spinner_state() {
|
||||
WAIT_SPINNER_DETAIL=""
|
||||
WAIT_SPINNER_MESSAGE=""
|
||||
WAIT_VERBOSE_LOG_FILE=""
|
||||
WAIT_VERBOSE_LAST_LOG_FILE=""
|
||||
WAIT_VERBOSE_EMITTED_LINES=0
|
||||
}
|
||||
|
||||
sanitize_wait_detail() {
|
||||
@@ -382,6 +457,39 @@ sanitize_wait_detail() {
|
||||
printf "%s" "$line"
|
||||
}
|
||||
|
||||
flush_wait_verbose_log() {
|
||||
local line=""
|
||||
local line_number=0
|
||||
local total_lines=0
|
||||
|
||||
[ "$VERBOSE" -eq 1 ] || return 0
|
||||
[ -n "$WAIT_VERBOSE_LOG_FILE" ] || return 0
|
||||
[ -f "$WAIT_VERBOSE_LOG_FILE" ] || return 0
|
||||
|
||||
if [ "$WAIT_VERBOSE_LAST_LOG_FILE" != "$WAIT_VERBOSE_LOG_FILE" ]; then
|
||||
WAIT_VERBOSE_LAST_LOG_FILE="$WAIT_VERBOSE_LOG_FILE"
|
||||
WAIT_VERBOSE_EMITTED_LINES=0
|
||||
fi
|
||||
|
||||
total_lines="$(wc -l < "$WAIT_VERBOSE_LOG_FILE" 2>/dev/null | tr -d '[:space:]')"
|
||||
[ -n "$total_lines" ] || total_lines=0
|
||||
if [ "$total_lines" -lt "$WAIT_VERBOSE_EMITTED_LINES" ]; then
|
||||
WAIT_VERBOSE_EMITTED_LINES=0
|
||||
fi
|
||||
[ "$total_lines" -gt "$WAIT_VERBOSE_EMITTED_LINES" ] || return 0
|
||||
|
||||
printf "\r\033[K" >&2
|
||||
while IFS= read -r line; do
|
||||
line_number=$((line_number + 1))
|
||||
[ "$line_number" -gt "$WAIT_VERBOSE_EMITTED_LINES" ] || continue
|
||||
line="$(sanitize_wait_detail "$line")"
|
||||
[ -n "$line" ] || continue
|
||||
printf "${DIM} %s${NC}\n" "$line" >&2
|
||||
done < "$WAIT_VERBOSE_LOG_FILE"
|
||||
|
||||
WAIT_VERBOSE_EMITTED_LINES="$total_lines"
|
||||
}
|
||||
|
||||
set_wait_detail() {
|
||||
WAIT_SPINNER_DETAIL="$(sanitize_wait_detail "$1")"
|
||||
if [ "$WAIT_SESSION_ACTIVE" -eq 1 ] && [ -n "$WAIT_SPINNER_MESSAGE" ]; then
|
||||
@@ -400,7 +508,7 @@ run_command_with_spinner() {
|
||||
fi
|
||||
|
||||
if [ "$VERBOSE" -eq 1 ]; then
|
||||
verbose_log_file="$(mktemp /tmp/planet_verbose.XXXXXX.log)"
|
||||
verbose_log_file="$(mktemp "$PLANET_STATE_DIR/verbose.XXXXXX.log")"
|
||||
WAIT_VERBOSE_LOG_FILE="$verbose_log_file"
|
||||
"$@" > "$verbose_log_file" 2>&1 &
|
||||
else
|
||||
@@ -494,7 +602,13 @@ log_error() {
|
||||
}
|
||||
|
||||
log_note() {
|
||||
if [ "$WAIT_SESSION_ACTIVE" -eq 1 ]; then
|
||||
clear_wait_spinner
|
||||
fi
|
||||
printf "${DIM} %s${NC}\n" "$1"
|
||||
if [ "$WAIT_SESSION_ACTIVE" -eq 1 ]; then
|
||||
resume_wait_session
|
||||
fi
|
||||
}
|
||||
|
||||
log_success() {
|
||||
@@ -704,7 +818,7 @@ remove_ai_provider_containers() {
|
||||
local container_ids
|
||||
container_ids="$(list_ai_provider_containers)"
|
||||
[ -n "$container_ids" ] || return 0
|
||||
echo "$container_ids" | xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
printf "%s\n" "$container_ids" | awk '/^[0-9a-f]{12,64}$/' | xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
run_ai_provider_container_manually() {
|
||||
@@ -1086,7 +1200,7 @@ wait_for_http() {
|
||||
set_wait_detail "${wait_detail_prefix} ${url} (1/${attempts})"
|
||||
|
||||
while [ "$attempt" -le "$attempts" ]; do
|
||||
if curl -s --max-time "$HTTP_CHECK_MAX_TIME" "$url" > /dev/null 2>&1; then
|
||||
if http_ok "$url"; then
|
||||
finish_wait_spinner "${service_name}已就绪"
|
||||
return 0
|
||||
fi
|
||||
@@ -1179,7 +1293,7 @@ wait_for_frontend_ready() {
|
||||
fi
|
||||
|
||||
if [ $(( tick % probe_every_ticks )) -eq 0 ] &&
|
||||
curl -s --max-time "$HTTP_CHECK_MAX_TIME" "http://localhost:${frontend_port}" > /dev/null 2>&1; then
|
||||
http_ok "http://localhost:${frontend_port}"; then
|
||||
if [ "$owns_wait_session" -eq 1 ]; then
|
||||
stop_wait_session
|
||||
finish_wait_spinner "前端已就绪"
|
||||
@@ -1289,6 +1403,7 @@ force_cleanup_external_port_listener() {
|
||||
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
|
||||
|
||||
@@ -1378,12 +1493,12 @@ EOF
|
||||
|
||||
# Service startup helpers
|
||||
wait_for_database_health() {
|
||||
wait_for_container_health "planet_postgres" "$AI_PROVIDER_HEALTH_CHECK_ATTEMPTS" "$DATABASE_RETRY_INTERVAL" "PostgreSQL" &&
|
||||
wait_for_container_health "planet_redis" "$AI_PROVIDER_HEALTH_CHECK_ATTEMPTS" "$DATABASE_RETRY_INTERVAL" "Redis"
|
||||
wait_for_container_health "planet_postgres" "$DATABASE_HEALTH_CHECK_ATTEMPTS" "$DATABASE_HEALTH_CHECK_INTERVAL" "PostgreSQL" &&
|
||||
wait_for_container_health "planet_redis" "$DATABASE_HEALTH_CHECK_ATTEMPTS" "$DATABASE_HEALTH_CHECK_INTERVAL" "Redis"
|
||||
}
|
||||
|
||||
wait_for_postgres_health() {
|
||||
wait_for_container_health "planet_postgres" "$AI_PROVIDER_HEALTH_CHECK_ATTEMPTS" "$DATABASE_RETRY_INTERVAL" "PostgreSQL"
|
||||
wait_for_container_health "planet_postgres" "$DATABASE_HEALTH_CHECK_ATTEMPTS" "$DATABASE_HEALTH_CHECK_INTERVAL" "PostgreSQL"
|
||||
}
|
||||
|
||||
start_database_services() {
|
||||
@@ -1401,6 +1516,19 @@ start_postgres_service() {
|
||||
# Backend lifecycle helpers
|
||||
cleanup_backend_processes() {
|
||||
local backend_port="${1:-$DEFAULT_BACKEND_PORT}"
|
||||
local tracked_pid=""
|
||||
|
||||
if [ -f "$BACKEND_PID_FILE" ]; then
|
||||
if tracked_pid="$(read_pid_file "$BACKEND_PID_FILE")"; then
|
||||
terminate_process_group TERM "$tracked_pid"
|
||||
terminate_process_tree TERM "$tracked_pid"
|
||||
sleep 1
|
||||
terminate_process_group KILL "$tracked_pid"
|
||||
terminate_process_tree KILL "$tracked_pid"
|
||||
fi
|
||||
remove_pid_file "$BACKEND_PID_FILE"
|
||||
fi
|
||||
|
||||
terminate_backend_processes TERM "$backend_port"
|
||||
|
||||
if ! wait_for_port_release "$backend_port" 15 0.2; then
|
||||
@@ -1424,11 +1552,12 @@ start_backend_with_retry() {
|
||||
fail_unreleased_port "$backend_port"
|
||||
fi
|
||||
cd "$SCRIPT_DIR/backend"
|
||||
: > /tmp/planet_backend.log
|
||||
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 > /tmp/planet_backend.log 2>&1 &
|
||||
: > "$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 &
|
||||
BACKEND_PID=$!
|
||||
write_pid_file "$BACKEND_PID_FILE" "$BACKEND_PID"
|
||||
if [ "$VERBOSE" -eq 1 ]; then
|
||||
WAIT_VERBOSE_LOG_FILE="/tmp/planet_backend.log"
|
||||
WAIT_VERBOSE_LOG_FILE="$BACKEND_LOG_FILE"
|
||||
fi
|
||||
|
||||
if wait_for_http "http://localhost:${backend_port}/health" "$BACKEND_HEALTH_CHECK_ATTEMPTS" "$BACKEND_HEALTH_CHECK_INTERVAL" "后端"; then
|
||||
@@ -1436,14 +1565,14 @@ start_backend_with_retry() {
|
||||
fi
|
||||
|
||||
kill "$BACKEND_PID" 2>/dev/null || true
|
||||
if backend_log_indicates_port_conflict "/tmp/planet_backend.log"; then
|
||||
if backend_log_indicates_port_conflict "$BACKEND_LOG_FILE"; then
|
||||
cleanup_backend_processes "$backend_port" || fail_unreleased_port "$backend_port"
|
||||
if wait_for_port_release "$backend_port" 5 0.2; then
|
||||
log_warn "后端端口冲突已清理,立即重试启动"
|
||||
retry=$((retry + 1))
|
||||
continue
|
||||
fi
|
||||
report_backend_port_conflict_if_needed "$backend_port" "/tmp/planet_backend.log"
|
||||
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"
|
||||
@@ -1451,7 +1580,7 @@ start_backend_with_retry() {
|
||||
done
|
||||
|
||||
clear_wait_spinner
|
||||
report_backend_port_conflict_if_needed "$backend_port" "/tmp/planet_backend.log" || true
|
||||
report_backend_port_conflict_if_needed "$backend_port" "$BACKEND_LOG_FILE" || true
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -1500,8 +1629,7 @@ ai_provider_service_healthy() {
|
||||
local ai_provider_port="${1:-$DEFAULT_AI_PROVIDER_PORT}"
|
||||
|
||||
docker inspect "$AI_PROVIDER_CONTAINER_NAME" >/dev/null 2>&1 || return 1
|
||||
curl -s --max-time "$HTTP_CHECK_MAX_TIME" \
|
||||
"http://localhost:${ai_provider_port}/health" >/dev/null 2>&1
|
||||
http_ok "http://localhost:${ai_provider_port}/health"
|
||||
}
|
||||
|
||||
ensure_database_services_healthy() {
|
||||
@@ -1596,7 +1724,7 @@ start_backend_service() {
|
||||
ensure_uv_backend_deps
|
||||
if ! start_backend_with_retry "$backend_port"; then
|
||||
log_error "后端启动失败,已重试 ${BACKEND_MAX_RETRIES} 次"
|
||||
tail -10 /tmp/planet_backend.log
|
||||
tail -10 "$BACKEND_LOG_FILE"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
@@ -1650,11 +1778,12 @@ terminate_process_group() {
|
||||
local pid="$2"
|
||||
local pgid=""
|
||||
|
||||
[ -n "$pid" ] || return 0
|
||||
is_safe_signal "$signal" || return 1
|
||||
is_pid "$pid" || return 0
|
||||
kill -0 "$pid" 2>/dev/null || return 0
|
||||
|
||||
pgid="$(ps -o pgid= -p "$pid" 2>/dev/null | tr -d '[:space:]')"
|
||||
[ -n "$pgid" ] || return 0
|
||||
is_pid "$pgid" || return 0
|
||||
|
||||
kill "-${signal}" -- "-${pgid}" 2>/dev/null || true
|
||||
}
|
||||
@@ -1665,7 +1794,7 @@ terminate_backend_processes() {
|
||||
local pids=""
|
||||
local pid=""
|
||||
|
||||
pids="$(pgrep -f "uvicorn" 2>/dev/null || true)"
|
||||
pids="$(pgrep -f "uvicorn .*--port ${backend_port}" 2>/dev/null || true)"
|
||||
for pid in $pids; do
|
||||
terminate_process_group "$signal" "$pid"
|
||||
terminate_process_tree "$signal" "$pid"
|
||||
@@ -1683,12 +1812,13 @@ terminate_process_tree() {
|
||||
local pid="$2"
|
||||
local child_pid
|
||||
|
||||
[ -n "$pid" ] || return 0
|
||||
is_safe_signal "$signal" || return 1
|
||||
is_pid "$pid" || return 0
|
||||
kill -0 "$pid" 2>/dev/null || return 0
|
||||
|
||||
if command -v pgrep >/dev/null 2>&1; then
|
||||
while IFS= read -r child_pid; do
|
||||
[ -n "$child_pid" ] || continue
|
||||
is_pid "$child_pid" || continue
|
||||
terminate_process_tree "$signal" "$child_pid"
|
||||
done < <(pgrep -P "$pid" 2>/dev/null || true)
|
||||
fi
|
||||
@@ -1821,15 +1951,13 @@ kill_port_if_requested() {
|
||||
frontend_log_indicates_port_conflict() {
|
||||
local log_file="$1"
|
||||
|
||||
[ -f "$log_file" ] || return 1
|
||||
grep -q "Port .* is already in use" "$log_file" 2>/dev/null
|
||||
log_matches "$log_file" "Port .* is already in use"
|
||||
}
|
||||
|
||||
backend_log_indicates_port_conflict() {
|
||||
local log_file="$1"
|
||||
|
||||
[ -f "$log_file" ] || return 1
|
||||
grep -Eiq "Address already in use|Errno 98" "$log_file" 2>/dev/null
|
||||
log_matches "$log_file" "Address already in use|Errno 98"
|
||||
}
|
||||
|
||||
print_windows_port_listener_details() {
|
||||
@@ -1927,18 +2055,16 @@ cleanup_frontend_processes() {
|
||||
local tracked_pid=""
|
||||
|
||||
if [ -f "$FRONTEND_PID_FILE" ]; then
|
||||
tracked_pid="$(cat "$FRONTEND_PID_FILE" 2>/dev/null || true)"
|
||||
if [ -n "$tracked_pid" ]; then
|
||||
if tracked_pid="$(read_pid_file "$FRONTEND_PID_FILE")"; then
|
||||
terminate_process_tree TERM "$tracked_pid"
|
||||
sleep 1
|
||||
terminate_process_tree KILL "$tracked_pid"
|
||||
fi
|
||||
rm -f "$FRONTEND_PID_FILE"
|
||||
remove_pid_file "$FRONTEND_PID_FILE"
|
||||
fi
|
||||
|
||||
pkill -f "${FRONTEND_VITE_ENTRY} --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
|
||||
pkill -f "${FRONTEND_VITE_ENTRY}" 2>/dev/null || true
|
||||
}
|
||||
|
||||
start_frontend_with_retry() {
|
||||
@@ -1954,25 +2080,25 @@ start_frontend_with_retry() {
|
||||
log_warn "前端端口 ${frontend_port} 预清理后仍需由 Vite 启动流程确认"
|
||||
fi
|
||||
cd "$SCRIPT_DIR/frontend"
|
||||
: > /tmp/planet_frontend.log
|
||||
: > "$FRONTEND_LOG_FILE"
|
||||
local -a frontend_args
|
||||
frontend_args=("$FRONTEND_VITE_ENTRY")
|
||||
if [ "$frontend_lan_enabled" -eq 1 ]; then
|
||||
frontend_args+=(--host 0.0.0.0)
|
||||
fi
|
||||
frontend_args+=(--port "$frontend_port" --strictPort)
|
||||
nohup "$FRONTEND_RUNTIME_BIN" "${frontend_args[@]}" > /tmp/planet_frontend.log 2>&1 &
|
||||
nohup "$FRONTEND_RUNTIME_BIN" "${frontend_args[@]}" > "$FRONTEND_LOG_FILE" 2>&1 &
|
||||
FRONTEND_PID=$!
|
||||
printf "%s" "$FRONTEND_PID" > "$FRONTEND_PID_FILE"
|
||||
write_pid_file "$FRONTEND_PID_FILE" "$FRONTEND_PID"
|
||||
|
||||
if wait_for_frontend_ready "$frontend_port" "$FRONTEND_PID" "/tmp/planet_frontend.log" "$FRONTEND_HEALTH_CHECK_ATTEMPTS" "$FRONTEND_HEALTH_CHECK_INTERVAL"; then
|
||||
if wait_for_frontend_ready "$frontend_port" "$FRONTEND_PID" "$FRONTEND_LOG_FILE" "$FRONTEND_HEALTH_CHECK_ATTEMPTS" "$FRONTEND_HEALTH_CHECK_INTERVAL"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
cleanup_frontend_processes "$frontend_port"
|
||||
reset_wait_spinner_state
|
||||
|
||||
if [ "$frontend_port_requested" -eq 1 ] && frontend_log_indicates_port_conflict "/tmp/planet_frontend.log"; then
|
||||
if [ "$frontend_port_requested" -eq 1 ] && frontend_log_indicates_port_conflict "$FRONTEND_LOG_FILE"; then
|
||||
kill_port_if_requested "$frontend_port" "前端"
|
||||
fi
|
||||
|
||||
@@ -2007,7 +2133,8 @@ start_frontend_service() {
|
||||
if ! start_frontend_with_retry "$frontend_port" "$frontend_port_requested" "$frontend_lan_enabled"; then
|
||||
stop_wait_session
|
||||
log_error "前端启动失败,已重试 ${FRONTEND_MAX_RETRIES} 次"
|
||||
tail -10 /tmp/planet_frontend.log
|
||||
tail -10 "$FRONTEND_LOG_FILE"
|
||||
print_port_listener_details "$frontend_port"
|
||||
exit 1
|
||||
fi
|
||||
stop_wait_session
|
||||
@@ -2139,7 +2266,7 @@ cleanup_exit_containers() {
|
||||
exit_containers="$(docker ps -a --filter status=exited -q 2>/dev/null || true)"
|
||||
if [ -n "$exit_containers" ]; then
|
||||
log_step "清理残留 Exit 容器"
|
||||
echo "$exit_containers" | xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
printf "%s\n" "$exit_containers" | awk '/^[0-9a-f]{12,64}$/' | xargs -r docker rm -f >/dev/null 2>&1 || true
|
||||
log_success "残留容器已清理"
|
||||
fi
|
||||
}
|
||||
@@ -2157,7 +2284,7 @@ stop_container_if_running() {
|
||||
}
|
||||
|
||||
stop_backend_service() {
|
||||
if pgrep -f "uvicorn" >/dev/null 2>&1 || ! can_bind_port "$DEFAULT_BACKEND_PORT"; then
|
||||
if pgrep -f "uvicorn .*--port ${DEFAULT_BACKEND_PORT}" >/dev/null 2>&1 || [ -f "$BACKEND_PID_FILE" ] || ! can_bind_port "$DEFAULT_BACKEND_PORT"; then
|
||||
cleanup_backend_processes "$DEFAULT_BACKEND_PORT"
|
||||
log_halt "后端服务已停止"
|
||||
fi
|
||||
@@ -2168,7 +2295,7 @@ stop_ai_provider_service() {
|
||||
}
|
||||
|
||||
stop_frontend_service() {
|
||||
if pgrep -f "${FRONTEND_VITE_ENTRY}" >/dev/null 2>&1 || [ -f "$FRONTEND_PID_FILE" ]; then
|
||||
if pgrep -f "${FRONTEND_VITE_ENTRY} .*--port ${DEFAULT_FRONTEND_PORT}" >/dev/null 2>&1 || [ -f "$FRONTEND_PID_FILE" ]; then
|
||||
cleanup_frontend_processes "$DEFAULT_FRONTEND_PORT"
|
||||
if [ -n "${FRONTEND_PORT:-}" ] && [ "$FRONTEND_PORT" != "$DEFAULT_FRONTEND_PORT" ]; then
|
||||
cleanup_frontend_processes "$FRONTEND_PORT"
|
||||
@@ -2183,11 +2310,39 @@ stop_frontend_service() {
|
||||
fi
|
||||
}
|
||||
|
||||
print_http_health_status() {
|
||||
local service_name="$1"
|
||||
local url="$2"
|
||||
|
||||
if http_ok "$url"; then
|
||||
echo -e "${DIM} ${service_name}:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} ${service_name}:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
}
|
||||
|
||||
print_process_health_status() {
|
||||
local service_name="$1"
|
||||
local pattern="$2"
|
||||
local pid_file="${3:-}"
|
||||
local tracked_pid=""
|
||||
|
||||
if [ -n "$pid_file" ]; then
|
||||
tracked_pid="$(read_pid_file "$pid_file" || true)"
|
||||
fi
|
||||
|
||||
if pgrep -f "$pattern" >/dev/null 2>&1 || { [ -n "$tracked_pid" ] && kill -0 "$tracked_pid" 2>/dev/null; }; then
|
||||
echo -e "${DIM} ${service_name}:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} ${service_name}:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
}
|
||||
|
||||
motion_agent_pids() {
|
||||
local pids=""
|
||||
|
||||
if [ -f "$MOTION_AGENT_PID_FILE" ]; then
|
||||
pids="$(cat "$MOTION_AGENT_PID_FILE" 2>/dev/null || true)"
|
||||
pids="$(read_pid_file "$MOTION_AGENT_PID_FILE" || true)"
|
||||
if [ -n "$pids" ] && kill -0 "$pids" 2>/dev/null; then
|
||||
printf "%s\n" "$pids"
|
||||
fi
|
||||
@@ -2206,7 +2361,7 @@ cleanup_motion_agent_processes() {
|
||||
terminate_process_tree "$signal" "$pid"
|
||||
done < <(motion_agent_pids | awk '!seen[$0]++')
|
||||
|
||||
rm -f "$MOTION_AGENT_PID_FILE"
|
||||
remove_pid_file "$MOTION_AGENT_PID_FILE"
|
||||
}
|
||||
|
||||
wait_for_motion_agent_ready() {
|
||||
@@ -2298,7 +2453,7 @@ start_motion_agent_service() {
|
||||
cd "$SCRIPT_DIR"
|
||||
nohup "$SCRIPT_DIR/.venv/bin/python" "${motion_args[@]}" > "$MOTION_AGENT_LOG_FILE" 2>&1 &
|
||||
MOTION_AGENT_PID=$!
|
||||
printf "%s" "$MOTION_AGENT_PID" > "$MOTION_AGENT_PID_FILE"
|
||||
write_pid_file "$MOTION_AGENT_PID_FILE" "$MOTION_AGENT_PID"
|
||||
|
||||
if wait_for_motion_agent_ready "$motion_agent_port" "$MOTION_AGENT_PID"; then
|
||||
log_success "Motion Agent 已就绪"
|
||||
@@ -2308,6 +2463,7 @@ start_motion_agent_service() {
|
||||
|
||||
log_error "Motion Agent 启动失败"
|
||||
tail -20 "$MOTION_AGENT_LOG_FILE" 2>/dev/null || true
|
||||
print_port_listener_details "$motion_agent_port"
|
||||
log_note "如只需验证 Web 端连接,可加 --motion-agent-dry-run。"
|
||||
log_note "如需真实摄像头识别,请确认系统存在 /dev/video*;脚本会自动发现,也可用 --motion-agent-camera-indexes 1,2 覆盖。"
|
||||
log_note "WSL 下也可用 --motion-agent-camera-urls rtsp://... 或 http://... 接入手机/网络摄像头。"
|
||||
@@ -2323,6 +2479,24 @@ stop_motion_agent_service() {
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup_failed_start() {
|
||||
[ "$START_RUN_ACTIVE" -eq 1 ] || return 0
|
||||
[ "$START_RUN_COMPLETED" -eq 0 ] || return 0
|
||||
|
||||
clear_wait_spinner
|
||||
log_warn "启动未完成,清理本轮已拉起的本地进程"
|
||||
|
||||
if [ "$STARTED_MOTION_AGENT_THIS_RUN" -eq 1 ]; then
|
||||
cleanup_motion_agent_processes TERM
|
||||
fi
|
||||
if [ "$STARTED_FRONTEND_THIS_RUN" -eq 1 ]; then
|
||||
cleanup_frontend_processes "${FRONTEND_PORT:-$DEFAULT_FRONTEND_PORT}"
|
||||
fi
|
||||
if [ "$STARTED_BACKEND_THIS_RUN" -eq 1 ]; then
|
||||
cleanup_backend_processes "${BACKEND_PORT:-$DEFAULT_BACKEND_PORT}" || true
|
||||
fi
|
||||
}
|
||||
|
||||
create_user() {
|
||||
local username
|
||||
local password
|
||||
@@ -2433,14 +2607,27 @@ start() {
|
||||
parse_service_args "$@"
|
||||
cleanup_exit_containers
|
||||
|
||||
START_RUN_ACTIVE=1
|
||||
START_RUN_COMPLETED=0
|
||||
STARTED_BACKEND_THIS_RUN=0
|
||||
STARTED_FRONTEND_THIS_RUN=0
|
||||
STARTED_MOTION_AGENT_THIS_RUN=0
|
||||
|
||||
print_splash
|
||||
|
||||
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"
|
||||
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"
|
||||
STARTED_MOTION_AGENT_THIS_RUN=1
|
||||
fi
|
||||
|
||||
write_port_state "$BACKEND_PORT" "$FRONTEND_PORT" "$AI_PROVIDER_PORT" "$MOTION_AGENT_PORT"
|
||||
START_RUN_COMPLETED=1
|
||||
START_RUN_ACTIVE=0
|
||||
|
||||
log_success "启动完成"
|
||||
log_note "智能星球计划: http://localhost:${FRONTEND_PORT}/earth"
|
||||
log_note "智能星球仪表盘: http://localhost:${FRONTEND_PORT}/admin"
|
||||
@@ -2468,6 +2655,10 @@ stop() {
|
||||
restart() {
|
||||
parse_service_args "$@"
|
||||
cleanup_exit_containers
|
||||
local state_backend_port=""
|
||||
local state_frontend_port=""
|
||||
local state_ai_provider_port=""
|
||||
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
|
||||
@@ -2506,6 +2697,24 @@ restart() {
|
||||
start_motion_agent_service "$MOTION_AGENT_PORT" "$MOTION_AGENT_DRY_RUN" "$FRONTEND_LAN_ENABLED"
|
||||
fi
|
||||
|
||||
state_backend_port="$(read_port_state_value BACKEND_PORT "$DEFAULT_BACKEND_PORT")"
|
||||
state_frontend_port="$(read_port_state_value FRONTEND_PORT "$DEFAULT_FRONTEND_PORT")"
|
||||
state_ai_provider_port="$(read_port_state_value AI_PROVIDER_PORT "$DEFAULT_AI_PROVIDER_PORT")"
|
||||
state_motion_agent_port="$(read_port_state_value MOTION_AGENT_PORT "$DEFAULT_MOTION_AGENT_PORT")"
|
||||
if [ "$BACKEND_PORT_REQUESTED" -eq 1 ]; then
|
||||
state_backend_port="$BACKEND_PORT"
|
||||
fi
|
||||
if [ "$FRONTEND_PORT_REQUESTED" -eq 1 ]; then
|
||||
state_frontend_port="$FRONTEND_PORT"
|
||||
fi
|
||||
if [ "$AI_PROVIDER_REQUESTED" -eq 1 ]; then
|
||||
state_ai_provider_port="$AI_PROVIDER_PORT"
|
||||
fi
|
||||
if [ "$MOTION_AGENT_REQUESTED" -eq 1 ]; then
|
||||
state_motion_agent_port="$MOTION_AGENT_PORT"
|
||||
fi
|
||||
write_port_state "$state_backend_port" "$state_frontend_port" "$state_ai_provider_port" "$state_motion_agent_port"
|
||||
|
||||
echo ""
|
||||
log_success "重启完成"
|
||||
if [ "$DATABASE_REQUESTED" -eq 1 ]; then
|
||||
@@ -2529,34 +2738,23 @@ restart() {
|
||||
}
|
||||
|
||||
health() {
|
||||
local backend_port=""
|
||||
local frontend_port=""
|
||||
local ai_provider_port=""
|
||||
|
||||
backend_port="$(read_port_state_value BACKEND_PORT "$DEFAULT_BACKEND_PORT")"
|
||||
frontend_port="$(read_port_state_value FRONTEND_PORT "$DEFAULT_FRONTEND_PORT")"
|
||||
ai_provider_port="$(read_port_state_value AI_PROVIDER_PORT "$DEFAULT_AI_PROVIDER_PORT")"
|
||||
|
||||
echo -e "${DIM}·${NC} ${BLUE}view${NC} ${WHITE}容器状态${NC}"
|
||||
docker ps --filter "name=planet_" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
|
||||
docker ps --filter "name=planet_" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || log_note "Docker daemon 不可用,跳过容器状态"
|
||||
|
||||
echo ""
|
||||
echo -e "${DIM}·${NC} ${BLUE}view${NC} ${WHITE}服务状态${NC}"
|
||||
if curl -s http://localhost:8000/health > /dev/null 2>&1; then
|
||||
echo -e "${DIM} 后端:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} 后端:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
|
||||
if curl -s "http://localhost:${DEFAULT_AI_PROVIDER_PORT}/health" > /dev/null 2>&1; then
|
||||
echo -e "${DIM} AI Provider:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} AI Provider:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
|
||||
if curl -s http://localhost:3000 > /dev/null 2>&1; then
|
||||
echo -e "${DIM} 前端:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} 前端:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
|
||||
if pgrep -f "python.*-m motion_agent" >/dev/null 2>&1 || [ -f "$MOTION_AGENT_PID_FILE" ]; then
|
||||
echo -e "${DIM} Motion Agent:${NC} ${GREEN}online${NC}"
|
||||
else
|
||||
echo -e "${DIM} Motion Agent:${NC} ${RED}offline${NC}"
|
||||
fi
|
||||
print_http_health_status "后端" "http://localhost:${backend_port}/health"
|
||||
print_http_health_status "AI Provider" "http://localhost:${ai_provider_port}/health"
|
||||
print_http_health_status "前端" "http://localhost:${frontend_port}"
|
||||
print_process_health_status "Motion Agent" "python.*-m motion_agent" "$MOTION_AGENT_PID_FILE"
|
||||
}
|
||||
|
||||
log() {
|
||||
@@ -2564,12 +2762,12 @@ log() {
|
||||
-f|--frontend)
|
||||
log_step "查看前端日志"
|
||||
log_note "按 Ctrl+C 退出"
|
||||
tail -f /tmp/planet_frontend.log
|
||||
tail -f "$FRONTEND_LOG_FILE"
|
||||
;;
|
||||
-b|--backend)
|
||||
log_step "查看后端日志"
|
||||
log_note "按 Ctrl+C 退出"
|
||||
tail -f /tmp/planet_backend.log
|
||||
tail -f "$BACKEND_LOG_FILE"
|
||||
;;
|
||||
-a|--ai-provider)
|
||||
log_step "查看 AI Provider 日志"
|
||||
@@ -2584,11 +2782,11 @@ log() {
|
||||
*)
|
||||
log_step "查看最近日志"
|
||||
log_note "后端"
|
||||
tail -20 /tmp/planet_backend.log 2>/dev/null || log_note "无日志"
|
||||
tail -20 "$BACKEND_LOG_FILE" 2>/dev/null || log_note "无日志"
|
||||
log_note "AI Provider"
|
||||
docker logs --tail 20 planet_aiprovider 2>/dev/null || log_note "无日志"
|
||||
log_note "前端"
|
||||
tail -20 /tmp/planet_frontend.log 2>/dev/null || log_note "无日志"
|
||||
tail -20 "$FRONTEND_LOG_FILE" 2>/dev/null || log_note "无日志"
|
||||
log_note "Motion Agent"
|
||||
tail -20 "$MOTION_AGENT_LOG_FILE" 2>/dev/null || log_note "无日志"
|
||||
;;
|
||||
@@ -2611,6 +2809,8 @@ parse_global_args() {
|
||||
GLOBAL_ARG_REMAINDER=("$@")
|
||||
}
|
||||
|
||||
trap cleanup_failed_start EXIT
|
||||
|
||||
parse_global_args "$@"
|
||||
set -- "${GLOBAL_ARG_REMAINDER[@]}"
|
||||
|
||||
@@ -2637,7 +2837,7 @@ case "$1" in
|
||||
;;
|
||||
*)
|
||||
log_error "用法: ./planet.sh {start|stop|restart|createuser|health|log}"
|
||||
log_note "全局参数: -v, --verbose 在当前执行行下方滚动显示最多 5 行命令输出"
|
||||
log_note "全局参数: -v, --verbose 在状态提示之间增量输出命令日志"
|
||||
log_note "start 启动服务,可选: -b <后端端口> -f <前端端口> -a <AI Provider 端口> -m/--motion-agent --motion-agent-port <端口> --motion-agent-camera-indexes 0,1 --motion-agent-camera-urls rtsp://... --motion-agent-dry-run --allow-lan --verbose"
|
||||
log_note "stop 停止服务"
|
||||
log_note "restart 重启服务,可选: -b [后端端口] -f [前端端口] -a [AI Provider 端口] -m [Motion Agent] -d --allow-lan --verbose"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "planet"
|
||||
version = "0.52.0"
|
||||
version = "0.56.0"
|
||||
description = "智能星球计划 - 态势感知系统"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
|
||||
Reference in new issue
Block a user