v 0.1.2
commit
e253c9608a
|
|
@ -0,0 +1,30 @@
|
|||
# 版本控制 / 本地环境
|
||||
.git
|
||||
.gitignore
|
||||
.venv
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Python 缓存
|
||||
**/__pycache__
|
||||
*.py[cod]
|
||||
.pytest_cache
|
||||
.ruff_cache
|
||||
|
||||
# 前端本地依赖与产物
|
||||
web/node_modules
|
||||
web/dist
|
||||
web/.vite
|
||||
web/tsconfig.tsbuildinfo
|
||||
|
||||
# 运行时数据:只保留码表种子,媒体/固件走挂载卷
|
||||
data/*
|
||||
!data/regions.json
|
||||
|
||||
# 文档与截图不需要进镜像
|
||||
docs
|
||||
README.md
|
||||
|
||||
# 系统文件
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
# ---- 运行环境 ----
|
||||
# 全部配置走环境变量/.env,不写进代码仓库(见 01-总体设计.md 第 8 节)
|
||||
APP_ENV=dev
|
||||
APP_VERSION=0.1.0
|
||||
|
||||
# ---- 端口(开发期) ----
|
||||
# scripts/dev.sh 起后端、vite 起前端都读这里。localhost 的 CORS 源会自动跟随
|
||||
# FRONTEND_PORT;手机/局域网访问走 Vite 代理,不需要额外配置 CORS。
|
||||
BACKEND_PORT=8100
|
||||
FRONTEND_PORT=5174
|
||||
|
||||
# ---- 数据库 ----
|
||||
DATABASE_URL=postgresql+asyncpg://postgres:sagacity@192.168.124.203:5432/nex_buddy
|
||||
|
||||
# ---- 缓存 ----
|
||||
REDIS_URL=redis://192.168.124.203:6379/9
|
||||
|
||||
# ---- 和风天气 ----
|
||||
# Key 直接可用;Host 是账号专属的,登录控制台 → 设置 复制(形如 abc1234xyz.re.qweatherapi.com)
|
||||
# 旧的 devapi/api.qweather.com 已返回 403 Invalid Host
|
||||
QWEATHER_KEY=HE2204271924421425
|
||||
QWEATHER_HOST=
|
||||
|
||||
# ---- 业务参数 ----
|
||||
SESSION_TTL_SECONDS=604800
|
||||
PAIR_CODE_TTL_SECONDS=600
|
||||
WEATHER_CACHE_SECONDS=1800
|
||||
DEFAULT_CITY=杭州
|
||||
|
||||
# ---- 资源目录 ----
|
||||
# 默认是项目根 data/;服务器/容器部署可指向宿主机挂载点
|
||||
# DATA_DIR=/srv/nex_buddy/data
|
||||
|
||||
# ---- Docker 部署(可选) ----
|
||||
# 宿主机资源目录(Compose 挂载到容器 /app/data),默认 ./data
|
||||
# NEX_BUDDY_DATA_DIR=/srv/nex_buddy/data
|
||||
# Web 对外端口,默认 80
|
||||
# HTTP_PORT=80
|
||||
# 仅 docker-deploy.sh --full 使用;请务必改掉默认口令
|
||||
# POSTGRES_DB=nex_buddy
|
||||
# POSTGRES_USER=nex_buddy
|
||||
# POSTGRES_PASSWORD=change-me
|
||||
# 构建加速(默认已用国内源,可覆盖)
|
||||
# PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
# APT_MIRROR=mirrors.tuna.tsinghua.edu.cn
|
||||
# NPM_REGISTRY=https://registry.npmmirror.com
|
||||
|
||||
# ---- CORS(一般不用配) ----
|
||||
# Web 与 API 同域部署(Nginx 反代 / 已配 WEB_BASE_URL)时不需要 CORS,
|
||||
# 保持不设置即可。只有 Web 与 API 确实不同域时才需要:
|
||||
# CORS_ORIGINS=https://app.example.com
|
||||
# 注意写完整源(协议 + 域名 + 端口),不要用 *。
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# ---- Python ----
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.ruff_cache/
|
||||
*.egg-info/
|
||||
|
||||
# ---- Node / 前端构建产物 ----
|
||||
web/node_modules/
|
||||
web/dist/
|
||||
web/.vite/
|
||||
web/*.local
|
||||
dist/
|
||||
build/
|
||||
|
||||
# ---- 配置与密钥 ----
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# ---- 运行时资源 ----
|
||||
# data/ 下是用户上传与固件包,默认不入库;
|
||||
# 部署时可整体挂载到宿主机磁盘(DATA_DIR 可覆盖默认路径)。
|
||||
/data/*
|
||||
!/data/regions.json
|
||||
|
||||
# ---- 系统 / 编辑器 ----
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
# nex_buddy · 服务平台
|
||||
|
||||
圆屏旋钮设备的服务端:账号、设备绑定、扫码登录、资料与星盘、天气、月度运势、TF 卡媒体同步、固件 OTA。
|
||||
配套文档:`../01-总体设计.md`(架构与决策)、`../03-服务端开发文档.md`(数据模型/接口/流程/排查)、
|
||||
`../04-Web前端开发规范.md`(页面与 UI 约定)、`../02-开发计划.md`(里程碑与待办)。
|
||||
|
||||
当前状态:M1–M4 完成,M5(音乐)缺副控真机联调;冒烟 `server/scripts/smoke.py` **71 项**全绿。
|
||||
|
||||
---
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
cd 01-开发工作区/服务平台/nex_buddy
|
||||
cp .env.example .env # 首次:填数据库/Redis/和风凭据
|
||||
./scripts/dev.sh # 后端:建 venv → alembic upgrade head → uvicorn :8100
|
||||
# 媒体、固件等运行时资源统一放在根目录 data/(可用 DATA_DIR 覆盖)
|
||||
|
||||
# 首次初始化:码表(3442 条行政区划 + 12 星座)、月度运势、管理员
|
||||
cd server
|
||||
../.venv/bin/python scripts/seed_catalog.py
|
||||
../.venv/bin/python scripts/seed_fortunes.py
|
||||
../.venv/bin/python scripts/create_admin.py --account admin@nexbuddy.com --password 'NexBuddy2026'
|
||||
|
||||
cd ../web && npm install && npm run dev # 前端 5174,/api 与 /device 代理到 8100(端口都在根 .env)
|
||||
```
|
||||
|
||||
- 前端 <http://127.0.0.1:5174>;接口文档 <http://127.0.0.1:8100/docs>
|
||||
- 健康检查 `GET /healthz` → `{ok, db, redis, weather_ready}`(设备配网页的「测试连通」就是打它)
|
||||
- 端到端自测:`cd server && ../.venv/bin/python scripts/smoke.py`
|
||||
会创建 `smoke*@test.local` 用户与 `SMOKE*` 设备,跑完按 `../03-服务端开发文档.md` §10.3 清理
|
||||
|
||||
> 管理员 `admin@nexbuddy.com` / `NexBuddy2026`(`create_admin.py` 生成,可重跑改口令)。
|
||||
> 设备默认服务端地址写在固件 `src/config/AppConfig.h` 的 `DEFAULT_SERVER_URL`,真机以 NVS 里的值为准。
|
||||
|
||||
---
|
||||
|
||||
## 服务器部署
|
||||
|
||||
脚本都在 `scripts/`,项目路径以 `/opt/nex_buddy` 为例:
|
||||
|
||||
直接部署需要:Python 3.12+、Node.js 18+、PostgreSQL、Redis、Nginx(数据库/Redis 也可用现成的远程实例)。
|
||||
Docker 部署只需要 Docker + Docker Compose,Python/Node 在镜像里构建。
|
||||
|
||||
```bash
|
||||
cd /opt/nex_buddy
|
||||
cp .env.example .env
|
||||
# 编辑 .env:APP_ENV=prod;DATABASE_URL / REDIS_URL 改成服务器地址;
|
||||
# 同域部署不用配 CORS_ORIGINS;如需把资源放到宿主机其他磁盘:
|
||||
# DATA_DIR=/srv/nex_buddy/data
|
||||
|
||||
./scripts/deploy.sh --init --no-restart # venv + 依赖 + 迁移 + 码表/运势 + 构建 web/dist
|
||||
|
||||
# 首次部署建管理员(可重跑改口令)
|
||||
cd server && ../.venv/bin/python scripts/create_admin.py \
|
||||
--account admin@nexbuddy.com --password '换成强口令'
|
||||
cd ..
|
||||
|
||||
sudo cp scripts/nex-buddy.service /etc/systemd/system/nex-buddy.service
|
||||
sudo vim /etc/systemd/system/nex-buddy.service # 改 User / WorkingDirectory
|
||||
sudo chown -R www-data:www-data data # 运行用户需要写媒体/固件目录
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now nex-buddy
|
||||
|
||||
sudo cp scripts/nginx-nex-buddy.conf /etc/nginx/sites-available/nex-buddy
|
||||
sudo vim /etc/nginx/sites-available/nex-buddy # 改 server_name / root
|
||||
sudo ln -s /etc/nginx/sites-available/nex-buddy /etc/nginx/sites-enabled/
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
- `scripts/deploy.sh`:默认安装依赖、执行迁移、构建前端;检测到 `nex-buddy.service` 时会自动重启并做 `/healthz` 健康检查。
|
||||
可选 `--init` / `--no-web` / `--no-migrate` / `--skip-install` / `--no-restart`。
|
||||
- `scripts/start.sh`:生产启动入口(`uvicorn --workers`,供 systemd 调用),不负责迁移和构建。
|
||||
- `scripts/dev.sh`:开发启动入口(带 `--reload`)。
|
||||
- Nginx 采用同域反代:`/` 出静态文件,`/api/`、`/device/`、`/healthz` 转给后端,因此浏览器不需要 CORS。
|
||||
- 运行时资源只有一个根:`data/`。部署时整体挂载或指向宿主机磁盘即可:
|
||||
`DATA_DIR=/srv/nex_buddy/data`,或容器里把宿主机目录挂到 `/app/data`。
|
||||
|
||||
### Docker 部署
|
||||
|
||||
不想在宿主机装 Python/Node 时用这套。默认使用 `.env` 里的外部 PostgreSQL/Redis;
|
||||
需要连数据库一起起时加 `--full`。
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# APP_ENV=prod;外部 DB/Redis 填 DATABASE_URL / REDIS_URL
|
||||
# 资源目录默认 ./data,也可 NEX_BUDDY_DATA_DIR=/srv/nex_buddy/data
|
||||
|
||||
./scripts/docker-deploy.sh # 已有 PG/Redis
|
||||
./scripts/docker-deploy.sh --full --init # 连 PG/Redis 一起起,并初始化码表
|
||||
|
||||
# 首次建管理员
|
||||
docker compose exec api python server/scripts/create_admin.py \
|
||||
--account admin@nexbuddy.com --password '强口令'
|
||||
```
|
||||
|
||||
- `data/` 会挂载到容器 `/app/data`,媒体、固件、码表都在这里。
|
||||
- 构建阶段 pip / npm / apt 默认走国内源,可用 `PIP_INDEX_URL`、`NPM_REGISTRY`、`APT_MIRROR` 覆盖;
|
||||
`docker pull` 的镜像加速见 `docker/README.md`。
|
||||
- `--full` 时先在 `.env` 修改 `POSTGRES_PASSWORD`,不要用默认口令。
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
```
|
||||
nex_buddy/
|
||||
├── .env / .env.example 配置(.env 不入库)
|
||||
├── .dockerignore
|
||||
├── docker-compose.yml API + Web(外部 DB/Redis)
|
||||
├── docker-compose.full.yml 可选:同时启动 PostgreSQL + Redis
|
||||
├── docker/ 镜像、Nginx、entrypoint 与 Docker 说明
|
||||
├── scripts/ 启动 / 部署 / systemd / Nginx 脚本
|
||||
├── data/ 运行时资源:regions.json + media/ + firmware/(媒体与固件不入库)
|
||||
├── server/
|
||||
│ ├── migrations/ Alembic 迁移(7 个版本,head 464bf9d382f4)
|
||||
│ ├── scripts/ smoke.py(71 项) / smoke_firmware.py / smoke_weblogin.py / seed_*.py / create_admin.py
|
||||
│ └── app/
|
||||
│ ├── main.py 路由挂载 + /healthz + 兜底异常处理
|
||||
│ ├── core/ config(.env 映射)、security(bcrypt/token/配对码)
|
||||
│ ├── db/ async engine 与 session
|
||||
│ ├── models/ user / device / firmware / media / region / zodiac / fortune / setting
|
||||
│ ├── schemas/ auth / catalog / firmware
|
||||
│ ├── api/ auth / devices / media / meta / admin / device_v1 / deps
|
||||
│ └── services/ astro / catalog / fortune / weather / firmware / media / redis_store
|
||||
└── web/ React + antd(Vite)
|
||||
└── src/ api.ts / theme.tsx / i18n.ts / styles.css / components / pages
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 页面
|
||||
|
||||
| 路由 | 内容 | 截图 |
|
||||
|---|---|---|
|
||||
| `/login` | 登录 / 注册(同一张卡,Segmented 切换) | `docs/shots/web-login.png` |
|
||||
| `/qr?t=<code>` | 扫码落地页:设备票据换会话,成功后跳个人页(不走登录守卫) | — |
|
||||
| `/bind` | 绑定页,支持 `?code=&did=` 预填 | `docs/shots/web-bind.png` |
|
||||
| `/` | 账号 → 我的设备 → TF 卡文件 / 个人资料(昵称·常住城市·时区)+ 出生信息与星盘(含本月运势) | `docs/shots/web-home.png` |
|
||||
| `/admin` | 六个页签:用户与设备、城市码表、星座码表、月度运势、固件管理、平台设置 | `docs/shots/admin-*.png`、`admin-users-mobile.png` |
|
||||
|
||||
细节与 UI 规则见 `../04-Web前端开发规范.md`;截图清单与四态(浅/深/英/移动)命名也在那里。
|
||||
|
||||
---
|
||||
|
||||
## 关键设计
|
||||
|
||||
**Redis 键**(db 9,完整表见 `03` §8)
|
||||
|
||||
| 键 | 用途 |
|
||||
|---|---|
|
||||
| `sess:<sha256(token)>` | Web 会话,value=user_id,7 天滑动 |
|
||||
| `dtoken:<device_id>:<sha256(secret)>` | 设备 token 白名单,解绑即删 |
|
||||
| `pair:<code>` / `pairtry:<code>` | 配对码(10 分钟)/ 防爆破计数(5 次/分钟) |
|
||||
| `wlogin:<code>` / `wlogin:dev:<device_id>` | 扫码票据(5 分钟、取出即删)/ 该设备最新一张 |
|
||||
| `weather:<city>` | 天气结果缓存(30 分钟) |
|
||||
| `cache:meta:*` | 码表/星座/运势缓存(1 小时,写操作即失效) |
|
||||
|
||||
**安全**
|
||||
|
||||
- 口令 bcrypt(cost 12),超 72 字节先截断;登录失败不区分"账号不存在/密码错";
|
||||
- token 只存哈希,库里没有任何明文凭证;
|
||||
- 设备 token 形如 `<device_id>:<secret>`,自带身份,解绑按前缀批量吊销;
|
||||
- 媒体预览允许 `?t=<token>`(`<img>`/`<audio>` 带不了头),仅在 `CurrentUserAny` 依赖里生效。
|
||||
|
||||
**天气(和风)**
|
||||
|
||||
- 配置优先级:平台设置(库)> `.env`,**直读库不缓存**;只有查询结果进 Redis;
|
||||
- Key 两种形态:32 位 Key 走 `X-QW-Api-Key`,JWT 走 `Authorization: Bearer`;
|
||||
- Host 是账号专属域名(`xxx.re.qweatherapi.com`),**不能由 Key 推导**;项目 ID(`HE…`)不是 Key;
|
||||
- 缺 Host/Key → 503 带指引;上游异常 → 502,不吞成 500。
|
||||
|
||||
**码表 / 时区 / 星盘**
|
||||
|
||||
- 地区即 GB/T 2260:省补 `0000`、地级市补 `00`、区县原样,共 3442 条;直辖市不重复一层(`changeOnSelect`);
|
||||
- 用户只存 code,展示名由服务端反查落一份;管理端改名只影响下次读取;
|
||||
- `users.timezone` 空则跟随常住地,再兜底 `Asia/Shanghai`;只影响"今天/本月",**星盘永远用出生地时区**;
|
||||
- 星盘用 pyswisseph 的 Moshier 解析式(无星历文件依赖),保存资料时算好落库;不填出生时间按当日 12:00 近似。
|
||||
|
||||
**运势**
|
||||
|
||||
- `fortunes` 两层:`scope='month'` 通用模板(每年复用)、`scope='ym'` 指定年月;取值顺序 ym → month → 内置模板;
|
||||
- 中英各一份,英文缺失回退中文;"本月"按居住时区判定,跨年不串月。
|
||||
|
||||
---
|
||||
|
||||
## 配置项
|
||||
|
||||
| 变量 | 说明 |
|
||||
|---|---|
|
||||
| `DATABASE_URL` | `postgresql+asyncpg://用户:口令@主机:5432/nex_buddy` |
|
||||
| `REDIS_URL` | `redis://主机:6379/9`(db 9 是项目专属库) |
|
||||
| `QWEATHER_KEY` / `QWEATHER_HOST` | 和风凭据;也可在管理端「平台设置」里改(库里优先) |
|
||||
| `WEB_BASE_URL` | 二维码里 Web 地址的**覆盖值**;空则按设备请求 Host 推导(同域部署不用配) |
|
||||
| `DATA_DIR` | 运行时资源根目录,默认项目根 `data/`;服务器/容器部署可指向宿主机挂载点 |
|
||||
| `BACKEND_PORT` / `FRONTEND_PORT` | 开发期端口(默认 8100 / 5174):`scripts/dev.sh` 与 `vite.config.ts` 都读它,改一处即可;localhost 的 CORS 源自动跟随 |
|
||||
| `CORS_ORIGINS` | **一般不用配**:同域部署不需要;仅 Web 与 API 分离域时设置,如 `https://app.example.com`。配了 `WEB_BASE_URL` 时其源会自动放行 |
|
||||
| `SESSION_TTL_SECONDS` / `PAIR_CODE_TTL_SECONDS` / `WEB_LOGIN_TTL_SECONDS` | 会话 7 天 / 配对码 10 分钟 / 扫码票据 5 分钟 |
|
||||
| `DEFAULT_CITY` | 用户没填城市时的兜底(默认杭州) |
|
||||
|
||||
---
|
||||
|
||||
## 已知问题
|
||||
|
||||
1. **Redis 快照写盘失败**(`rdb_last_bgsave_status=err`,`dir=/data`):已临时 `CONFIG SET stop-writes-on-bgsave-error no`(重启失效)。
|
||||
业务数据在 PG,丢快照只影响登录态;根治要在服务器查 `df -h /data` 与 Redis 日志。
|
||||
2. **开发机 IP 用 DHCP**:设备 `net.server` 与截图脚本里的地址会变,改配置以设备 NVS/命令行参数为准。
|
||||
3. **后端偶发事件循环卡死**(端口在听但请求超时):`lsof -i :8100` 找 PID → `kill -9` → 重新 `./scripts/dev.sh`;排查见 `03` §10。
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,44 @@
|
|||
# 可选覆盖文件:把 PostgreSQL / Redis 也交给 Compose 管理。
|
||||
# 用法:./scripts/docker-deploy.sh --full
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: "${POSTGRES_DB:-nex_buddy}"
|
||||
POSTGRES_USER: "${POSTGRES_USER:-nex_buddy}"
|
||||
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-change-me}"
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
|
||||
api:
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-nex_buddy}:${POSTGRES_PASSWORD:-change-me}@postgres:5432/${POSTGRES_DB:-nex_buddy}"
|
||||
REDIS_URL: "redis://redis:6379/9"
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
name: nex-buddy
|
||||
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.api
|
||||
args:
|
||||
APT_MIRROR: "${APT_MIRROR:-mirrors.tuna.tsinghua.edu.cn}"
|
||||
PIP_INDEX_URL: "${PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}"
|
||||
image: nex-buddy-api:latest
|
||||
init: true
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
DATA_DIR: /app/data
|
||||
FORWARDED_ALLOW_IPS: "*"
|
||||
WEB_CONCURRENCY: "${WEB_CONCURRENCY:-2}"
|
||||
volumes:
|
||||
- "${NEX_BUDDY_DATA_DIR:-./data}:/app/data"
|
||||
expose:
|
||||
- "8100"
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8100/healthz', timeout=3)"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
start_period: 30s
|
||||
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.web
|
||||
args:
|
||||
NPM_REGISTRY: "${NPM_REGISTRY:-https://registry.npmmirror.com}"
|
||||
image: nex-buddy-web:latest
|
||||
ports:
|
||||
- "${HTTP_PORT:-80}:80"
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
# syntax=docker/dockerfile:1
|
||||
FROM python:3.12-slim AS builder
|
||||
|
||||
# 国内构建加速:pip / apt 默认走清华源,可通过 build arg 覆盖。
|
||||
ARG APT_MIRROR=mirrors.tuna.tsinghua.edu.cn
|
||||
ARG PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
|
||||
ENV PIP_NO_CACHE_DIR=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PIP_DEFAULT_TIMEOUT=120
|
||||
|
||||
RUN set -eux; \
|
||||
if [ -n "$APT_MIRROR" ]; then \
|
||||
APT_HOST="${APT_MIRROR#http://}"; \
|
||||
APT_HOST="${APT_HOST#https://}"; \
|
||||
APT_HOST="${APT_HOST%/}"; \
|
||||
for f in /etc/apt/sources.list /etc/apt/sources.list.d/debian.sources; do \
|
||||
if [ -f "$f" ]; then \
|
||||
sed -i "s|deb.debian.org|${APT_HOST}|g; s|security.debian.org|${APT_HOST}|g" "$f"; \
|
||||
fi; \
|
||||
done; \
|
||||
fi; \
|
||||
apt-get update; \
|
||||
apt-get install -y --no-install-recommends build-essential libc6-dev; \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /build
|
||||
COPY requirements.txt .
|
||||
RUN python -m pip install --upgrade pip --index-url "$PIP_INDEX_URL" \
|
||||
&& python -m pip install --prefix=/install -r requirements.txt --index-url "$PIP_INDEX_URL"
|
||||
|
||||
|
||||
FROM python:3.12-slim AS runtime
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
DATA_DIR=/app/data
|
||||
|
||||
COPY --from=builder /install /usr/local
|
||||
|
||||
WORKDIR /app
|
||||
COPY server ./server
|
||||
COPY data/regions.json ./seed/regions.json
|
||||
COPY docker/api-entrypoint.sh /usr/local/bin/api-entrypoint
|
||||
|
||||
RUN chmod +x /usr/local/bin/api-entrypoint \
|
||||
&& mkdir -p /app/data/media /app/data/firmware
|
||||
|
||||
VOLUME ["/app/data"]
|
||||
EXPOSE 8100
|
||||
|
||||
ENTRYPOINT ["/usr/local/bin/api-entrypoint"]
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
# syntax=docker/dockerfile:1
|
||||
FROM node:20-alpine AS build
|
||||
|
||||
# npm 国内加速;可通过 build arg 覆盖。
|
||||
ARG NPM_REGISTRY=https://registry.npmmirror.com
|
||||
|
||||
WORKDIR /app/web
|
||||
COPY web/package.json web/package-lock.json ./
|
||||
RUN npm config set registry "$NPM_REGISTRY" \
|
||||
&& npm config set replace-registry-host always \
|
||||
&& npm ci --no-audit --no-fund
|
||||
|
||||
COPY web/ ./
|
||||
RUN npm run build
|
||||
|
||||
|
||||
FROM nginx:1.27-alpine
|
||||
|
||||
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /app/web/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
# Docker 部署
|
||||
|
||||
## 文件
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| `docker/Dockerfile.api` | FastAPI 镜像(多阶段构建) |
|
||||
| `docker/Dockerfile.web` | 前端构建 + Nginx 镜像 |
|
||||
| `docker/nginx.conf` | 容器内 Nginx:静态文件 + `/api`、`/device` 反代 |
|
||||
| `docker/api-entrypoint.sh` | 启动前创建数据目录、补 `regions.json`、执行迁移 |
|
||||
| `docker-compose.yml` | API + Web;数据库/Redis 使用 `.env` 中的外部实例 |
|
||||
| `docker-compose.full.yml` | 可选覆盖:同时启动 PostgreSQL + Redis |
|
||||
|
||||
## 国内下载加速
|
||||
|
||||
构建参数默认已经改成国内源,也可以在 `.env` 或命令行覆盖:
|
||||
|
||||
| 参数 | 默认值 | 用途 |
|
||||
|---|---|---|
|
||||
| `PIP_INDEX_URL` | `https://pypi.tuna.tsinghua.edu.cn/simple` | pip 包 |
|
||||
| `APT_MIRROR` | `mirrors.tuna.tsinghua.edu.cn` | Debian apt(仅构建阶段) |
|
||||
| `NPM_REGISTRY` | `https://registry.npmmirror.com` | npm 包 |
|
||||
|
||||
```bash
|
||||
# 临时换源构建
|
||||
PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple/ \
|
||||
APT_MIRROR=mirrors.aliyun.com \
|
||||
NPM_REGISTRY=https://registry.npmmirror.com \
|
||||
docker compose build
|
||||
```
|
||||
|
||||
Docker 镜像本身不在这里配置;如果 `docker pull` 慢,在宿主机
|
||||
`/etc/docker/daemon.json` 配镜像加速,然后重启 Docker:
|
||||
|
||||
```json
|
||||
{
|
||||
"registry-mirrors": ["https://docker.m.daocloud.io"]
|
||||
}
|
||||
```
|
||||
|
||||
镜像加速地址会变化,以当前可用的服务为准。
|
||||
|
||||
## 数据目录
|
||||
|
||||
容器内固定使用 `/app/data`,Compose 默认把宿主机 `./data` 挂进去:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- "${NEX_BUDDY_DATA_DIR:-./data}:/app/data"
|
||||
```
|
||||
|
||||
所以在 `.env` 里写绝对路径即可把资源放到独立磁盘:
|
||||
|
||||
```bash
|
||||
NEX_BUDDY_DATA_DIR=/srv/nex_buddy/data
|
||||
```
|
||||
|
||||
首次挂载空目录时,entrypoint 会把镜像内的 `regions.json` 复制进去;媒体和固件目录会自动创建。
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
DATA_DIR="${DATA_DIR:-/app/data}"
|
||||
mkdir -p "$DATA_DIR/media" "$DATA_DIR/firmware"
|
||||
|
||||
# 首次使用空目录挂载时,把镜像内置的码表种子放进去。
|
||||
if [ ! -f "$DATA_DIR/regions.json" ] && [ -f /app/seed/regions.json ]; then
|
||||
cp /app/seed/regions.json "$DATA_DIR/regions.json"
|
||||
fi
|
||||
|
||||
cd /app/server
|
||||
|
||||
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
|
||||
echo ">> alembic upgrade head"
|
||||
python -m alembic upgrade head
|
||||
fi
|
||||
|
||||
echo ">> uvicorn :${BACKEND_PORT:-8100} (workers=${WEB_CONCURRENCY:-2})"
|
||||
exec python -m uvicorn app.main:app \
|
||||
--host 0.0.0.0 \
|
||||
--port "${BACKEND_PORT:-8100}" \
|
||||
--workers "${WEB_CONCURRENCY:-2}" \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-*}"
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# 媒体上传上限:后端单文件最大 32MB
|
||||
client_max_body_size 40m;
|
||||
|
||||
# Docker 内置 DNS:api 容器重建后也能重新解析
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api_upstream http://api:8100;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass $api_upstream$request_uri;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
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 /device/ {
|
||||
proxy_pass $api_upstream$request_uri;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
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 = /healthz {
|
||||
proxy_pass $api_upstream$request_uri;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA 路由:刷新 /admin、/qr 等路径时回落到 index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
fastapi
|
||||
uvicorn[standard]
|
||||
sqlalchemy[asyncio]
|
||||
asyncpg
|
||||
alembic
|
||||
redis
|
||||
pydantic-settings
|
||||
httpx
|
||||
bcrypt
|
||||
python-multipart
|
||||
Pillow
|
||||
mutagen
|
||||
pyswisseph
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
# scripts
|
||||
|
||||
| 文件 | 用途 |
|
||||
|---|---|
|
||||
| `dev.sh` | 开发启动:建 venv(首次)→ `alembic upgrade head` → `uvicorn --reload` |
|
||||
| `start.sh` | 生产启动:只启动 uvicorn(`--workers`),供 systemd 调用 |
|
||||
| `deploy.sh` | 服务器部署:依赖 → 迁移 → 构建 Web → 重启服务 → 健康检查 |
|
||||
| `docker-deploy.sh` | Docker 部署:构建镜像 → 启动 Compose → 可选初始化码表 |
|
||||
| `nex-buddy.service` | systemd 模板,首次部署时改路径/运行用户 |
|
||||
| `nginx-nex-buddy.conf` | Nginx 同域反代模板(静态文件 + `/api`、`/device`) |
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
./scripts/dev.sh # 默认读 .env 的 BACKEND_PORT
|
||||
./scripts/dev.sh 8101 # 临时指定端口
|
||||
```
|
||||
|
||||
## 服务器部署
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# APP_ENV=prod;DATABASE_URL / REDIS_URL 改成服务器地址
|
||||
|
||||
./scripts/deploy.sh --init --no-restart # --init 仅在首次部署时需要
|
||||
cd server && ../.venv/bin/python scripts/create_admin.py \
|
||||
--account admin@nexbuddy.com --password '换成强口令'
|
||||
cd ..
|
||||
sudo cp scripts/nex-buddy.service /etc/systemd/system/
|
||||
sudo vim /etc/systemd/system/nex-buddy.service # 改 User / WorkingDirectory
|
||||
sudo chown -R www-data:www-data data # 与 service 的 User 保持一致
|
||||
sudo systemctl daemon-reload && sudo systemctl enable --now nex-buddy
|
||||
|
||||
sudo cp scripts/nginx-nex-buddy.conf /etc/nginx/sites-available/nex-buddy
|
||||
sudo vim /etc/nginx/sites-available/nex-buddy # 改 server_name / root
|
||||
sudo ln -s /etc/nginx/sites-available/nex-buddy /etc/nginx/sites-enabled/
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
之后更新代码只需重新执行 `./scripts/deploy.sh`(检测到 systemd 服务会自动重启并检查 `/healthz`)。
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
./scripts/docker-deploy.sh # 使用 .env 里的外部 PG/Redis
|
||||
./scripts/docker-deploy.sh --full --init # 连 PostgreSQL/Redis 一起起,并初始化码表
|
||||
```
|
||||
|
||||
镜像构建默认使用国内 pip/npm/apt 源;`PIP_INDEX_URL`、`NPM_REGISTRY`、`APT_MIRROR`
|
||||
可在 `.env` 或命令行覆盖。详细的镜像拉取加速与挂载说明见 `docker/README.md`。
|
||||
|
||||
## 资源目录
|
||||
|
||||
媒体、固件等运行时文件统一放在项目根 `data/`,只有 `regions.json` 入库,其余内容被 `.gitignore` 忽略。
|
||||
服务器或容器部署时把该目录挂到宿主机磁盘即可;也可以用 `DATA_DIR` 指向别的位置:
|
||||
|
||||
```bash
|
||||
DATA_DIR=/srv/nex_buddy/data
|
||||
```
|
||||
|
||||
## CORS
|
||||
|
||||
同域部署(Nginx 把 Web 和 API 放在同一个域名下)不需要 CORS,`.env` 里不用写 `CORS_ORIGINS`。
|
||||
只有 Web 与 API 确实不同域时才配置:
|
||||
|
||||
```bash
|
||||
CORS_ORIGINS=https://app.example.com
|
||||
```
|
||||
|
||||
如果已经配置了 `WEB_BASE_URL`,它的源会自动加入允许列表,通常不必再写 `CORS_ORIGINS`。
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
#!/usr/bin/env bash
|
||||
# 服务器部署:scripts/deploy.sh [选项]
|
||||
# 默认流程:创建/更新 venv → 安装依赖 → alembic upgrade → 构建 Web → 重启服务 → 健康检查。
|
||||
#
|
||||
# 选项:
|
||||
# --no-web 不安装/构建前端
|
||||
# --no-migrate 不执行数据库迁移
|
||||
# --skip-install 跳过 Python 依赖安装(依赖没变时可加快部署)
|
||||
# --no-restart 不重启 systemd 服务
|
||||
# --init 首次部署:额外导入城市/星座码表与通用月度运势
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
DO_WEB=1
|
||||
DO_MIGRATE=1
|
||||
DO_INSTALL=1
|
||||
DO_RESTART=1
|
||||
DO_INIT=0
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
服务器部署:scripts/deploy.sh [选项]
|
||||
默认流程:创建/更新 venv → 安装依赖 → alembic upgrade → 构建 Web → 重启服务 → 健康检查。
|
||||
|
||||
选项:
|
||||
--no-web 不安装/构建前端
|
||||
--no-migrate 不执行数据库迁移
|
||||
--skip-install 跳过 Python 依赖安装(依赖没变时可加快部署)
|
||||
--no-restart 不重启 systemd 服务
|
||||
--init 首次部署:额外导入城市/星座码表与通用月度运势
|
||||
EOF
|
||||
}
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-web) DO_WEB=0 ;;
|
||||
--no-migrate) DO_MIGRATE=0 ;;
|
||||
--skip-install) DO_INSTALL=0 ;;
|
||||
--no-restart) DO_RESTART=0 ;;
|
||||
--init) DO_INIT=1 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "未知参数:$arg(用 --help 查看用法)" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo "!! 缺少 .env:先执行 cp .env.example .env,并填写 DATABASE_URL / REDIS_URL / QWEATHER_*" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PYTHON="${PYTHON:-python3}"
|
||||
if ! command -v "$PYTHON" >/dev/null 2>&1; then
|
||||
echo "!! 找不到 $PYTHON,请先安装 Python 3.12+" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -x .venv/bin/python ]; then
|
||||
echo ">> 创建虚拟环境"
|
||||
"$PYTHON" -m venv .venv
|
||||
fi
|
||||
|
||||
if [ "$DO_INSTALL" = 1 ]; then
|
||||
echo ">> 安装 Python 依赖"
|
||||
.venv/bin/python -m pip install --upgrade pip
|
||||
.venv/bin/python -m pip install -r requirements.txt
|
||||
fi
|
||||
|
||||
if [ "$DO_MIGRATE" = 1 ]; then
|
||||
echo ">> 数据库迁移"
|
||||
(cd server && ../.venv/bin/python -m alembic upgrade head)
|
||||
fi
|
||||
|
||||
if [ "$DO_INIT" = 1 ]; then
|
||||
echo ">> 初始化码表与运势"
|
||||
(
|
||||
cd server
|
||||
../.venv/bin/python scripts/seed_catalog.py
|
||||
../.venv/bin/python scripts/seed_fortunes.py
|
||||
)
|
||||
fi
|
||||
|
||||
if [ "$DO_WEB" = 1 ]; then
|
||||
if ! command -v npm >/dev/null 2>&1; then
|
||||
echo "!! 找不到 npm,构建前端需要 Node.js 18+" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo ">> 安装并构建 Web"
|
||||
(
|
||||
cd web
|
||||
if [ -f package-lock.json ]; then
|
||||
npm ci
|
||||
else
|
||||
npm install
|
||||
fi
|
||||
npm run build
|
||||
)
|
||||
fi
|
||||
|
||||
PORT="$(grep -E '^BACKEND_PORT=' .env 2>/dev/null | tail -1 | cut -d= -f2 | tr -d '[:space:]' || true)"
|
||||
PORT="${PORT:-8100}"
|
||||
SERVICE_NAME="${SERVICE_NAME:-nex-buddy}"
|
||||
STARTED=0
|
||||
|
||||
if [ "$DO_RESTART" = 1 ]; then
|
||||
if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ] && command -v systemctl >/dev/null 2>&1; then
|
||||
echo ">> 重启服务 ${SERVICE_NAME}"
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
else
|
||||
sudo systemctl restart "$SERVICE_NAME"
|
||||
fi
|
||||
STARTED=1
|
||||
elif [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]; then
|
||||
echo "!! 已安装 ${SERVICE_NAME}.service,但当前环境没有 systemctl,跳过重启" >&2
|
||||
else
|
||||
echo ">> 未安装 systemd 单元 ${SERVICE_NAME}.service,跳过重启"
|
||||
echo " 首次部署:sudo cp scripts/nex-buddy.service /etc/systemd/system/${SERVICE_NAME}.service"
|
||||
echo " 然后按实际路径/用户修改 WorkingDirectory、User,再 systemctl enable --now ${SERVICE_NAME}"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$STARTED" = 1 ] && command -v curl >/dev/null 2>&1; then
|
||||
echo ">> 健康检查 http://127.0.0.1:${PORT}/healthz"
|
||||
for _ in $(seq 1 20); do
|
||||
if out="$(curl -fsS "http://127.0.0.1:${PORT}/healthz" 2>/dev/null)"; then
|
||||
echo "$out"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "!! 健康检查失败:确认服务已启动、端口 ${PORT} 正确" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ">> 部署完成"
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
#!/usr/bin/env bash
|
||||
# 开发期启动:scripts/dev.sh [端口]
|
||||
# 后端端口默认取 .env 的 BACKEND_PORT(没有就用 8100);命令行参数优先级更高。
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
PORT="${1:-}"
|
||||
if [ -z "$PORT" ]; then
|
||||
PORT="$(grep -E '^BACKEND_PORT=' .env 2>/dev/null | tail -1 | cut -d= -f2 | tr -d '[:space:]' || true)"
|
||||
PORT="${PORT:-8100}"
|
||||
fi
|
||||
|
||||
if [ ! -d .venv ]; then
|
||||
echo ">> 创建虚拟环境"
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip -q install -r requirements.txt
|
||||
fi
|
||||
|
||||
echo ">> 迁移数据库"
|
||||
(cd server && ../.venv/bin/python -m alembic upgrade head)
|
||||
|
||||
echo ">> 启动 http://0.0.0.0:${PORT} (文档 /docs)"
|
||||
cd server && exec ../.venv/bin/python -m uvicorn app.main:app --host 0.0.0.0 --port "$PORT" --reload
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
#!/usr/bin/env bash
|
||||
# Docker 部署:scripts/docker-deploy.sh [--full] [--init] [--no-build]
|
||||
# --full 同时启动 PostgreSQL / Redis(docker-compose.full.yml)
|
||||
# --init 首次部署:导入码表与通用月度运势
|
||||
# --no-build 跳过镜像构建,直接用已有镜像启动
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
FULL=0
|
||||
INIT=0
|
||||
BUILD=1
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Docker 部署:scripts/docker-deploy.sh [选项]
|
||||
--full 同时启动 PostgreSQL / Redis
|
||||
--init 首次部署:导入码表与通用月度运势
|
||||
--no-build 跳过镜像构建
|
||||
EOF
|
||||
}
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--full) FULL=1 ;;
|
||||
--init) INIT=1 ;;
|
||||
--no-build) BUILD=0 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) echo "未知参数:$arg(用 --help 查看用法)" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "!! 找不到 docker" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! docker compose version >/dev/null 2>&1; then
|
||||
echo "!! 需要 Docker Compose v2(docker compose)" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f .env ]; then
|
||||
echo "!! 缺少 .env:先执行 cp .env.example .env 并填写数据库/Redis/和风凭据" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
FILES=(-f docker-compose.yml)
|
||||
if [ "$FULL" = 1 ]; then
|
||||
FILES+=(-f docker-compose.full.yml)
|
||||
fi
|
||||
|
||||
if [ "$BUILD" = 1 ]; then
|
||||
echo ">> 构建镜像(pip/npm/apt 使用国内镜像源,可用 build arg 覆盖)"
|
||||
docker compose "${FILES[@]}" build
|
||||
fi
|
||||
|
||||
echo ">> 启动容器"
|
||||
docker compose "${FILES[@]}" up -d --wait
|
||||
|
||||
if [ "$INIT" = 1 ]; then
|
||||
echo ">> 初始化码表与运势"
|
||||
docker compose "${FILES[@]}" exec -T api python server/scripts/seed_catalog.py
|
||||
docker compose "${FILES[@]}" exec -T api python server/scripts/seed_fortunes.py
|
||||
fi
|
||||
|
||||
docker compose "${FILES[@]}" ps
|
||||
echo ">> 完成;首次建管理员:docker compose exec api python server/scripts/create_admin.py --account admin@nexbuddy.com --password '强口令'"
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
# systemd 模板:首次部署时改好路径和运行用户,再复制到 /etc/systemd/system/。
|
||||
#
|
||||
# sudo cp scripts/nex-buddy.service /etc/systemd/system/nex-buddy.service
|
||||
# sudo systemctl daemon-reload
|
||||
# sudo systemctl enable --now nex-buddy
|
||||
#
|
||||
# 服务只需要读 .env,不把密钥再抄一份到 systemd 里。
|
||||
|
||||
[Unit]
|
||||
Description=nex_buddy API
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/opt/nex_buddy
|
||||
ExecStart=/bin/bash /opt/nex_buddy/scripts/start.sh
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
UMask=0077
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
# Nginx 同域部署模板:Web 静态文件 + /api 与 /device 反代到 FastAPI。
|
||||
# 把 server_name、root 改成实际值;HTTPS 证书按需用 certbot 配置。
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name example.com;
|
||||
|
||||
root /opt/nex_buddy/web/dist;
|
||||
index index.html;
|
||||
|
||||
# 媒体上传上限:后端单文件最大 32MB
|
||||
client_max_body_size 40m;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:8100;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
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 /device/ {
|
||||
proxy_pass http://127.0.0.1:8100;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
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 = /healthz {
|
||||
proxy_pass http://127.0.0.1:8100;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# SPA 路由:刷新 /admin、/qr 等路径时回落到 index.html
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
#!/usr/bin/env bash
|
||||
# 生产启动:scripts/start.sh [端口]
|
||||
# 由 systemd/supervisor 调用;不建 venv、不跑迁移,部署阶段由 scripts/deploy.sh 完成。
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
PORT="${1:-}"
|
||||
if [ -z "$PORT" ]; then
|
||||
PORT="$(grep -E '^BACKEND_PORT=' .env 2>/dev/null | tail -1 | cut -d= -f2 | tr -d '[:space:]' || true)"
|
||||
PORT="${PORT:-8100}"
|
||||
fi
|
||||
|
||||
if [ ! -x .venv/bin/python ]; then
|
||||
echo "!! 未找到 .venv/bin/python,请先执行 scripts/deploy.sh" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
WORKERS="${WEB_CONCURRENCY:-2}"
|
||||
echo ">> 启动 http://0.0.0.0:${PORT}(workers=${WORKERS})"
|
||||
cd server && exec ../.venv/bin/python -m uvicorn app.main:app \
|
||||
--host "${HOST:-0.0.0.0}" \
|
||||
--port "$PORT" \
|
||||
--workers "$WORKERS" \
|
||||
--proxy-headers \
|
||||
--forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}"
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
[alembic]
|
||||
script_location = migrations
|
||||
prepend_sys_path = .
|
||||
version_path_separator = os
|
||||
# The real URL is loaded from .env by migrations/env.py; this is only a placeholder.
|
||||
sqlalchemy.url =
|
||||
|
||||
[post_write_hooks]
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
|
|
@ -0,0 +1,661 @@
|
|||
"""管理端:用户 / 设备 / 固件 / 平台设置 / 城市码表 / 星座码表 / 月度运势。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from app.api.deps import CurrentAdmin, SessionDep
|
||||
from app.core.config import settings
|
||||
from app.models import Device, Firmware, Fortune, PlatformSetting, Region, User, ZodiacSign
|
||||
from app.schemas.auth import AdminSettingIn, DeviceOut, OkOut, UserOut, user_out
|
||||
from app.schemas.catalog import FortuneIn, FortuneOut, FortunePatch, RegionIn, RegionPatch, ZodiacIn, ZodiacPatch
|
||||
from app.schemas.firmware import DeviceUpgradeOut, FirmwareOut, FirmwarePatch, RolloutIn, UpgradeIn
|
||||
from app.services import catalog, firmware, redis_store
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
# 内置标准码表(GB/T 2260 三级),管理端可一键补全
|
||||
SEED_PATH = settings.data_dir / "regions.json"
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
async def list_users(admin: CurrentAdmin, db: SessionDep) -> dict:
|
||||
users = (await db.execute(select(User).order_by(User.created_at.desc()))).scalars().all()
|
||||
devices = (await db.execute(select(Device).where(Device.bound_user_id.isnot(None)))).scalars().all()
|
||||
zmap = await catalog.zodiac_map(db)
|
||||
by_user: dict[uuid.UUID, list[DeviceOut]] = {}
|
||||
for d in devices:
|
||||
by_user.setdefault(d.bound_user_id, []).append(DeviceOut.model_validate(d))
|
||||
|
||||
return {
|
||||
"total": len(users),
|
||||
"items": [
|
||||
{**user_out(u, zmap).model_dump(mode="json"),
|
||||
"devices": [d.model_dump(mode="json") for d in by_user.get(u.id, [])]}
|
||||
for u in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/users/{user_id}/status", response_model=OkOut)
|
||||
async def set_user_status(user_id: uuid.UUID, status: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
if status not in ("active", "disabled"):
|
||||
raise HTTPException(400, "status must be active|disabled")
|
||||
user = await db.get(User, user_id)
|
||||
if user is None:
|
||||
raise HTTPException(404, "user not found")
|
||||
if user.id == admin.id and status == "disabled":
|
||||
raise HTTPException(400, "cannot disable yourself")
|
||||
|
||||
user.status = status
|
||||
await db.commit()
|
||||
|
||||
if status == "disabled":
|
||||
# 停用即失联:吊销其 Web 会话与所有设备 token
|
||||
await redis_store.revoke_sessions_of(str(user.id))
|
||||
for d in (await db.execute(select(Device).where(Device.bound_user_id == user.id))).scalars():
|
||||
await redis_store.revoke_device_tokens(str(d.id))
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 设备管理
|
||||
@router.delete("/devices/{device_id}", response_model=OkOut)
|
||||
async def unbind_device(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
"""管理员解绑设备:清掉绑定关系并吊销设备 token,设备下次开机需重新配对。"""
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
if device.bound_user_id is None:
|
||||
raise HTTPException(400, "device not bound")
|
||||
|
||||
device.bound_user_id = None
|
||||
device.bound_at = None
|
||||
await db.commit()
|
||||
await redis_store.revoke_device_tokens(str(device.id))
|
||||
return OkOut(ok=True, detail="已解绑")
|
||||
|
||||
|
||||
@router.post("/devices/{device_id}/revoke", response_model=OkOut)
|
||||
async def revoke_device(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
"""只吊销 token 不解绑:设备下次请求即 401,需重新走配对流程。"""
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
n = await redis_store.revoke_device_tokens(str(device.id))
|
||||
return OkOut(ok=True, detail=f"revoked {n} token(s)")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 固件管理
|
||||
def _fw_out(fw: Firmware, device_count: int = 0) -> dict:
|
||||
return FirmwareOut.model_validate(fw).model_copy(update={"device_count": device_count}).model_dump(mode="json")
|
||||
|
||||
|
||||
@router.get("/firmwares")
|
||||
async def list_firmwares(
|
||||
admin: CurrentAdmin,
|
||||
db: SessionDep,
|
||||
model: str | None = None,
|
||||
channel: str | None = Query(default=None, pattern="^(stable|beta)$"),
|
||||
) -> dict:
|
||||
stmt = select(Firmware)
|
||||
if model:
|
||||
stmt = stmt.where(Firmware.model == model)
|
||||
if channel:
|
||||
stmt = stmt.where(Firmware.channel == channel)
|
||||
rows = list((await db.execute(stmt.order_by(Firmware.version_code.desc()))).scalars().all())
|
||||
counts = await firmware.device_counts(db)
|
||||
return {
|
||||
"items": [_fw_out(fw, counts.get(fw.version, 0)) for fw in rows],
|
||||
"storage": firmware.env_storage_hint(),
|
||||
"max_size": firmware.MAX_SIZE,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/firmwares", response_model=OkOut)
|
||||
async def upload_firmware(
|
||||
admin: CurrentAdmin,
|
||||
db: SessionDep,
|
||||
file: UploadFile = File(..., description="xxx.ino.bin"),
|
||||
version: str = Form(..., description="0.1.2 / 0.2.0-rc1"),
|
||||
model: str = Form("JC3636K518C_I_W"),
|
||||
channel: str = Form("stable"),
|
||||
notes: str = Form(""),
|
||||
notes_en: str = Form(""),
|
||||
min_version: str = Form(""),
|
||||
publish: bool = Form(False),
|
||||
) -> OkOut:
|
||||
"""上传固件包。
|
||||
|
||||
校验顺序是「便宜的先做」:版本号 → 通道 → 唯一性 → 落盘算哈希 → 镜像头。
|
||||
这样传错文件时不用等 2 MB 都写完才报错(哈希必须读完,但重复版本能在最前面拦掉)。
|
||||
"""
|
||||
version = version.strip()
|
||||
channel = (channel or "stable").strip()
|
||||
if channel not in ("stable", "beta"):
|
||||
raise HTTPException(400, "channel 只能是 stable / beta")
|
||||
try:
|
||||
code = firmware.version_code(version)
|
||||
except firmware.FirmwareError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
if min_version:
|
||||
try:
|
||||
firmware.parse_version(min_version)
|
||||
except firmware.FirmwareError as exc:
|
||||
raise HTTPException(400, f"最低版本:{exc}") from exc
|
||||
|
||||
dup = await db.scalar(
|
||||
select(func.count()).select_from(Firmware).where(
|
||||
Firmware.model == model, Firmware.channel == channel, Firmware.version == version
|
||||
)
|
||||
)
|
||||
if dup:
|
||||
raise HTTPException(409, f"{model} / {channel} 通道已有 {version},先删掉旧包再传")
|
||||
|
||||
try:
|
||||
# 传 UploadFile 本身:它的 read() 是 async,save_stream 靠 await 流式读
|
||||
path, size, sha = await firmware.save_stream(file, file.filename or "firmware.bin")
|
||||
except firmware.FirmwareError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
fw = Firmware(
|
||||
model=model.strip(),
|
||||
version=version,
|
||||
version_code=code,
|
||||
channel=channel,
|
||||
size_bytes=size,
|
||||
sha256=sha,
|
||||
filename=path.name,
|
||||
original_name=(file.filename or "")[:160],
|
||||
notes=notes.strip(),
|
||||
notes_en=notes_en.strip(),
|
||||
min_version=min_version.strip(),
|
||||
published=bool(publish),
|
||||
created_by=admin.id,
|
||||
published_at=now if publish else None,
|
||||
)
|
||||
db.add(fw)
|
||||
await db.commit()
|
||||
return OkOut(ok=True, detail=f"已上传 {version}({size / 1024:.0f} KB,sha256 {sha[:8]}…)")
|
||||
|
||||
|
||||
@router.put("/firmwares/{firmware_id}", response_model=OkOut)
|
||||
async def update_firmware(firmware_id: uuid.UUID, body: FirmwarePatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
fw = await db.get(Firmware, firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("min_version"):
|
||||
try:
|
||||
firmware.parse_version(data["min_version"])
|
||||
except firmware.FirmwareError as exc:
|
||||
raise HTTPException(400, f"最低版本:{exc}") from exc
|
||||
|
||||
# 发布状态变化时补 published_at,方便列表按「上线时间」看
|
||||
if "published" in data and data["published"] != fw.published:
|
||||
fw.published_at = datetime.now(timezone.utc) if data["published"] else None
|
||||
for k, v in data.items():
|
||||
setattr(fw, k, v)
|
||||
await db.commit()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.delete("/firmwares/{firmware_id}", response_model=OkOut)
|
||||
async def delete_firmware(firmware_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
fw = await db.get(Firmware, firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
|
||||
# 有设备正指着这个包:要么等它升完,要么先取消下发,避免设备拿到 404
|
||||
target = await db.scalar(
|
||||
select(func.count()).select_from(Device).where(Device.target_firmware_id == fw.id)
|
||||
) or 0
|
||||
if target:
|
||||
raise HTTPException(400, f"还有 {target} 台设备的目标版本指向它,先取消下发再删")
|
||||
|
||||
firmware.remove_file(fw)
|
||||
await db.delete(fw)
|
||||
await db.commit()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.get("/firmwares/{firmware_id}/download")
|
||||
async def admin_download_firmware(firmware_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep):
|
||||
fw = await db.get(Firmware, firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
path = firmware.path_of(fw)
|
||||
if not path.exists():
|
||||
raise HTTPException(410, "firmware file missing on server")
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type="application/octet-stream",
|
||||
filename=f"knob_os-{fw.version}.bin",
|
||||
headers={"X-Firmware-Sha256": fw.sha256},
|
||||
)
|
||||
|
||||
|
||||
def _device_label(user: User | None) -> str:
|
||||
if user is None:
|
||||
return ""
|
||||
return user.nickname or user.email or user.phone or ""
|
||||
|
||||
|
||||
@router.get("/devices/upgrades")
|
||||
async def list_device_upgrades(admin: CurrentAdmin, db: SessionDep, q: str | None = None) -> dict:
|
||||
"""设备升级状态列表:一屏看清「谁在什么版本、有没有推、推成功没」。"""
|
||||
stmt = select(Device)
|
||||
rows = list((await db.execute(stmt.order_by(Device.last_active_at.desc().nullslast()))).scalars().all())
|
||||
|
||||
uid_by_device = {d.bound_user_id for d in rows if d.bound_user_id}
|
||||
users: dict[uuid.UUID, User] = {}
|
||||
if uid_by_device:
|
||||
for u in (await db.execute(select(User).where(User.id.in_(uid_by_device)))).scalars():
|
||||
users[u.id] = u
|
||||
|
||||
items = [
|
||||
DeviceUpgradeOut(
|
||||
id=d.id,
|
||||
chip_id=d.chip_id,
|
||||
model=d.model,
|
||||
fw_version=d.fw_version or "",
|
||||
target_version=d.target_version or "",
|
||||
upgrade_state=d.upgrade_state or "",
|
||||
upgrade_error=d.upgrade_error or "",
|
||||
upgrade_at=d.upgrade_at,
|
||||
boot_slot=d.boot_slot or "",
|
||||
fw_updated_at=d.fw_updated_at,
|
||||
bound_user_id=d.bound_user_id,
|
||||
user_label=_device_label(users.get(d.bound_user_id) if d.bound_user_id else None),
|
||||
last_active_at=d.last_active_at,
|
||||
).model_dump(mode="json")
|
||||
for d in rows
|
||||
]
|
||||
if q:
|
||||
like = q.strip().lower()
|
||||
items = [
|
||||
i for i in items
|
||||
if like in i["chip_id"].lower() or like in (i["user_label"] or "").lower()
|
||||
or like in (i["fw_version"] or "") or like in (i["target_version"] or "")
|
||||
]
|
||||
|
||||
counts = await firmware.device_counts(db)
|
||||
latest = await firmware.latest_published(db, "JC3636K518C_I_W")
|
||||
pending = sum(1 for d in rows if d.target_firmware_id)
|
||||
return {
|
||||
"total": len(rows),
|
||||
"by_version": counts,
|
||||
"latest": latest.version if latest else "",
|
||||
"pending": pending,
|
||||
"items": items,
|
||||
}
|
||||
|
||||
|
||||
async def _assign(device: Device, fw: Firmware) -> None:
|
||||
device.target_firmware_id = fw.id
|
||||
device.target_version = fw.version
|
||||
device.upgrade_state = "pending"
|
||||
device.upgrade_error = ""
|
||||
device.upgrade_at = datetime.now(timezone.utc)
|
||||
|
||||
|
||||
@router.post("/devices/{device_id}/upgrade", response_model=OkOut)
|
||||
async def push_upgrade(device_id: uuid.UUID, body: UpgradeIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
"""给单台设备点名下发。允许指定更低的版本(回滚)。"""
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
fw = await db.get(Firmware, body.firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
|
||||
await _assign(device, fw)
|
||||
await db.commit()
|
||||
return OkOut(ok=True, detail=f"已指定 {device.chip_id} 升级到 {fw.version}(设备下次检查更新时生效)")
|
||||
|
||||
|
||||
@router.delete("/devices/{device_id}/upgrade", response_model=OkOut)
|
||||
async def cancel_upgrade(device_id: uuid.UUID, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
device.target_firmware_id = None
|
||||
device.target_version = ""
|
||||
if device.upgrade_state in ("pending", "downloading"):
|
||||
device.upgrade_state = "canceled"
|
||||
await db.commit()
|
||||
return OkOut(ok=True, detail="已取消下发")
|
||||
|
||||
|
||||
@router.post("/firmwares/{firmware_id}/rollout", response_model=OkOut)
|
||||
async def rollout_firmware(firmware_id: uuid.UUID, body: RolloutIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
"""批量下发。
|
||||
|
||||
默认只推给「版本低于该包」的设备——不然给已经在新版本上的设备再推一遍,
|
||||
等于让它白下载 2 MB 然后回滚到同一版。
|
||||
"""
|
||||
fw = await db.get(Firmware, firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
if not fw.published and not body.device_ids:
|
||||
raise HTTPException(400, "该固件还没发布;批量下发前先发布,或指定具体设备")
|
||||
|
||||
stmt = select(Device)
|
||||
if body.device_ids:
|
||||
stmt = stmt.where(Device.id.in_(body.device_ids))
|
||||
devices = list((await db.execute(stmt)).scalars().all())
|
||||
|
||||
hit = 0
|
||||
for d in devices:
|
||||
if d.model and fw.model and d.model != fw.model:
|
||||
continue
|
||||
if not body.device_ids and firmware.compare(d.fw_version or "", fw.version) >= 0:
|
||||
continue
|
||||
await _assign(d, fw)
|
||||
hit += 1
|
||||
|
||||
await db.commit()
|
||||
return OkOut(ok=True, detail=f"已指定 {hit} 台设备升级到 {fw.version}(共匹配 {len(devices)} 台,设备下次检查更新时生效)")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 月度运势
|
||||
@router.get("/fortunes")
|
||||
async def list_fortunes(
|
||||
admin: CurrentAdmin,
|
||||
db: SessionDep,
|
||||
zodiac_code: str | None = None,
|
||||
scope: str | None = Query(default=None, pattern="^(month|ym)$"),
|
||||
year: int | None = Query(default=None, ge=2000, le=2100, description="按 ym 年过滤"),
|
||||
) -> dict:
|
||||
stmt = select(Fortune)
|
||||
if zodiac_code:
|
||||
stmt = stmt.where(Fortune.zodiac_code == zodiac_code)
|
||||
if scope:
|
||||
stmt = stmt.where(Fortune.scope == scope)
|
||||
if year:
|
||||
stmt = stmt.where(Fortune.period.like(f"{year}-%"))
|
||||
rows = list((await db.execute(stmt)).scalars().all())
|
||||
# 按黄经序排(白羊…双鱼),比按 code 字母序可读得多
|
||||
zmap = await catalog.zodiac_map(db)
|
||||
rows.sort(key=lambda f: (zmap.get(f.zodiac_code, {}).get("sort_order", 99), f.scope != "month", f.period))
|
||||
return {"items": [FortuneOut.model_validate(r).model_dump(mode="json") for r in rows]}
|
||||
|
||||
|
||||
@router.post("/fortunes", response_model=OkOut)
|
||||
async def create_fortune(body: FortuneIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
if not await db.get(ZodiacSign, body.zodiac_code):
|
||||
raise HTTPException(400, f"星座 {body.zodiac_code} 不在码表里")
|
||||
_check_period(body.scope, body.period)
|
||||
dup = await db.scalar(
|
||||
select(func.count()).select_from(Fortune).where(
|
||||
Fortune.zodiac_code == body.zodiac_code,
|
||||
Fortune.scope == body.scope,
|
||||
Fortune.period == body.period,
|
||||
)
|
||||
)
|
||||
if dup:
|
||||
raise HTTPException(409, "该星座该周期已有条目,走编辑")
|
||||
db.add(Fortune(**body.model_dump()))
|
||||
await db.commit()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.put("/fortunes/{fortune_id}", response_model=OkOut)
|
||||
async def update_fortune(fortune_id: int, body: FortunePatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
row = await db.get(Fortune, fortune_id)
|
||||
if row is None:
|
||||
raise HTTPException(404, "fortune not found")
|
||||
for k, v in body.model_dump(exclude_unset=True).items():
|
||||
setattr(row, k, v)
|
||||
await db.commit()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.delete("/fortunes/{fortune_id}", response_model=OkOut)
|
||||
async def delete_fortune(fortune_id: int, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
row = await db.get(Fortune, fortune_id)
|
||||
if row is None:
|
||||
raise HTTPException(404, "fortune not found")
|
||||
await db.delete(row)
|
||||
await db.commit()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
def _check_period(scope: str, period: str) -> None:
|
||||
if scope == "month":
|
||||
if not (len(period) == 2 and period.isdigit() and 1 <= int(period) <= 12):
|
||||
raise HTTPException(400, "month 的 period 必须是两位月份,如 '11'")
|
||||
else:
|
||||
parts = period.split("-")
|
||||
if len(parts) != 2 or not all(p.isdigit() for p in parts):
|
||||
raise HTTPException(400, "ym 的 period 必须是 '2026-11' 形式")
|
||||
y, m = int(parts[0]), int(parts[1])
|
||||
if not (2000 <= y <= 2100 and 1 <= m <= 12):
|
||||
raise HTTPException(400, "ym 超出范围")
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
async def get_settings(admin: CurrentAdmin, db: SessionDep) -> dict:
|
||||
rows = (await db.execute(select(PlatformSetting))).scalars().all()
|
||||
return {"items": [{"key": r.key, "value": r.value, "updated_at": r.updated_at.isoformat() if r.updated_at else None} for r in rows]}
|
||||
|
||||
|
||||
@router.put("/settings", response_model=OkOut)
|
||||
async def put_setting(body: AdminSettingIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
row = await db.get(PlatformSetting, body.key)
|
||||
if row is None:
|
||||
row = PlatformSetting(key=body.key, value=body.value, updated_by=admin.id)
|
||||
db.add(row)
|
||||
else:
|
||||
row.value = body.value
|
||||
row.updated_by = admin.id
|
||||
await db.commit()
|
||||
# 配置不入缓存,写完即生效;只需清掉可能已按旧配置取到的天气结果
|
||||
if body.key.startswith("qweather"):
|
||||
await redis_store.clear_weather_cache()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 城市码表
|
||||
@router.get("/regions")
|
||||
async def list_regions(
|
||||
admin: CurrentAdmin,
|
||||
db: SessionDep,
|
||||
q: str | None = None,
|
||||
level: int | None = None,
|
||||
parent_code: str | None = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(50, ge=1, le=500),
|
||||
) -> dict:
|
||||
stmt = select(Region)
|
||||
count_stmt = select(func.count()).select_from(Region)
|
||||
if q:
|
||||
like = f"%{q.strip()}%"
|
||||
cond = or_(Region.name.ilike(like), Region.code.ilike(like))
|
||||
stmt = stmt.where(cond)
|
||||
count_stmt = count_stmt.where(cond)
|
||||
if level:
|
||||
stmt = stmt.where(Region.level == level)
|
||||
count_stmt = count_stmt.where(Region.level == level)
|
||||
if parent_code:
|
||||
stmt = stmt.where(Region.parent_code == parent_code)
|
||||
count_stmt = count_stmt.where(Region.parent_code == parent_code)
|
||||
|
||||
total = await db.scalar(count_stmt) or 0
|
||||
rows = (
|
||||
await db.execute(
|
||||
stmt.order_by(Region.sort_order, Region.code).offset((page - 1) * page_size).limit(page_size)
|
||||
)
|
||||
).scalars().all()
|
||||
return {
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"items": [
|
||||
{
|
||||
"code": r.code, "name": r.name, "level": r.level, "parent_code": r.parent_code,
|
||||
"timezone": r.timezone, "enabled": r.enabled, "sort_order": r.sort_order,
|
||||
}
|
||||
for r in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/regions", response_model=OkOut)
|
||||
async def create_region(body: RegionIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
code = body.code.strip()
|
||||
if await db.get(Region, code):
|
||||
raise HTTPException(409, f"代码 {code} 已存在")
|
||||
if body.parent_code and not await db.get(Region, body.parent_code):
|
||||
raise HTTPException(400, "上级代码不存在")
|
||||
|
||||
max_sort = await db.scalar(select(func.max(Region.sort_order))) or 0
|
||||
db.add(Region(**{**body.model_dump(), "code": code, "sort_order": body.sort_order or max_sort + 1}))
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True, detail=f"已新增 {body.name}")
|
||||
|
||||
|
||||
@router.put("/regions/{code}", response_model=OkOut)
|
||||
async def update_region(code: str, body: RegionPatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
region = await db.get(Region, code)
|
||||
if region is None:
|
||||
raise HTTPException(404, "region not found")
|
||||
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("parent_code") and not await db.get(Region, data["parent_code"]):
|
||||
raise HTTPException(400, "上级代码不存在")
|
||||
for k, v in data.items():
|
||||
setattr(region, k, v)
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.delete("/regions/{code}", response_model=OkOut)
|
||||
async def delete_region(code: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
region = await db.get(Region, code)
|
||||
if region is None:
|
||||
raise HTTPException(404, "region not found")
|
||||
|
||||
children = await db.scalar(select(func.count()).select_from(Region).where(Region.parent_code == code)) or 0
|
||||
if children:
|
||||
raise HTTPException(400, f"还有 {children} 个下级地区,先删下级或改为停用")
|
||||
used = await db.scalar(
|
||||
select(func.count()).select_from(User).where(
|
||||
or_(User.birth_region_code == code, User.residence_region_code == code)
|
||||
)
|
||||
) or 0
|
||||
if used:
|
||||
raise HTTPException(400, f"有 {used} 位用户用到这个地区,建议改为停用(enabled=false)")
|
||||
|
||||
await db.delete(region)
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.post("/regions/import", response_model=OkOut)
|
||||
async def import_regions(
|
||||
admin: CurrentAdmin,
|
||||
db: SessionDep,
|
||||
mode: str = Query("missing", pattern="^(missing|upsert)$"),
|
||||
) -> OkOut:
|
||||
"""从内置 GB/T 2260 码表补数据。missing 只补缺的,upsert 覆盖同名手改。"""
|
||||
if not SEED_PATH.exists():
|
||||
raise HTTPException(500, "内置码表文件缺失")
|
||||
rows: list[dict[str, Any]] = json.loads(SEED_PATH.read_text("utf-8"))
|
||||
|
||||
existing = {r.code: r for r in (await db.execute(select(Region))).scalars().all()}
|
||||
added = updated = 0
|
||||
for row in rows:
|
||||
cur = existing.get(row["code"])
|
||||
if cur is None:
|
||||
db.add(Region(**row))
|
||||
added += 1
|
||||
elif mode == "upsert":
|
||||
cur.name = row["name"]
|
||||
cur.level = row["level"]
|
||||
cur.parent_code = row["parent_code"]
|
||||
cur.timezone = row["timezone"]
|
||||
cur.sort_order = row["sort_order"]
|
||||
updated += 1
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True, detail=f"新增 {added} 条,更新 {updated} 条")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 星座码表
|
||||
@router.get("/zodiacs")
|
||||
async def list_zodiacs(admin: CurrentAdmin, db: SessionDep) -> dict:
|
||||
rows = (
|
||||
await db.execute(select(ZodiacSign).order_by(ZodiacSign.sort_order))
|
||||
).scalars().all()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"code": z.code, "name_cn": z.name_cn, "name_en": z.name_en, "symbol": z.symbol,
|
||||
"element": z.element, "start_month": z.start_month, "start_day": z.start_day,
|
||||
"end_month": z.end_month, "end_day": z.end_day, "intro": z.intro,
|
||||
"sort_order": z.sort_order, "enabled": z.enabled,
|
||||
"date_range": f"{z.start_month:02d}-{z.start_day:02d} ~ {z.end_month:02d}-{z.end_day:02d}",
|
||||
}
|
||||
for z in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.post("/zodiacs", response_model=OkOut)
|
||||
async def create_zodiac(body: ZodiacIn, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
if await db.get(ZodiacSign, body.code):
|
||||
raise HTTPException(409, f"代码 {body.code} 已存在")
|
||||
if await db.scalar(select(func.count()).select_from(ZodiacSign).where(ZodiacSign.sort_order == body.sort_order)):
|
||||
raise HTTPException(400, f"黄经序号 {body.sort_order} 已被占用(0 白羊 … 11 双鱼)")
|
||||
db.add(ZodiacSign(**body.model_dump()))
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.put("/zodiacs/{code}", response_model=OkOut)
|
||||
async def update_zodiac(code: str, body: ZodiacPatch, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
sign = await db.get(ZodiacSign, code)
|
||||
if sign is None:
|
||||
raise HTTPException(404, "sign not found")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
new_order = data.get("sort_order")
|
||||
if new_order is not None and new_order != sign.sort_order:
|
||||
clash = await db.scalar(
|
||||
select(func.count()).select_from(ZodiacSign).where(ZodiacSign.sort_order == new_order)
|
||||
)
|
||||
if clash:
|
||||
raise HTTPException(400, f"黄经序号 {new_order} 已被占用")
|
||||
for k, v in data.items():
|
||||
setattr(sign, k, v)
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.delete("/zodiacs/{code}", response_model=OkOut)
|
||||
async def delete_zodiac(code: str, admin: CurrentAdmin, db: SessionDep) -> OkOut:
|
||||
sign = await db.get(ZodiacSign, code)
|
||||
if sign is None:
|
||||
raise HTTPException(404, "sign not found")
|
||||
used = await db.scalar(
|
||||
select(func.count()).select_from(User).where(or_(User.sun_sign == code, User.moon_sign == code))
|
||||
) or 0
|
||||
if used:
|
||||
raise HTTPException(400, f"有 {used} 位用户的星盘用到它,建议停用而不是删除")
|
||||
await db.delete(sign)
|
||||
await db.commit()
|
||||
await catalog.invalidate()
|
||||
return OkOut(ok=True)
|
||||
|
|
@ -0,0 +1,199 @@
|
|||
"""账号:注册 / 登录 / 登出 / 资料。会话 token 白名单式存 Redis。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, status
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.api.deps import CurrentUser, SessionDep
|
||||
from app.core.security import (
|
||||
hash_password,
|
||||
new_token,
|
||||
normalize_web_login_code,
|
||||
token_hash,
|
||||
verify_password,
|
||||
)
|
||||
from app.models import User
|
||||
from app.schemas.auth import (
|
||||
LoginIn,
|
||||
LoginOut,
|
||||
OkOut,
|
||||
ProfileIn,
|
||||
QrLoginIn,
|
||||
RegisterIn,
|
||||
UserOut,
|
||||
user_out,
|
||||
)
|
||||
from app.services import astro, catalog, redis_store
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
|
||||
def _split_account(account: str) -> tuple[str | None, str | None]:
|
||||
a = account.strip()
|
||||
if "@" in a:
|
||||
return a.lower(), None
|
||||
digits = "".join(ch for ch in a if ch.isdigit() or ch == "+")
|
||||
return None, digits or None
|
||||
|
||||
|
||||
@router.post("/auth/register", response_model=LoginOut, status_code=status.HTTP_201_CREATED)
|
||||
async def register(body: RegisterIn, db: SessionDep) -> LoginOut:
|
||||
email, phone = _split_account(body.account)
|
||||
if not email and not phone:
|
||||
raise HTTPException(400, "account must be an email or a phone number")
|
||||
|
||||
exists = await db.scalar(
|
||||
select(func.count()).select_from(User).where(
|
||||
(User.email == email) if email else (User.phone == phone)
|
||||
)
|
||||
)
|
||||
if exists:
|
||||
raise HTTPException(409, "account already registered")
|
||||
|
||||
# 第一个注册者成为管理员,省掉手工改库引导(后续可在管理端增删)
|
||||
total = await db.scalar(select(func.count()).select_from(User)) or 0
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
phone=phone,
|
||||
password_hash=hash_password(body.password),
|
||||
nickname=body.nickname or (email.split("@")[0] if email else f"用户{phone[-4:]}"),
|
||||
role="admin" if total == 0 else "user",
|
||||
)
|
||||
db.add(user)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
token = new_token()
|
||||
await redis_store.save_session(token_hash(token), str(user.id))
|
||||
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
||||
|
||||
|
||||
@router.post("/auth/login", response_model=LoginOut)
|
||||
async def login(body: LoginIn, db: SessionDep) -> LoginOut:
|
||||
email, phone = _split_account(body.account)
|
||||
user = await db.scalar(
|
||||
select(User).where((User.email == email) if email else (User.phone == phone))
|
||||
)
|
||||
# 统一错误文案,不暴露账号是否存在
|
||||
if user is None or not verify_password(body.password, user.password_hash):
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "account or password incorrect")
|
||||
if user.status != "active":
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
|
||||
|
||||
token = new_token()
|
||||
await redis_store.save_session(token_hash(token), str(user.id))
|
||||
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
||||
|
||||
|
||||
@router.post("/auth/qr-login", response_model=LoginOut)
|
||||
async def qr_login(body: QrLoginIn, db: SessionDep) -> LoginOut:
|
||||
"""设备屏上二维码换会话:免密登录到该设备的绑定账号。
|
||||
|
||||
票据一码一用(取出即删),有效期 5 分钟;这样即使二维码被旁人拍到,
|
||||
也只有第一个打开的人能用,设备重开二维码会立刻换新码。
|
||||
"""
|
||||
code = normalize_web_login_code(body.code)
|
||||
payload = await redis_store.pop_web_login(code) if code else None
|
||||
if not payload:
|
||||
raise HTTPException(
|
||||
status.HTTP_401_UNAUTHORIZED,
|
||||
"二维码已失效,请在设备上重新打开",
|
||||
)
|
||||
|
||||
user = await db.get(User, payload.get("user_id", ""))
|
||||
if user is None or user.status != "active":
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
|
||||
|
||||
token = new_token()
|
||||
await redis_store.save_session(token_hash(token), str(user.id))
|
||||
return LoginOut(token=token, user=user_out(user, await catalog.zodiac_map(db)))
|
||||
|
||||
|
||||
@router.post("/auth/logout", response_model=OkOut)
|
||||
async def logout(authorization: Annotated[str | None, Header()] = None) -> OkOut:
|
||||
"""只清当前这条会话;同一账号在其它设备上的登录不受影响。"""
|
||||
raw = (authorization or "").strip()
|
||||
if raw.lower().startswith("bearer "):
|
||||
await redis_store.drop_session(token_hash(raw[7:].strip()))
|
||||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.get("/user/profile", response_model=UserOut)
|
||||
async def get_profile(user: CurrentUser, db: SessionDep) -> UserOut:
|
||||
return user_out(user, await catalog.zodiac_map(db))
|
||||
|
||||
|
||||
@router.put("/user/profile", response_model=UserOut)
|
||||
async def update_profile(body: ProfileIn, user: CurrentUser, db: SessionDep) -> UserOut:
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
|
||||
# 出生地/居住地:入参是码表 code,名字由码表反查后落库,前端不传名字
|
||||
birth_code_changed = "birth_region_code" in data
|
||||
if birth_code_changed:
|
||||
code = data.pop("birth_region_code")
|
||||
if code:
|
||||
city, place, _tz = await catalog.resolve_place(db, code)
|
||||
if place is None:
|
||||
raise HTTPException(400, "出生城市不在码表里")
|
||||
user.birth_region_code = code
|
||||
user.birth_city = city
|
||||
user.birth_place = place
|
||||
else:
|
||||
user.birth_region_code = None
|
||||
user.birth_city = None
|
||||
user.birth_place = None
|
||||
|
||||
if "residence_region_code" in data:
|
||||
code = data.pop("residence_region_code")
|
||||
if code:
|
||||
city, place, _tz = await catalog.resolve_place(db, code)
|
||||
if place is None:
|
||||
raise HTTPException(400, "居住城市不在码表里")
|
||||
user.residence_region_code = code
|
||||
user.residence_city = city
|
||||
user.residence_place = place
|
||||
else:
|
||||
user.residence_region_code = None
|
||||
user.residence_city = None
|
||||
user.residence_place = None
|
||||
|
||||
# 居住时区:必须是合法 IANA 名;星盘不受它影响(星盘用出生地时区)
|
||||
if "timezone" in data:
|
||||
tz = data["timezone"]
|
||||
if tz:
|
||||
try:
|
||||
ZoneInfo(tz)
|
||||
except ZoneInfoNotFoundError:
|
||||
raise HTTPException(400, f"未知时区:{tz}") from None
|
||||
user.timezone = tz or None
|
||||
|
||||
for k, v in data.items():
|
||||
setattr(user, k, v)
|
||||
|
||||
# 星盘:日期/时间/出生地任一变化都重算;没生日就清空
|
||||
if user.birthday is None:
|
||||
user.sun_sign = user.moon_sign = None
|
||||
user.sun_degree = user.moon_degree = None
|
||||
elif birth_code_changed or "birthday" in data or "birth_time" in data or not user.sun_sign:
|
||||
await _recompute_astro(db, user)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
return user_out(user, await catalog.zodiac_map(db))
|
||||
|
||||
|
||||
async def _recompute_astro(db, user: User) -> None:
|
||||
"""月亮走得太快,时区差一小时就可能跨星座,所以强调「出生地」而不是「现在所在地」。"""
|
||||
tz = "Asia/Shanghai"
|
||||
if user.birth_region_code:
|
||||
_, _, tz = await catalog.resolve_place(db, user.birth_region_code)
|
||||
result = astro.compute(user.birthday, user.birth_time, tz)
|
||||
user.sun_sign = result.sun_sign
|
||||
user.moon_sign = result.moon_sign
|
||||
user.sun_degree = result.sun_degree
|
||||
user.moon_degree = result.moon_degree
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
"""鉴权依赖:Web 会话 token、设备 token。
|
||||
|
||||
两种 token 都只把 sha256 存进 Redis,库里不留凭证。
|
||||
设备 token 形如 ``<device_id>:<secret>``,自带设备标识,省一个请求头。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, Query, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import token_hash
|
||||
from app.db.session import get_session
|
||||
from app.models import Device, User
|
||||
from app.services import redis_store
|
||||
|
||||
SessionDep = Annotated[AsyncSession, Depends(get_session)]
|
||||
|
||||
|
||||
def _bearer(authorization: str | None) -> str:
|
||||
if not authorization or not authorization.lower().startswith("bearer "):
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
return authorization[7:].strip()
|
||||
|
||||
|
||||
async def current_user(
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
db: AsyncSession = Depends(get_session),
|
||||
) -> User:
|
||||
token = _bearer(authorization)
|
||||
uid = await redis_store.load_session(token_hash(token))
|
||||
if not uid:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
|
||||
|
||||
user = await db.get(User, uid)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "user not found")
|
||||
if user.status != "active":
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
|
||||
return user
|
||||
|
||||
|
||||
async def current_admin(user: User = Depends(current_user)) -> User:
|
||||
if user.role != "admin":
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "admin only")
|
||||
return user
|
||||
|
||||
|
||||
async def current_device(
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
db: AsyncSession = Depends(get_session),
|
||||
) -> Device:
|
||||
raw = _bearer(authorization)
|
||||
device_id, _, secret = raw.partition(":")
|
||||
if not device_id or not secret:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "malformed device token")
|
||||
|
||||
if not await redis_store.load_device_token(device_id, token_hash(secret)):
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device token rejected")
|
||||
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device unknown")
|
||||
return device
|
||||
|
||||
|
||||
CurrentUser = Annotated[User, Depends(current_user)]
|
||||
CurrentAdmin = Annotated[User, Depends(current_admin)]
|
||||
CurrentDevice = Annotated[Device, Depends(current_device)]
|
||||
|
||||
|
||||
async def current_user_any(
|
||||
t: Annotated[str | None, Query(description="token(媒体预览用,<img>/<audio> 带不了头)")] = None,
|
||||
authorization: Annotated[str | None, Header()] = None,
|
||||
db: AsyncSession = Depends(get_session),
|
||||
) -> User:
|
||||
"""接受 ``?t=<token>`` 或 Authorization 头的用户鉴权。
|
||||
|
||||
``<img src>`` / ``<audio src>`` 没法加请求头,媒体预览只能把 token 放 query。
|
||||
只给「读自己媒体文件」这一条路径用,别扩散——URL 里的 token 会进日志和
|
||||
Referer,风险面比头大。
|
||||
"""
|
||||
token = t or (_bearer(authorization) if authorization else None)
|
||||
if not token:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing token")
|
||||
|
||||
uid = await redis_store.load_session(token_hash(token))
|
||||
if not uid:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
|
||||
user = await db.get(User, uid)
|
||||
if user is None or user.status != "active":
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "account unavailable")
|
||||
return user
|
||||
|
||||
|
||||
CurrentUserAny = Annotated[User, Depends(current_user_any)]
|
||||
|
||||
|
||||
async def user_of_device(device: Device, db: AsyncSession) -> User | None:
|
||||
if not device.bound_user_id:
|
||||
return None
|
||||
return (await db.execute(select(User).where(User.id == device.bound_user_id))).scalar_one_or_none()
|
||||
|
|
@ -0,0 +1,517 @@
|
|||
"""设备端接口 ``/device/v1``:配对码、换 token、资料、天气、星盘、固件升级。
|
||||
|
||||
约定:除 ``pair/*`` 外全部要求 ``Authorization: Bearer <device_id>:<secret>``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request, status
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.api.deps import CurrentDevice, SessionDep, user_of_device
|
||||
from app.core.config import settings
|
||||
from app.core.security import (
|
||||
new_pair_code,
|
||||
new_token,
|
||||
new_web_login_code,
|
||||
normalize_pair_code,
|
||||
token_hash,
|
||||
)
|
||||
from app.models import Device, Firmware, MediaFile, User
|
||||
from app.schemas.auth import (
|
||||
PairClaimIn,
|
||||
PairClaimOut,
|
||||
PairCodeIn,
|
||||
PairCodeOut,
|
||||
PairStatusOut,
|
||||
UserOut,
|
||||
user_out,
|
||||
)
|
||||
from app.schemas.firmware import CheckOut
|
||||
from app.services import catalog, firmware, fortune, media, redis_store, weather
|
||||
|
||||
router = APIRouter(prefix="/device/v1", tags=["device"])
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
@router.post("/pair/code", response_model=PairCodeOut)
|
||||
async def issue_pair_code(body: PairCodeIn, db: SessionDep) -> PairCodeOut:
|
||||
"""设备开机进绑定页时调用:登记芯片指纹并拿到 6 位码。
|
||||
|
||||
码可以由设备自己生成(屏显逻辑在固件侧),也可以让服务端生成——
|
||||
服务端生成的好处是不可预测、便于限流。
|
||||
"""
|
||||
chip_id = body.chip_id.strip().upper()
|
||||
if len(chip_id) < 12:
|
||||
raise HTTPException(400, "chip_id too short")
|
||||
|
||||
device = await db.scalar(select(Device).where(Device.chip_id == chip_id))
|
||||
if device is None:
|
||||
device = Device(chip_id=chip_id, model=body.model, fw_version=body.fw_version)
|
||||
db.add(device)
|
||||
await db.commit()
|
||||
await db.refresh(device)
|
||||
elif body.fw_version and device.fw_version != body.fw_version:
|
||||
device.fw_version = body.fw_version
|
||||
await db.commit()
|
||||
|
||||
if device.bound_user_id:
|
||||
raise HTTPException(409, "device already bound; unbind it in the web portal first")
|
||||
|
||||
code = normalize_pair_code(body.code or "") or new_pair_code()
|
||||
if len(code) != 6:
|
||||
raise HTTPException(400, "pairing code must be 6 digits")
|
||||
|
||||
await redis_store.put_pair(
|
||||
code,
|
||||
{"device_id": str(device.id), "chip_id": chip_id},
|
||||
ttl=settings.pair_code_ttl_seconds,
|
||||
)
|
||||
return PairCodeOut(code=code, expires_in=settings.pair_code_ttl_seconds, server_time=_now_iso())
|
||||
|
||||
|
||||
@router.get("/pair/status", response_model=PairStatusOut)
|
||||
async def pair_status(
|
||||
code: str = Query(..., min_length=6, max_length=6),
|
||||
chip_id: str = Query(...),
|
||||
) -> PairStatusOut:
|
||||
"""绑定页内每 5 秒检查一次(不属全局轮询)。"""
|
||||
code = normalize_pair_code(code)
|
||||
payload = await redis_store.get_pair(code)
|
||||
if not payload:
|
||||
# 码已经消费完(claim 之后)也算已绑定,但正常流程不会走到这里
|
||||
return PairStatusOut(status="expired")
|
||||
if payload.get("chip_id") and payload["chip_id"].upper() != chip_id.strip().upper():
|
||||
raise HTTPException(403, "code does not belong to this device")
|
||||
if payload.get("bound_user_id"):
|
||||
return PairStatusOut(status="bound")
|
||||
return PairStatusOut(status="waiting")
|
||||
|
||||
|
||||
@router.post("/pair/claim", response_model=PairClaimOut)
|
||||
async def pair_claim(body: PairClaimIn, db: SessionDep) -> PairClaimOut:
|
||||
"""码被网页消费后 2 分钟内,设备凭码换长期 token。"""
|
||||
code = normalize_pair_code(body.code)
|
||||
payload = await redis_store.get_pair(code)
|
||||
if not payload:
|
||||
raise HTTPException(404, "code expired")
|
||||
|
||||
chip_id = body.chip_id.strip().upper()
|
||||
if payload.get("chip_id", "").upper() != chip_id:
|
||||
raise HTTPException(403, "code does not belong to this device")
|
||||
|
||||
user_id = payload.get("bound_user_id")
|
||||
if not user_id:
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "code not claimed by any account yet")
|
||||
|
||||
device = await db.get(Device, payload["device_id"])
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
|
||||
user = await db.get(User, user_id)
|
||||
if user is None or user.status != "active":
|
||||
raise HTTPException(403, "account unavailable")
|
||||
|
||||
# 一码一机:换 token 同时作废旧 token
|
||||
await redis_store.revoke_device_tokens(str(device.id))
|
||||
secret = new_token()
|
||||
await redis_store.save_device_token(str(device.id), token_hash(secret))
|
||||
await redis_store.consume_pair(code)
|
||||
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
return PairClaimOut(
|
||||
token=f"{device.id}:{secret}",
|
||||
device_id=device.id,
|
||||
user=user_out(user, await catalog.zodiac_map(db)),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
async def ping(device: CurrentDevice, db: SessionDep) -> dict:
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return {"ok": True, "ts": _now_iso()}
|
||||
|
||||
|
||||
@router.get("/profile", response_model=UserOut)
|
||||
async def profile(device: CurrentDevice, db: SessionDep) -> UserOut:
|
||||
user = await user_of_device(device, db)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return user_out(user, await catalog.zodiac_map(db))
|
||||
|
||||
|
||||
@router.get("/weather")
|
||||
async def get_weather(
|
||||
device: CurrentDevice,
|
||||
db: SessionDep,
|
||||
city: str | None = Query(default=None, description="不传则用账号资料里的出生城市"),
|
||||
) -> dict:
|
||||
user = await user_of_device(device, db)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||||
|
||||
# 日常天气优先用居住地,没填再退到出生地
|
||||
target = (city or user.residence_city or user.birth_city or settings.default_city).strip()
|
||||
try:
|
||||
data = await weather.now(db, target)
|
||||
except weather.WeatherNotConfigured as exc:
|
||||
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from exc
|
||||
except weather.WeatherUpstreamError as exc:
|
||||
raise HTTPException(status.HTTP_502_BAD_GATEWAY, str(exc)) from exc
|
||||
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return data
|
||||
|
||||
|
||||
async def _user_effective_tz(db, user: User) -> str:
|
||||
"""「今天/本月」用哪个时区:用户显式设置 > 居住地码表时区 > 内地标准时。"""
|
||||
if user.timezone:
|
||||
return user.timezone
|
||||
if user.residence_region_code:
|
||||
_city, _place, tz = await catalog.resolve_place(db, user.residence_region_code)
|
||||
return tz
|
||||
return "Asia/Shanghai"
|
||||
|
||||
|
||||
@router.get("/astro")
|
||||
async def device_astro(
|
||||
device: CurrentDevice,
|
||||
db: SessionDep,
|
||||
lang: str = Query(default="zh", pattern="^(zh|en)$"),
|
||||
) -> dict:
|
||||
"""星盘:太阳/月亮星座 + 当月运势。
|
||||
|
||||
「当月」按用户居住时区算,跨界(比如 12 月 31 日 23 点)不串月。
|
||||
运势文案支持中英文,取值顺序:管理端指定年月 → 管理端通用月度 → 内置模板。
|
||||
"""
|
||||
user = await user_of_device(device, db)
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device not bound")
|
||||
|
||||
tz_name = await _user_effective_tz(db, user)
|
||||
try:
|
||||
tz = ZoneInfo(tz_name)
|
||||
except ZoneInfoNotFoundError:
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
local_now = datetime.now(timezone.utc).astimezone(tz)
|
||||
year, month = local_now.year, local_now.month
|
||||
|
||||
zmap = await catalog.zodiac_map(db)
|
||||
lang = "en" if lang == "en" else "zh"
|
||||
|
||||
def pack(kind: str) -> dict | None:
|
||||
code = getattr(user, f"{kind}_sign", None)
|
||||
if not code:
|
||||
return None
|
||||
info = zmap.get(code, {})
|
||||
name = info.get("name_en") if lang == "en" and info.get("name_en") else info.get("name_cn", code)
|
||||
return {
|
||||
"code": code,
|
||||
"name": name,
|
||||
"symbol": info.get("symbol", ""),
|
||||
"element": info.get("element", ""),
|
||||
"degree": float(getattr(user, f"{kind}_degree", 0) or 0),
|
||||
"date_range": info.get("date_range", ""),
|
||||
}
|
||||
|
||||
sun, moon = pack("sun"), pack("moon")
|
||||
|
||||
# 运势跟随月亮星座更准(月亮掌管情绪与内在),没月亮就退太阳
|
||||
fortune_sign = user.moon_sign or user.sun_sign
|
||||
f_data = await fortune.for_user(db, fortune_sign, year, month, lang)
|
||||
if f_data is None and fortune_sign:
|
||||
info = zmap.get(fortune_sign, {})
|
||||
sign_name = info.get("name_en") if lang == "en" and info.get("name_en") else info.get("name_cn", fortune_sign)
|
||||
f_data = fortune.generic_fortune(sign_name, info.get("element", ""), month, lang)
|
||||
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return {
|
||||
"ok": True,
|
||||
"lang": lang,
|
||||
"timezone": tz_name,
|
||||
"local_time": local_now.isoformat(timespec="seconds"),
|
||||
"period": f"{year}-{month:02d}",
|
||||
"sun": sun,
|
||||
"moon": moon,
|
||||
"fortune_sign": fortune_sign,
|
||||
"fortune": f_data,
|
||||
}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 固件升级
|
||||
@router.get("/firmware/check", response_model=CheckOut)
|
||||
async def check_firmware(
|
||||
device: CurrentDevice,
|
||||
db: SessionDep,
|
||||
current: str | None = Query(default=None, description="设备当前版本,不传则用库里的 fw_version"),
|
||||
lang: str = Query(default="zh", pattern="^(zh|en)$"),
|
||||
) -> CheckOut:
|
||||
"""设备开机/定时来问一句:我要不要升级。
|
||||
|
||||
``url`` 给的是**相对路径**——设备拼自己的 serverUrl,换域名/换端口都不用改库里数据。
|
||||
"""
|
||||
cur = (current or device.fw_version or "").strip()
|
||||
if current and current != device.fw_version:
|
||||
device.fw_version = current
|
||||
await db.commit()
|
||||
|
||||
fw, forced = await firmware.resolve_for_device(db, device)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
if fw is None or not fw.published:
|
||||
return CheckOut(update=False)
|
||||
|
||||
# 自动更新只升不降;管理员点名时允许回滚
|
||||
if not forced and firmware.compare(fw.version, cur) <= 0:
|
||||
return CheckOut(update=False)
|
||||
|
||||
return CheckOut(
|
||||
update=True,
|
||||
version=fw.version,
|
||||
size=fw.size_bytes,
|
||||
sha256=fw.sha256,
|
||||
notes=(fw.notes_en if lang == "en" and fw.notes_en else fw.notes),
|
||||
url=f"/device/v1/firmware/{fw.id}/download",
|
||||
mandatory=forced,
|
||||
reason="forced" if forced else "newer",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/firmware/{firmware_id}/download")
|
||||
async def download_firmware(firmware_id: uuid.UUID, device: CurrentDevice, db: SessionDep):
|
||||
"""下发 bin 本体。
|
||||
|
||||
只有已发布的包能下;下发给点名设备时,目标包即使下线了也放行——
|
||||
否则管理员刚点了「下线」,设备正在下载就 404 了。
|
||||
"""
|
||||
fw = await db.get(Firmware, firmware_id)
|
||||
if fw is None:
|
||||
raise HTTPException(404, "firmware not found")
|
||||
forced = device.target_firmware_id == fw.id
|
||||
if not fw.published and not forced:
|
||||
raise HTTPException(404, "firmware not published")
|
||||
|
||||
path = firmware.path_of(fw)
|
||||
if not path.exists():
|
||||
raise HTTPException(410, "firmware file missing on server")
|
||||
|
||||
fw.download_count += 1
|
||||
device.upgrade_state = "downloading"
|
||||
device.target_firmware_id = fw.id
|
||||
device.target_version = fw.version
|
||||
device.upgrade_at = datetime.now(timezone.utc)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type="application/octet-stream",
|
||||
filename=f"knob_os-{fw.version}.bin",
|
||||
headers={"X-Firmware-Version": fw.version, "X-Firmware-Sha256": fw.sha256},
|
||||
)
|
||||
|
||||
|
||||
class ReportIn(BaseModel):
|
||||
version: str
|
||||
status: str = "success" # success | failed
|
||||
error: str = ""
|
||||
slot: str = ""
|
||||
|
||||
|
||||
@router.post("/firmware/report")
|
||||
async def report_firmware(body: ReportIn, device: CurrentDevice, db: SessionDep) -> dict:
|
||||
"""设备升级完(或失败)回报一句,管理端据此判断这轮推没推成功。"""
|
||||
ok = body.status == "success"
|
||||
device.upgrade_state = "success" if ok else "failed"
|
||||
device.upgrade_error = "" if ok else (body.error or "unknown")[:160]
|
||||
device.upgrade_at = datetime.now(timezone.utc)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
if body.slot:
|
||||
device.boot_slot = body.slot[:8]
|
||||
|
||||
if ok:
|
||||
if body.version and body.version != device.fw_version:
|
||||
device.fw_version = body.version[:32]
|
||||
device.fw_updated_at = datetime.now(timezone.utc)
|
||||
# 任务完成即清目标,否则下次 check 还会把同一版再推一遍
|
||||
device.target_firmware_id = None
|
||||
device.target_version = ""
|
||||
|
||||
await db.commit()
|
||||
return {"ok": True, "state": device.upgrade_state}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 扫码登录 Web
|
||||
class WebLoginOut(BaseModel):
|
||||
"""设备屏上的二维码内容:手机打开 url 即自动登录该设备的绑定账号。"""
|
||||
|
||||
code: str
|
||||
url: str
|
||||
expires_in: int
|
||||
|
||||
|
||||
def _web_base(request: Request) -> str:
|
||||
"""手机要打开的 Web 基地址。
|
||||
|
||||
不再单独配置:设备里配的「服务端地址」就是它请求我们的 Host,同域拼接天然
|
||||
正确(正式部署 Web 与 API 同一个入口)。只有两种情况需要干预:
|
||||
|
||||
* 前后端分离开发:设备直连 API 端口(.env 的 ``BACKEND_PORT``,默认 8100),
|
||||
页面在 ``FRONTEND_PORT``(默认 5174),按这两个端口换算;
|
||||
* Web 与 API 真的不同域(CDN 等):用 .env 的 ``WEB_BASE_URL`` 覆盖。
|
||||
"""
|
||||
base = settings.web_base_url.strip()
|
||||
if base:
|
||||
return base.rstrip("/")
|
||||
|
||||
url = request.url
|
||||
host = url.hostname or "127.0.0.1"
|
||||
port = url.port
|
||||
if port == settings.backend_port:
|
||||
port = settings.frontend_port
|
||||
if port and port not in (80, 443):
|
||||
return f"{url.scheme}://{host}:{port}"
|
||||
return f"{url.scheme}://{host}"
|
||||
|
||||
|
||||
@router.post("/web-login/ticket", response_model=WebLoginOut)
|
||||
async def web_login_ticket(device: CurrentDevice, request: Request, db: SessionDep) -> WebLoginOut:
|
||||
"""「我的」页下拉时调用:拿一张一次性票据,编成二维码给手机扫。
|
||||
|
||||
票据只对当前设备的绑定账号有效、一码一用、5 分钟过期;屏幕上重新打开
|
||||
二维码会换新码,旧码随之失效。
|
||||
"""
|
||||
user = await user_of_device(device, db)
|
||||
if user is None or user.status != "active":
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "device not bound to an active user")
|
||||
|
||||
code = new_web_login_code()
|
||||
ttl = settings.web_login_ttl_seconds
|
||||
await redis_store.put_web_login(code, str(user.id), str(device.id), ttl)
|
||||
base = _web_base(request)
|
||||
return WebLoginOut(code=code, url=f"{base}/qr?t={code}", expires_in=ttl)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ TF 卡媒体同步
|
||||
class ManifestItem(BaseModel):
|
||||
id: uuid.UUID
|
||||
kind: str
|
||||
name: str
|
||||
size: int
|
||||
crc32: int
|
||||
url: str
|
||||
|
||||
|
||||
class MediaManifestOut(BaseModel):
|
||||
rev: str
|
||||
items: list[ManifestItem]
|
||||
|
||||
|
||||
class MediaStateOut(BaseModel):
|
||||
"""轻量状态:设备进入音乐/相册模块时查一次,决定要不要弹「同步」提示。
|
||||
|
||||
``rev`` 是服务端当前清单指纹,``synced_rev`` 是设备上次同步完回报的指纹;
|
||||
设备拿它跟自己 TF 卡上的本地清单 rev 对比,清单变了(删除/改名)也会提示。
|
||||
"""
|
||||
|
||||
seq: int # 兼容字段:网页触发时代的计数,设备侧同步不再依赖
|
||||
ack: int # 兼容字段:同上
|
||||
pending: int # 清单里有、设备还没同步的文件数(不分类型,总口径)
|
||||
pending_pic: int = 0 # 其中图片数:相册弹窗只报这个,别把音乐混进去
|
||||
pending_music: int = 0 # 其中音乐数:同上
|
||||
rev: str = "" # 服务端当前清单指纹
|
||||
synced_rev: str = "" # 设备上次同步时的清单指纹
|
||||
|
||||
|
||||
@router.get("/media/pending", response_model=MediaStateOut)
|
||||
async def media_pending(device: CurrentDevice, db: SessionDep) -> MediaStateOut:
|
||||
"""设备进入音乐/相册时查:有没有文件要同步。
|
||||
|
||||
响应几百字节;``pending > 0`` 或 ``rev != synced_rev`` 都算「有待同步」,
|
||||
设备据此弹确认框,用户同意才拉 manifest 开始同步。
|
||||
"""
|
||||
todo, files = await media.pending_for_device(db, device)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return MediaStateOut(
|
||||
seq=device.media_sync_seq,
|
||||
ack=device.media_sync_ack,
|
||||
pending=len(todo),
|
||||
pending_pic=sum(1 for f in todo if f.kind == "pic"),
|
||||
pending_music=sum(1 for f in todo if f.kind == "music"),
|
||||
rev=media.manifest_rev(files),
|
||||
synced_rev=device.media_synced_rev,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/media/manifest", response_model=MediaManifestOut)
|
||||
async def media_manifest(device: CurrentDevice, db: SessionDep) -> MediaManifestOut:
|
||||
"""设备要同步的媒体清单(绑定用户的全量库,设备自己 diff 增量)。
|
||||
|
||||
``rev`` 是整份清单的指纹:设备可以用它快速判断「清单变没变」,
|
||||
没变就不用逐条比对了;同步完成后原样回报,服务端据此判断是否最新。
|
||||
"""
|
||||
files = await media.manifest_for_device(db, device)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
items = [
|
||||
ManifestItem(
|
||||
id=mf.id,
|
||||
kind=mf.kind,
|
||||
name=mf.name,
|
||||
size=mf.size,
|
||||
crc32=mf.crc32,
|
||||
url=f"/device/v1/media/{mf.id}/file",
|
||||
)
|
||||
for mf in files
|
||||
]
|
||||
return MediaManifestOut(rev=media.manifest_rev(files), items=items)
|
||||
|
||||
|
||||
@router.get("/media/{media_id}/file")
|
||||
async def media_download(media_id: uuid.UUID, device: CurrentDevice, db: SessionDep):
|
||||
"""下发媒体文件本体。只放行绑定用户自己的库,防止跨账号拖文件。"""
|
||||
mf = await db.get(MediaFile, media_id)
|
||||
if mf is None or mf.owner_user_id != device.bound_user_id:
|
||||
raise HTTPException(404, "media not found")
|
||||
path = media.path_of(mf)
|
||||
if not path.exists():
|
||||
raise HTTPException(410, "file missing on server")
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return FileResponse(path, media_type="application/octet-stream", filename=mf.name)
|
||||
|
||||
|
||||
class MediaReportIn(BaseModel):
|
||||
synced: list[uuid.UUID] = []
|
||||
deleted: list[uuid.UUID] = []
|
||||
# 这一轮处理的是第几次同步请求、清单指纹是什么——游标推进靠它们
|
||||
seq: int = 0
|
||||
rev: str = ""
|
||||
|
||||
|
||||
@router.post("/media/report")
|
||||
async def media_report(body: MediaReportIn, device: CurrentDevice, db: SessionDep) -> dict:
|
||||
"""设备同步完(或删完)回报:网页端据此显示每台设备的同步状态。"""
|
||||
await media.apply_report(db, device, body.synced, body.deleted, body.seq, body.rev)
|
||||
device.last_active_at = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
return {"ok": True, "synced": len(body.synced), "deleted": len(body.deleted), "ack": device.media_sync_ack}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
"""Web 侧设备管理:输入配对码绑定、设备列表、解绑。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.api.deps import CurrentUser, SessionDep
|
||||
from app.core.security import normalize_pair_code
|
||||
from app.models import Device, User
|
||||
from app.schemas.auth import DeviceOut, OkOut, PairByCodeIn
|
||||
from app.services import media, redis_store
|
||||
|
||||
router = APIRouter(tags=["devices"])
|
||||
|
||||
|
||||
@router.post("/devices/pair", response_model=DeviceOut)
|
||||
async def pair_device(body: PairByCodeIn, user: CurrentUser, db: SessionDep) -> DeviceOut:
|
||||
code = normalize_pair_code(body.code)
|
||||
if len(code) != 6:
|
||||
raise HTTPException(400, "pairing code must be 6 digits")
|
||||
|
||||
# 防爆破:同一配对码 5 次/分钟
|
||||
tries = await redis_store.bump_pair_try(code)
|
||||
if tries > 5:
|
||||
raise HTTPException(429, "too many attempts, wait a minute")
|
||||
|
||||
payload = await redis_store.get_pair(code)
|
||||
if not payload:
|
||||
raise HTTPException(404, "code expired or not found")
|
||||
if payload.get("bound_user_id"):
|
||||
raise HTTPException(409, "code already used")
|
||||
|
||||
device_id = payload["device_id"]
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None:
|
||||
raise HTTPException(404, "device not found")
|
||||
if device.bound_user_id and device.bound_user_id != user.id:
|
||||
raise HTTPException(409, "device already bound to another account")
|
||||
|
||||
device.bound_user_id = user.id
|
||||
device.bound_at = datetime.now(timezone.utc)
|
||||
await redis_store.mark_pair_bound(code, str(user.id))
|
||||
await db.commit()
|
||||
await db.refresh(device)
|
||||
return DeviceOut.model_validate(device)
|
||||
|
||||
|
||||
@router.get("/devices", response_model=list[DeviceOut])
|
||||
async def list_devices(user: CurrentUser, db: SessionDep) -> list[DeviceOut]:
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Device)
|
||||
.where(Device.bound_user_id == user.id)
|
||||
.order_by(Device.bound_at.desc().nulls_last())
|
||||
)
|
||||
).scalars()
|
||||
return [DeviceOut.model_validate(d) for d in rows]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- TF 卡媒体同步
|
||||
# 用户进「TF 卡文件」模块时检查有没有待同步文件;点「立即同步」才下发任务。
|
||||
# 设备侧每 15 秒只探一个几字节的状态(seq/ack),不做定时全量同步。
|
||||
class MediaPendingItem(BaseModel):
|
||||
id: uuid.UUID
|
||||
kind: str
|
||||
name: str
|
||||
size: int
|
||||
|
||||
|
||||
class MediaPendingOut(BaseModel):
|
||||
device_id: uuid.UUID
|
||||
seq: int
|
||||
ack: int
|
||||
pending: int # 待下载/更新的文件数
|
||||
rev: str # 服务端清单指纹
|
||||
synced_rev: str # 设备上次同步完的指纹(不同即有删除/更新)
|
||||
items: list[MediaPendingItem]
|
||||
|
||||
|
||||
@router.get("/devices/{device_id}/media/pending", response_model=MediaPendingOut)
|
||||
async def media_pending_for_device(
|
||||
device_id: uuid.UUID, user: CurrentUser, db: SessionDep
|
||||
) -> MediaPendingOut:
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None or device.bound_user_id != user.id:
|
||||
raise HTTPException(404, "device not found")
|
||||
|
||||
todo, files = await media.pending_for_device(db, device)
|
||||
return MediaPendingOut(
|
||||
device_id=device.id,
|
||||
seq=device.media_sync_seq,
|
||||
ack=device.media_sync_ack,
|
||||
pending=len(todo),
|
||||
rev=media.manifest_rev(files),
|
||||
synced_rev=device.media_synced_rev,
|
||||
items=[MediaPendingItem(id=f.id, kind=f.kind, name=f.name, size=f.size) for f in todo],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/devices/{device_id}/media/sync")
|
||||
async def trigger_media_sync(device_id: uuid.UUID, user: CurrentUser, db: SessionDep) -> dict:
|
||||
"""用户点了「立即同步」:seq +1,设备下一次探测(≤15 秒)就开始同步。"""
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None or device.bound_user_id != user.id:
|
||||
raise HTTPException(404, "device not found")
|
||||
|
||||
device.media_sync_seq += 1
|
||||
await db.commit()
|
||||
return {"ok": True, "seq": device.media_sync_seq}
|
||||
|
||||
|
||||
@router.delete("/devices/{device_id}", response_model=OkOut)
|
||||
async def unbind(device_id: uuid.UUID, user: CurrentUser, db: SessionDep) -> OkOut:
|
||||
device = await db.get(Device, device_id)
|
||||
if device is None or device.bound_user_id != user.id:
|
||||
raise HTTPException(404, "device not found")
|
||||
|
||||
device.bound_user_id = None
|
||||
device.bound_at = None
|
||||
await db.commit()
|
||||
# 立刻吊销:设备下次请求就 401,回落到未绑定态
|
||||
n = await redis_store.revoke_device_tokens(str(device_id))
|
||||
return OkOut(ok=True, detail=f"revoked {n} token(s)")
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
"""用户媒体库接口 ``/api/media``:TF 卡文件管理的数据源。
|
||||
|
||||
上传即入库,入库即进入设备同步清单;删除则设备会在下一次同步时清掉 TF 卡
|
||||
上的同名文件。设备侧的接口在 device_v1(manifest / download / report)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, UploadFile, status
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from app.api.deps import CurrentUser, CurrentUserAny, SessionDep
|
||||
from app.models import DeviceMedia, MediaFile
|
||||
from app.services import media as msvc
|
||||
|
||||
router = APIRouter(prefix="/media", tags=["media"])
|
||||
|
||||
|
||||
class MediaOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
kind: str
|
||||
name: str
|
||||
size: int
|
||||
crc32: int
|
||||
width: int
|
||||
height: int
|
||||
original_name: str
|
||||
created_at: str
|
||||
synced_devices: int = 0
|
||||
has_cover: bool = False
|
||||
|
||||
@staticmethod
|
||||
def of(mf: MediaFile, synced: int = 0) -> "MediaOut":
|
||||
return MediaOut(
|
||||
id=mf.id,
|
||||
kind=mf.kind,
|
||||
name=mf.name,
|
||||
size=mf.size,
|
||||
crc32=mf.crc32,
|
||||
width=mf.width,
|
||||
height=mf.height,
|
||||
original_name=mf.original_name,
|
||||
created_at=mf.created_at.isoformat() if mf.created_at else "",
|
||||
synced_devices=synced,
|
||||
has_cover=bool(mf.cover_file),
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=list[MediaOut])
|
||||
async def list_media(db: SessionDep, user: CurrentUser) -> list[MediaOut]:
|
||||
rows = list(
|
||||
(
|
||||
await db.execute(
|
||||
select(MediaFile).where(MediaFile.owner_user_id == user.id).order_by(MediaFile.created_at.desc())
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
states = await msvc.sync_states(db, user.id)
|
||||
return [MediaOut.of(r, states.get(r.id, 0)) for r in rows]
|
||||
|
||||
|
||||
@router.post("", response_model=MediaOut, status_code=201)
|
||||
async def upload_media(db: SessionDep, user: CurrentUser, file: UploadFile) -> MediaOut:
|
||||
"""上传一个文件。音乐原样入库;图片服务端转 JPEG(限边/去 EXIF)。"""
|
||||
raw = await file.read()
|
||||
if not raw:
|
||||
raise HTTPException(400, "empty file")
|
||||
|
||||
try:
|
||||
kind = msvc.kind_of(file.filename or "")
|
||||
name = msvc.sanitize_name(file.filename or "")
|
||||
except msvc.MediaError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
if len(raw) > msvc.max_size_for(kind):
|
||||
cap = msvc.max_size_for(kind) // (1024 * 1024)
|
||||
raise HTTPException(400, f"文件超过 {cap} MB 上限")
|
||||
|
||||
width = height = 0
|
||||
cover_file = ""
|
||||
if kind == "image":
|
||||
try:
|
||||
raw, width, height = msvc.process_image(raw)
|
||||
except msvc.MediaError as e:
|
||||
raise HTTPException(400, str(e)) from e
|
||||
|
||||
# 同名即视为「重新上传」:替换内容、保留 id,设备端按 crc32 不同重新下载
|
||||
existing = await db.scalar(
|
||||
select(MediaFile).where(MediaFile.owner_user_id == user.id, MediaFile.name == name)
|
||||
)
|
||||
filename, size, crc = msvc.save_bytes(kind, name, raw)
|
||||
cover_id = existing.id if existing is not None else uuid.uuid4()
|
||||
if kind == "music":
|
||||
cover_file = msvc.extract_cover(raw, cover_id)
|
||||
if existing is None:
|
||||
mf = MediaFile(
|
||||
owner_user_id=user.id,
|
||||
kind=kind,
|
||||
name=name,
|
||||
size=size,
|
||||
crc32=crc,
|
||||
filename=filename,
|
||||
original_name=file.filename or name,
|
||||
width=width,
|
||||
height=height,
|
||||
cover_file=cover_file,
|
||||
)
|
||||
db.add(mf)
|
||||
else:
|
||||
msvc.remove_file(existing)
|
||||
msvc.remove_cover(existing)
|
||||
existing.kind = kind
|
||||
existing.size = size
|
||||
existing.crc32 = crc
|
||||
existing.filename = filename
|
||||
existing.original_name = file.filename or name
|
||||
existing.width = width
|
||||
existing.height = height
|
||||
existing.cover_file = cover_file
|
||||
# 内容换了:清掉各设备的「已同步」记录,让它们重新进入待同步
|
||||
await db.execute(delete(DeviceMedia).where(DeviceMedia.media_id == existing.id))
|
||||
mf = existing
|
||||
await db.commit()
|
||||
await db.refresh(mf)
|
||||
return MediaOut.of(mf, 0)
|
||||
|
||||
|
||||
@router.delete("/{media_id}", status_code=204)
|
||||
async def delete_media(media_id: uuid.UUID, db: SessionDep, user: CurrentUser) -> None:
|
||||
mf = await db.get(MediaFile, media_id)
|
||||
if mf is None or mf.owner_user_id != user.id:
|
||||
raise HTTPException(404, "media not found")
|
||||
# TF 卡上的文件由设备 diff 清单后删除;这里只管服务端这份
|
||||
await db.execute(delete(MediaFile).where(MediaFile.id == mf.id))
|
||||
await db.commit()
|
||||
msvc.remove_file(mf)
|
||||
msvc.remove_cover(mf)
|
||||
|
||||
|
||||
@router.get("/{media_id}/cover")
|
||||
async def media_cover(media_id: uuid.UUID, db: SessionDep, user: CurrentUserAny) -> FileResponse:
|
||||
"""MP3 内嵌封面缩略图(上传时已抽取压好)。没有封面返回 404。"""
|
||||
mf = await db.get(MediaFile, media_id)
|
||||
if mf is None or mf.owner_user_id != user.id or not mf.cover_file:
|
||||
raise HTTPException(404, "no cover")
|
||||
path = msvc.COVERS_DIR / mf.cover_file
|
||||
if not path.exists():
|
||||
raise HTTPException(status.HTTP_410_GONE, "cover missing on server")
|
||||
return FileResponse(path, media_type="image/jpeg")
|
||||
|
||||
|
||||
@router.get("/{media_id}/file")
|
||||
async def media_file(media_id: uuid.UUID, db: SessionDep, user: CurrentUserAny) -> FileResponse:
|
||||
"""网页预览/试听。
|
||||
|
||||
用 ``CurrentUserAny``:``<img>``/``<audio>`` 带不了 Authorization 头,
|
||||
网页端把 token 拼在 ``?t=`` 上。
|
||||
"""
|
||||
mf = await db.get(MediaFile, media_id)
|
||||
if mf is None or mf.owner_user_id != user.id:
|
||||
raise HTTPException(404, "media not found")
|
||||
path = msvc.path_of(mf)
|
||||
if not path.exists():
|
||||
raise HTTPException(status.HTTP_410_GONE, "file missing on server")
|
||||
mt = "audio/mpeg" if mf.kind == "music" else "image/jpeg"
|
||||
return FileResponse(path, media_type=mt, filename=mf.name)
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
"""码表与星盘试算:登录用户只读。写操作在 /api/admin 下。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, time, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.deps import CurrentUser, SessionDep
|
||||
from app.services import astro, catalog, fortune
|
||||
|
||||
router = APIRouter(prefix="/meta", tags=["meta"])
|
||||
|
||||
|
||||
@router.get("/regions/tree")
|
||||
async def regions_tree(user: CurrentUser, db: SessionDep) -> dict:
|
||||
"""省 → 市 → 区县 三级树,直接喂给前端 Cascader。"""
|
||||
tree = await catalog.region_tree(db)
|
||||
return {"items": tree, "count": sum(1 for _ in _walk(tree))}
|
||||
|
||||
|
||||
def _walk(nodes: list[dict]):
|
||||
for n in nodes:
|
||||
yield n
|
||||
yield from _walk(n.get("children") or [])
|
||||
|
||||
|
||||
@router.get("/regions/resolve")
|
||||
async def resolve_region(user: CurrentUser, db: SessionDep, code: str = Query(..., min_length=2)) -> dict:
|
||||
city, place, tz = await catalog.resolve_place(db, code)
|
||||
if place is None:
|
||||
raise HTTPException(404, "region not found")
|
||||
return {"code": code, "city": city, "place": place, "timezone": tz}
|
||||
|
||||
|
||||
@router.get("/zodiacs")
|
||||
async def zodiacs(user: CurrentUser, db: SessionDep) -> dict:
|
||||
items = await catalog.zodiacs(db)
|
||||
return {"items": items, "count": len(items)}
|
||||
|
||||
|
||||
class AstroPreviewIn(BaseModel):
|
||||
birthday: date
|
||||
birth_time: time | None = None
|
||||
birth_region_code: str | None = Field(default=None, description="不传按 Asia/Shanghai")
|
||||
|
||||
|
||||
@router.post("/astro/preview")
|
||||
async def astro_preview(body: AstroPreviewIn, user: CurrentUser, db: SessionDep) -> dict:
|
||||
"""保存前先看一眼:改日期/城市时前端即时出结果。"""
|
||||
tz = "Asia/Shanghai"
|
||||
place = None
|
||||
if body.birth_region_code:
|
||||
_, place, tz = await catalog.resolve_place(db, body.birth_region_code)
|
||||
result = astro.compute(body.birthday, body.birth_time, tz)
|
||||
zmap = await catalog.zodiac_map(db)
|
||||
|
||||
def pack(kind: str, sign: str, deg: float) -> dict:
|
||||
info = zmap.get(sign, {})
|
||||
return {
|
||||
"code": sign,
|
||||
"name": info.get("name_cn", sign),
|
||||
"symbol": info.get("symbol", ""),
|
||||
"element": info.get("element", ""),
|
||||
"degree": deg,
|
||||
"date_range": info.get("date_range", ""),
|
||||
}
|
||||
|
||||
return {
|
||||
"sun": pack("sun", result.sun_sign, result.sun_degree),
|
||||
"moon": pack("moon", result.moon_sign, result.moon_degree),
|
||||
"birth_place": place,
|
||||
"timezone": result.tz,
|
||||
"utc_time": result.utc_time,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/fortune")
|
||||
async def my_fortune(
|
||||
user: CurrentUser,
|
||||
db: SessionDep,
|
||||
lang: str = Query(default="zh", pattern="^(zh|en)$"),
|
||||
) -> dict:
|
||||
"""登录用户自己的当月运势(「当月」按居住时区),供首页星座卡展示。"""
|
||||
tz_name = user.timezone
|
||||
if not tz_name and user.residence_region_code:
|
||||
_c, _p, tz_name = await catalog.resolve_place(db, user.residence_region_code)
|
||||
try:
|
||||
tz = ZoneInfo(tz_name or "Asia/Shanghai")
|
||||
except Exception:
|
||||
tz = ZoneInfo("Asia/Shanghai")
|
||||
local_now = datetime.now(timezone.utc).astimezone(tz)
|
||||
year, month = local_now.year, local_now.month
|
||||
|
||||
zmap = await catalog.zodiac_map(db)
|
||||
sign = user.moon_sign or user.sun_sign
|
||||
data = await fortune.for_user(db, sign, year, month, lang)
|
||||
if data is None and sign:
|
||||
info = zmap.get(sign, {})
|
||||
name = info.get("name_en") if lang == "en" and info.get("name_en") else info.get("name_cn", sign)
|
||||
data = fortune.generic_fortune(name, info.get("element", ""), month, lang)
|
||||
return {
|
||||
"period": f"{year}-{month:02d}",
|
||||
"timezone": tz_name or "Asia/Shanghai",
|
||||
"sign": sign,
|
||||
"fortune": data,
|
||||
}
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
"""运行时配置:环境变量 / .env 为唯一来源,代码里不落任何密钥。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
# server/app/core/config.py -> nex_buddy/
|
||||
ROOT = Path(__file__).resolve().parents[3]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=ROOT / ".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
case_sensitive=False,
|
||||
)
|
||||
|
||||
app_name: str = "nex_buddy"
|
||||
app_env: str = "dev"
|
||||
app_version: str = "0.1.0"
|
||||
|
||||
# 运行时资源根目录:媒体、固件、码表等。默认项目根 data/;
|
||||
# 服务器/容器部署可用 DATA_DIR 指向宿主机挂载点。
|
||||
data_dir: Path = ROOT / "data"
|
||||
|
||||
database_url: str = "postgresql+asyncpg://postgres:sagacity@192.168.124.203:5432/nex_buddy"
|
||||
redis_url: str = "redis://192.168.124.203:6379/9"
|
||||
|
||||
# 和风:Key 与 Host 都只在服务端;Host 是账号专属域名,缺了会 403 Invalid Host
|
||||
qweather_key: str = ""
|
||||
qweather_host: str = "p52yvqedka.re.qweatherapi.com"
|
||||
|
||||
session_ttl_seconds: int = 7 * 24 * 3600
|
||||
pair_code_ttl_seconds: int = 600
|
||||
|
||||
# 设备屏上二维码的 Web 基地址(手机要能访问到)。
|
||||
# 默认按设备请求的 Host 推导——设备里配的「服务端地址」就是它,同域部署不用配。
|
||||
# 仅当 Web 与 API 确实不同域时才在这里(.env)覆盖。
|
||||
web_base_url: str = ""
|
||||
# 端口(开发期):scripts/dev.sh 起后端、vite 起前端都从 .env 读这两个值,
|
||||
# 改了 FRONTEND_PORT 后,localhost 的 CORS 源会自动跟着换(见 cors_list)
|
||||
backend_port: int = 8100
|
||||
frontend_port: int = 5174
|
||||
# 扫码登录票据有效期:够扫码 + 手机打开,过期就在设备上重开一次
|
||||
web_login_ttl_seconds: int = 300
|
||||
pair_claim_window_seconds: int = 120 # 码消费后 2 分钟内必须换 token
|
||||
weather_cache_seconds: int = 1800
|
||||
default_city: str = "杭州"
|
||||
|
||||
# 默认不配置:Web 与 API 同域(Nginx 反代 / Vite proxy)时浏览器不需要 CORS。
|
||||
# 只有确实分离部署(如 web.example.com + api.example.com)才设置,
|
||||
# 逗号分隔,写完整源(协议 + 域名 + 端口),例如:
|
||||
# CORS_ORIGINS=https://app.example.com
|
||||
cors_origins: str = ""
|
||||
|
||||
@property
|
||||
def cors_list(self) -> list[str]:
|
||||
out: list[str] = []
|
||||
|
||||
def add(origin: str) -> None:
|
||||
origin = origin.strip().rstrip("/")
|
||||
if origin and origin not in out:
|
||||
out.append(origin)
|
||||
|
||||
for raw in self.cors_origins.split(","):
|
||||
add(raw)
|
||||
if "*" in out:
|
||||
return ["*"]
|
||||
|
||||
if self.app_env == "dev":
|
||||
# localhost 的前端源由端口推导,改 FRONTEND_PORT 不用回来改 CORS。
|
||||
# 手机通过局域网访问 Vite 时走的是同源代理,也不需要额外加 IP。
|
||||
add(f"http://localhost:{self.frontend_port}")
|
||||
add(f"http://127.0.0.1:{self.frontend_port}")
|
||||
|
||||
# 配了 WEB_BASE_URL(扫码二维码的 Web 地址)时,它的源就是浏览器实际
|
||||
# 访问 Web 的源;分离部署时自动放行,不必再抄一遍到 CORS_ORIGINS。
|
||||
if self.web_base_url.strip():
|
||||
parts = urlsplit(self.web_base_url.strip())
|
||||
if parts.scheme and parts.netloc:
|
||||
add(f"{parts.scheme}://{parts.netloc}")
|
||||
|
||||
return out
|
||||
|
||||
@property
|
||||
def qweather_host_url(self) -> str:
|
||||
"""归一化成 https://host,接受带协议/带斜杠的写法。"""
|
||||
h = (self.qweather_host or "").strip().rstrip("/")
|
||||
if not h:
|
||||
return ""
|
||||
if not h.startswith(("http://", "https://")):
|
||||
h = "https://" + h
|
||||
return h
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
"""口令哈希与 token 生成。
|
||||
|
||||
设计要点(01-总体设计.md 第 7 节):口令用 bcrypt 存哈希;token 只存哈希,
|
||||
即使 Redis 被读也无法反推出可用的凭证。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
|
||||
import bcrypt
|
||||
|
||||
# bcrypt 只取前 72 字节,超长口令先截断,避免不同口令哈希相同
|
||||
_MAX = 72
|
||||
|
||||
|
||||
def hash_password(raw: str) -> str:
|
||||
return bcrypt.hashpw(raw.encode("utf-8")[:_MAX], bcrypt.gensalt(rounds=12)).decode()
|
||||
|
||||
|
||||
def verify_password(raw: str, stored: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(raw.encode("utf-8")[:_MAX], stored.encode())
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
"""会话/设备 token:32 字节随机,URL 安全。"""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def new_pair_code() -> str:
|
||||
"""6 位数字配对码,避开前导 0 便于屏显与手输。"""
|
||||
return str(secrets.randbelow(900000) + 100000)
|
||||
|
||||
|
||||
def normalize_pair_code(code: str) -> str:
|
||||
return "".join(ch for ch in (code or "") if ch.isdigit())[:6]
|
||||
|
||||
|
||||
# 扫码登录票据:大写字母 + 数字,去掉 0/O、1/I 这类扫错眼睛的字符
|
||||
_LOGIN_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
|
||||
|
||||
def new_web_login_code(n: int = 10) -> str:
|
||||
return "".join(secrets.choice(_LOGIN_ALPHABET) for _ in range(n))
|
||||
|
||||
|
||||
def normalize_web_login_code(code: str) -> str:
|
||||
return "".join(ch for ch in (code or "").upper() if ch in _LOGIN_ALPHABET)[:16]
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
"""SQLAlchemy 基类与会话工厂。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy import MetaData
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
NAMING_CONVENTION = {
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
}
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
metadata = MetaData(naming_convention=NAMING_CONVENTION)
|
||||
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.database_url,
|
||||
pool_pre_ping=True,
|
||||
pool_size=5,
|
||||
max_overflow=5,
|
||||
echo=False,
|
||||
)
|
||||
|
||||
SessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
async def get_session() -> AsyncIterator[AsyncSession]:
|
||||
async with SessionLocal() as session:
|
||||
yield session
|
||||
|
||||
|
||||
async def dispose_engine() -> None:
|
||||
await engine.dispose()
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
"""nex_buddy 服务端入口。
|
||||
|
||||
启动:./scripts/dev.sh(开发)/ ./scripts/start.sh(生产,systemd 调用)
|
||||
健康检查:GET /healthz —— 设备配网页的「测试连通」就是打这个。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.api import admin, auth, device_v1, devices, media, meta
|
||||
from app.core.config import settings
|
||||
from app.db.session import SessionLocal, dispose_engine
|
||||
from app.services import redis_store, weather
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
||||
log = logging.getLogger("nex_buddy")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
log.info("starting %s v%s (%s)", settings.app_name, settings.app_version, settings.app_env)
|
||||
if await redis_store.ping():
|
||||
log.info("redis ok")
|
||||
else:
|
||||
log.warning("redis unreachable: %s", settings.redis_url)
|
||||
yield
|
||||
await redis_store.close()
|
||||
await dispose_engine()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="nex_buddy",
|
||||
version=settings.app_version,
|
||||
description="ESP32 圆屏设备服务平台:账号 / 绑定 / 资料 / 天气",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_list,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(devices.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
app.include_router(media.router, prefix="/api")
|
||||
app.include_router(meta.router, prefix="/api")
|
||||
app.include_router(device_v1.router)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request, exc):
|
||||
"""兜底 500:把完整堆栈打进日志,前端只收到统一错误文案。
|
||||
|
||||
uvicorn 默认不把未捕获异常写进重定向的日志文件,
|
||||
出了 500 又没有堆栈,等于盲猜。
|
||||
"""
|
||||
log.exception("unhandled error on %s %s", request.method, request.url.path)
|
||||
from fastapi.responses import JSONResponse
|
||||
return JSONResponse(status_code=500, content={"detail": "服务器内部错误(详情见服务端日志)"})
|
||||
|
||||
|
||||
@app.get("/healthz", tags=["meta"])
|
||||
async def healthz() -> dict:
|
||||
"""设备配网页连通性测试用;不要鉴权,也不要吐敏感信息。"""
|
||||
db_ok = False
|
||||
weather_ok = False
|
||||
try:
|
||||
async with SessionLocal() as s:
|
||||
await s.execute(text("select 1"))
|
||||
db_ok = True
|
||||
# 天气是否可用取决于「有效配置」:管理端设置 > Redis > .env
|
||||
weather_ok = await weather.is_configured(s)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("db health failed: %s", exc)
|
||||
|
||||
redis_ok = await redis_store.ping()
|
||||
return {
|
||||
"ok": db_ok and redis_ok,
|
||||
"service": settings.app_name,
|
||||
"version": settings.app_version,
|
||||
"db": db_ok,
|
||||
"redis": redis_ok,
|
||||
"weather_ready": weather_ok,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/", tags=["meta"])
|
||||
async def root() -> dict:
|
||||
return {"service": settings.app_name, "version": settings.app_version, "docs": "/docs"}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
"""模型集中导出:Alembic 与应用都从这里取元数据。"""
|
||||
|
||||
from app.models.device import Device
|
||||
from app.models.firmware import Firmware
|
||||
from app.models.fortune import Fortune
|
||||
from app.models.media import DeviceMedia, MediaFile
|
||||
from app.models.region import Region
|
||||
from app.models.setting import PlatformSetting
|
||||
from app.models.user import User
|
||||
from app.models.zodiac import ZodiacSign
|
||||
|
||||
__all__ = [
|
||||
"User",
|
||||
"Device",
|
||||
"Firmware",
|
||||
"PlatformSetting",
|
||||
"Region",
|
||||
"ZodiacSign",
|
||||
"Fortune",
|
||||
"MediaFile",
|
||||
"DeviceMedia",
|
||||
]
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
"""设备:芯片指纹、固件版本、绑定关系、最近活跃(01-总体设计.md 4.2)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, String, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class Device(Base):
|
||||
__tablename__ = "devices"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
|
||||
# 芯片 efuse MAC,作设备指纹;一台设备只有一条记录
|
||||
chip_id: Mapped[str] = mapped_column(String(32), unique=True, index=True)
|
||||
model: Mapped[str] = mapped_column(String(64), default="JC3636K518C_I_W")
|
||||
fw_version: Mapped[str] = mapped_column(String(32), default="")
|
||||
|
||||
bound_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), index=True
|
||||
)
|
||||
bound_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
last_active_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
# ---- OTA 升级状态 ----
|
||||
# target_firmware_id 是管理员「点名下发」的目标包;设备来 check 时优先拿它,
|
||||
# 这样可以在不做灰度系统的情况下,先把某一版推给一台设备验证。
|
||||
target_firmware_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), index=True)
|
||||
target_version: Mapped[str] = mapped_column(String(32), default="")
|
||||
# ""(无任务) / pending(已下发待设备取) / downloading / success / failed / canceled
|
||||
upgrade_state: Mapped[str] = mapped_column(String(16), default="")
|
||||
upgrade_error: Mapped[str] = mapped_column(String(160), default="")
|
||||
upgrade_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
# 设备上报的启动分区(app0/app1),排查「烧了没生效」时很有用
|
||||
boot_slot: Mapped[str] = mapped_column(String(8), default="")
|
||||
fw_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
||||
# ---- TF 卡媒体同步(用户点「同步」才动,不做定时自动同步)----
|
||||
# seq 是用户按下同步的次数;设备每 15 秒轻量探一次,只有 seq > ack 才真同步。
|
||||
# ack 是设备回报的「已处理到第几次」;rev 是设备同步完的清单指纹,
|
||||
# 两者一起用来判断「有没有新增/删除待同步」——不用设备频繁上报全量清单。
|
||||
media_sync_seq: Mapped[int] = mapped_column(Integer, default=0)
|
||||
media_sync_ack: Mapped[int] = mapped_column(Integer, default=0)
|
||||
media_synced_rev: Mapped[str] = mapped_column(String(32), default="")
|
||||
|
||||
bound_user: Mapped["User | None"] = relationship(back_populates="devices")
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
"""固件包:OTA 升级的版本仓。
|
||||
|
||||
设计要点(为什么这么建):
|
||||
- **按机型 + 通道隔离**:一个平台可能接多种硬件(当前只有 JC3636K518C_I_W),
|
||||
不同机型的 bin 不能互刷;stable/beta 两个通道让测试版和设备自更新互不干扰。
|
||||
- **published 而不是删表**:设备手上可能还跑着旧版本,删一行会丢历史;
|
||||
「下线」只是不再下发给新设备,文件仍在,管理端还能下载复核。
|
||||
- **version_code 冗余存一份**:semver 的比较在 SQL 里写起来很丑,
|
||||
落库时算成整数(major*10^6 + minor*10^3 + patch),排序与取最新都变成一次 ORDER BY。
|
||||
- **sha256 必存**:设备端下载完要校验,服务端自己也要能自证文件没被替换。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, DateTime, Integer, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
|
||||
class Firmware(Base):
|
||||
__tablename__ = "firmwares"
|
||||
__table_args__ = (UniqueConstraint("model", "channel", "version", name="uq_firmware_version"),)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
|
||||
model: Mapped[str] = mapped_column(String(64), default="JC3636K518C_I_W", index=True)
|
||||
version: Mapped[str] = mapped_column(String(32))
|
||||
version_code: Mapped[int] = mapped_column(Integer, default=0, index=True)
|
||||
channel: Mapped[str] = mapped_column(String(16), default="stable")
|
||||
|
||||
size_bytes: Mapped[int] = mapped_column(BigInteger, default=0)
|
||||
sha256: Mapped[str] = mapped_column(String(64), default="")
|
||||
# 落盘文件名(相对 data/firmware),原始上传名只作展示
|
||||
filename: Mapped[str] = mapped_column(String(128), default="")
|
||||
original_name: Mapped[str] = mapped_column(String(160), default="")
|
||||
|
||||
notes: Mapped[str] = mapped_column(Text, default="")
|
||||
notes_en: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
# 低于此版本不允许直接跨刷(留空表示不限制)
|
||||
min_version: Mapped[str] = mapped_column(String(32), default="")
|
||||
|
||||
published: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
download_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
"""月度运势:星座 × 月份的管理端文案。
|
||||
|
||||
两层数据:
|
||||
* ``scope='month'`` 通用月度模板 —— period 存 ``'01'``..``'12'``,每年都适用;
|
||||
* ``scope='ym'`` 指定年月 —— period 存 ``'2026-11'``,优先级高于模板。
|
||||
|
||||
设备端取运势的顺序:指定年月 → 通用月度 → 没有(前端自行兜底文案)。
|
||||
中英文各存一份(``content`` / ``content_en``),平台中英文切换直接取对应列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String, Text, UniqueConstraint, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class Fortune(Base):
|
||||
__tablename__ = "zodiac_fortunes"
|
||||
__table_args__ = (UniqueConstraint("zodiac_code", "scope", "period", name="uq_fortune_period"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
|
||||
zodiac_code: Mapped[str] = mapped_column(String(16), index=True) # aries / ...
|
||||
scope: Mapped[str] = mapped_column(String(8)) # month / ym
|
||||
period: Mapped[str] = mapped_column(String(7)) # '11' 或 '2026-11'
|
||||
|
||||
title: Mapped[str] = mapped_column(String(64), default="")
|
||||
title_en: Mapped[str] = mapped_column(String(128), default="")
|
||||
content: Mapped[str] = mapped_column(Text, default="") # 中文
|
||||
content_en: Mapped[str] = mapped_column(Text, default="") # English,空则回退中文
|
||||
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
"""媒体库:网页上传 → 设备 TF 卡增量同步的版本仓(01-总体设计.md 3.4/3.5)。
|
||||
|
||||
设计要点:
|
||||
- **按用户隔离**:媒体属于账号,同步目标是该账号绑定的设备。换绑设备后
|
||||
新设备会按同一份清单重新同步,不用重新上传。
|
||||
- **kind 只有 music / image**:音乐原样透传(MP3 由副控解码);图片上传时
|
||||
服务端就转成 JPEG(限边、去 EXIF)——设备端不做图像处理,省 CPU 和内存。
|
||||
- **crc32 而不是 sha256**:设备端要边下载边校验,CRC32 在 ESP32 上有硬件
|
||||
加速且表驱动只要 256 字节;文件的完整性风险是传输误码不是恶意篡改,
|
||||
管理端另有 sha256 需求的场景是固件,不是这里。
|
||||
- **device_media 只做展示**:设备手上有一份 TF 卡清单(/nexbuddy/media.json)
|
||||
才是同步的权威状态;这张表存设备最后一次回报的结果,网页端拿它显示
|
||||
「已同步 / 待同步」,不再反向推导。
|
||||
- **删除靠 diff**:用户在网页删掉一个文件,清单里就没有了;设备对比
|
||||
「本地有、清单没有」→ 删 TF 卡文件并回报。不做软删除,减少状态机。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, String, UniqueConstraint, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class MediaFile(Base):
|
||||
__tablename__ = "media_files"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
owner_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True
|
||||
)
|
||||
|
||||
kind: Mapped[str] = mapped_column(String(8)) # music / image
|
||||
# TF 卡上的文件名(含扩展名),同一用户内唯一——设备端靠它落盘
|
||||
name: Mapped[str] = mapped_column(String(160))
|
||||
size: Mapped[int] = mapped_column(BigInteger, default=0)
|
||||
crc32: Mapped[int] = mapped_column(BigInteger, default=0)
|
||||
|
||||
# 落盘文件名(相对 data/media),原始上传名只作展示
|
||||
filename: Mapped[str] = mapped_column(String(128), default="")
|
||||
original_name: Mapped[str] = mapped_column(String(160), default="")
|
||||
|
||||
# 图片处理后尺寸(音乐恒 0),设备端相册不需要再解码才知道多大
|
||||
width: Mapped[int] = mapped_column(Integer, default=0)
|
||||
height: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
# MP3 内嵌封面抽取后的 JPEG 文件名(covers/ 下相对名),空 = 无封面。
|
||||
# 只给网页列表当缩略图;设备唱片机自己解内嵌封面,不用这份。
|
||||
cover_file: Mapped[str] = mapped_column(String(128), default="")
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
__table_args__ = (UniqueConstraint("owner_user_id", "name", name="uq_media_name"),)
|
||||
|
||||
|
||||
class DeviceMedia(Base):
|
||||
__tablename__ = "device_media"
|
||||
__table_args__ = (UniqueConstraint("device_id", "media_id", name="uq_device_media"),)
|
||||
|
||||
device_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("devices.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
media_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), ForeignKey("media_files.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
# synced = 文件已在 TF 卡上;设备删除/下载失败都会如实回报
|
||||
state: Mapped[str] = mapped_column(String(12), default="synced")
|
||||
synced_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
"""城市码表:GB/T 2260 行政区划,三级(省 / 市 / 区县)。
|
||||
|
||||
选择器直接用这张表,用户资料里只存 code,名字跟着码表走——
|
||||
码表由管理端维护,改名/停用都不影响历史数据的指向。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class Region(Base):
|
||||
__tablename__ = "regions"
|
||||
|
||||
# 六位行政区划代码,省补 0000(330000),地级市补 00(330100)
|
||||
code: Mapped[str] = mapped_column(String(12), primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(64), index=True)
|
||||
level: Mapped[int] = mapped_column(Integer, default=1) # 1 省 / 3 市辖区里的区 / 2 地级市
|
||||
parent_code: Mapped[str | None] = mapped_column(String(12), index=True)
|
||||
|
||||
# 出生时间换算 UTC 要时区;港澳台与内地同属 UTC+8 但规则库分开更稳
|
||||
timezone: Mapped[str] = mapped_column(String(64), default="Asia/Shanghai")
|
||||
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
"""平台运行时设置(和风 Key/Host 等):存库 + Redis 缓存,.env 兜底。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, String, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class PlatformSetting(Base):
|
||||
__tablename__ = "settings"
|
||||
|
||||
key: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
value: Mapped[dict | str | int | None] = mapped_column(JSONB)
|
||||
updated_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
"""用户:账号、资料、角色与状态(01-总体设计.md 4.2)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime, time, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Date, DateTime, Numeric, String, Time, func
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models.device import Device
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
|
||||
# 邮箱或手机号二选一,注册时按是否含 @ 判定
|
||||
email: Mapped[str | None] = mapped_column(String(190), unique=True, index=True)
|
||||
phone: Mapped[str | None] = mapped_column(String(32), unique=True, index=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(128))
|
||||
|
||||
nickname: Mapped[str] = mapped_column(String(64), default="")
|
||||
real_name: Mapped[str | None] = mapped_column(String(64))
|
||||
|
||||
# 出生地:只存码表 code,名字另存一份是为了列表/设备侧免 join
|
||||
birthday: Mapped[date | None] = mapped_column(Date)
|
||||
birth_time: Mapped[time | None] = mapped_column(Time)
|
||||
birth_city: Mapped[str | None] = mapped_column(String(64)) # 市级名,天气用它
|
||||
birth_region_code: Mapped[str | None] = mapped_column(String(12))
|
||||
birth_place: Mapped[str | None] = mapped_column(String(128)) # 完整路径:浙江省 杭州市 西湖区
|
||||
|
||||
# 居住地(决定日常天气与运势的「当月」,可与出生地不同)
|
||||
residence_region_code: Mapped[str | None] = mapped_column(String(12))
|
||||
residence_city: Mapped[str | None] = mapped_column(String(64))
|
||||
residence_place: Mapped[str | None] = mapped_column(String(128))
|
||||
|
||||
# 居住时区(IANA 名,如 Asia/Shanghai)。空则按居住地码表时区,再兜底内地标准时。
|
||||
# 只影响「今天是几号/几月」这类日常语义;星盘用的是出生地时区,与这里无关。
|
||||
timezone: Mapped[str | None] = mapped_column(String(64))
|
||||
|
||||
# 星盘结果(保存资料时算好落库,设备直接读,不用现场算)
|
||||
sun_sign: Mapped[str | None] = mapped_column(String(16))
|
||||
moon_sign: Mapped[str | None] = mapped_column(String(16))
|
||||
sun_degree: Mapped[float | None] = mapped_column(Numeric(6, 2))
|
||||
moon_degree: Mapped[float | None] = mapped_column(Numeric(6, 2))
|
||||
|
||||
role: Mapped[str] = mapped_column(String(16), default="user") # user / admin
|
||||
status: Mapped[str] = mapped_column(String(16), default="active") # active / disabled
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=_utcnow
|
||||
)
|
||||
|
||||
devices: Mapped[list["Device"]] = relationship(back_populates="bound_user")
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
"""星座码表:12 星座的展示信息与日期区间。
|
||||
|
||||
黄经 0° 起算顺序就是 sort_order 的顺序(白羊=0 … 双鱼=11),
|
||||
星盘算出来的黄经按 ``int(lon // 30)`` 直接对到这张表,所以
|
||||
**顺序不能乱改**;名字、符号、元素、起止日期、释义都可以在管理端改。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Integer, String, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class ZodiacSign(Base):
|
||||
__tablename__ = "zodiac_signs"
|
||||
|
||||
code: Mapped[str] = mapped_column(String(16), primary_key=True) # aries / taurus ...
|
||||
name_cn: Mapped[str] = mapped_column(String(16))
|
||||
name_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
symbol: Mapped[str] = mapped_column(String(8), default="") # ♈
|
||||
element: Mapped[str] = mapped_column(String(8), default="") # 火 / 土 / 风 / 水
|
||||
start_month: Mapped[int] = mapped_column(Integer, default=1)
|
||||
start_day: Mapped[int] = mapped_column(Integer, default=1)
|
||||
end_month: Mapped[int] = mapped_column(Integer, default=1)
|
||||
end_day: Mapped[int] = mapped_column(Integer, default=1)
|
||||
intro: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0) # = 黄经序号,0..11
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
"""请求/响应模型。字段与 01-总体设计.md 4.2 对齐。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime, time
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class RegisterIn(BaseModel):
|
||||
account: str = Field(description="邮箱或手机号")
|
||||
password: str = Field(min_length=6, max_length=64)
|
||||
nickname: str = ""
|
||||
|
||||
|
||||
class LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class QrLoginIn(BaseModel):
|
||||
"""设备屏二维码里的一次性票据。"""
|
||||
|
||||
code: str
|
||||
|
||||
|
||||
class UserOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: uuid.UUID
|
||||
email: str | None = None
|
||||
phone: str | None = None
|
||||
nickname: str = ""
|
||||
real_name: str | None = None
|
||||
|
||||
birthday: date | None = None
|
||||
birth_time: time | None = None
|
||||
birth_city: str | None = None
|
||||
birth_region_code: str | None = None
|
||||
birth_place: str | None = None
|
||||
|
||||
residence_region_code: str | None = None
|
||||
residence_city: str | None = None
|
||||
residence_place: str | None = None
|
||||
timezone: str | None = None
|
||||
|
||||
# 星盘:只落 code,名字/符号按码表实时补(见 user_out)
|
||||
sun_sign: str | None = None
|
||||
sun_sign_name: str | None = None
|
||||
sun_symbol: str | None = None
|
||||
sun_degree: float | None = None
|
||||
moon_sign: str | None = None
|
||||
moon_sign_name: str | None = None
|
||||
moon_symbol: str | None = None
|
||||
moon_degree: float | None = None
|
||||
|
||||
role: str = "user"
|
||||
status: str = "active"
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
def user_out(user: "User", zodiacs: dict[str, dict] | None = None) -> UserOut:
|
||||
"""把 user 行转成出参;给了星座码表就把 code 翻成名字与符号。"""
|
||||
out = UserOut.model_validate(user)
|
||||
for kind in ("sun", "moon"):
|
||||
code = getattr(user, f"{kind}_sign", None)
|
||||
info = (zodiacs or {}).get(code or "")
|
||||
if info:
|
||||
setattr(out, f"{kind}_sign_name", info["name_cn"])
|
||||
setattr(out, f"{kind}_symbol", info["symbol"])
|
||||
return out
|
||||
|
||||
|
||||
class LoginOut(BaseModel):
|
||||
token: str
|
||||
user: UserOut
|
||||
|
||||
|
||||
class ProfileIn(BaseModel):
|
||||
nickname: str | None = None
|
||||
real_name: str | None = None
|
||||
birthday: date | None = None
|
||||
birth_time: time | None = None
|
||||
# 码表 code:出生地决定时区(进而决定月亮星座),居住地决定日常天气与运势「当月」
|
||||
birth_region_code: str | None = None
|
||||
residence_region_code: str | None = None
|
||||
# 居住时区(IANA 名)。只影响日常语义,不影响星盘(星盘用出生地时区)
|
||||
timezone: str | None = Field(default=None, max_length=64)
|
||||
|
||||
|
||||
class DeviceOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: uuid.UUID
|
||||
chip_id: str
|
||||
model: str
|
||||
fw_version: str
|
||||
bound_at: datetime | None = None
|
||||
last_active_at: datetime | None = None
|
||||
|
||||
|
||||
class PairCodeIn(BaseModel):
|
||||
chip_id: str = Field(description="芯片 efuse MAC,十六进制 12~17 位")
|
||||
model: str = "JC3636K518C_I_W"
|
||||
fw_version: str = ""
|
||||
code: str | None = Field(default=None, description="设备自行生成的 6 位码;不传则服务端生成")
|
||||
|
||||
|
||||
class PairCodeOut(BaseModel):
|
||||
code: str
|
||||
expires_in: int
|
||||
server_time: str
|
||||
|
||||
|
||||
class PairStatusOut(BaseModel):
|
||||
status: str # waiting / bound / claimed / expired
|
||||
user_hint: str | None = None
|
||||
|
||||
|
||||
class PairClaimIn(BaseModel):
|
||||
code: str
|
||||
chip_id: str
|
||||
|
||||
|
||||
class PairClaimOut(BaseModel):
|
||||
token: str
|
||||
device_id: uuid.UUID
|
||||
user: UserOut
|
||||
|
||||
|
||||
class PairByCodeIn(BaseModel):
|
||||
code: str
|
||||
|
||||
|
||||
class AdminSettingIn(BaseModel):
|
||||
key: str
|
||||
value: str | int | dict | None
|
||||
|
||||
|
||||
class OkOut(BaseModel):
|
||||
ok: bool = True
|
||||
detail: str | None = None
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
"""码表(城市 / 星座)增删改的出入参。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class RegionOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
code: str
|
||||
name: str
|
||||
level: int
|
||||
parent_code: str | None = None
|
||||
timezone: str = "Asia/Shanghai"
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class RegionIn(BaseModel):
|
||||
code: str = Field(min_length=2, max_length=12, description="行政区划代码,六位,如 330106")
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
level: int = Field(default=1, ge=1, le=3)
|
||||
parent_code: str | None = None
|
||||
timezone: str = "Asia/Shanghai"
|
||||
enabled: bool = True
|
||||
sort_order: int = 0
|
||||
|
||||
|
||||
class RegionPatch(BaseModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
level: int | None = Field(default=None, ge=1, le=3)
|
||||
parent_code: str | None = None
|
||||
timezone: str | None = None
|
||||
enabled: bool | None = None
|
||||
sort_order: int | None = None
|
||||
|
||||
|
||||
class ZodiacOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
code: str
|
||||
name_cn: str
|
||||
name_en: str = ""
|
||||
symbol: str = ""
|
||||
element: str = ""
|
||||
start_month: int = 1
|
||||
start_day: int = 1
|
||||
end_month: int = 1
|
||||
end_day: int = 1
|
||||
intro: str = ""
|
||||
sort_order: int = 0
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class ZodiacIn(BaseModel):
|
||||
code: str = Field(min_length=2, max_length=16)
|
||||
name_cn: str = Field(min_length=1, max_length=16)
|
||||
name_en: str = ""
|
||||
symbol: str = ""
|
||||
element: str = ""
|
||||
start_month: int = Field(default=1, ge=1, le=12)
|
||||
start_day: int = Field(default=1, ge=1, le=31)
|
||||
end_month: int = Field(default=1, ge=1, le=12)
|
||||
end_day: int = Field(default=1, ge=1, le=31)
|
||||
intro: str = ""
|
||||
sort_order: int = Field(default=0, ge=0, le=11)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class ZodiacPatch(BaseModel):
|
||||
name_cn: str | None = Field(default=None, min_length=1, max_length=16)
|
||||
name_en: str | None = None
|
||||
symbol: str | None = None
|
||||
element: str | None = None
|
||||
start_month: int | None = Field(default=None, ge=1, le=12)
|
||||
start_day: int | None = Field(default=None, ge=1, le=31)
|
||||
end_month: int | None = Field(default=None, ge=1, le=12)
|
||||
end_day: int | None = Field(default=None, ge=1, le=31)
|
||||
intro: str | None = None
|
||||
sort_order: int | None = Field(default=None, ge=0, le=11)
|
||||
enabled: bool | None = None
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 月度运势
|
||||
class FortuneOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
zodiac_code: str
|
||||
scope: str # month(通用月度)/ ym(指定年月)
|
||||
period: str # '11' 或 '2026-11'
|
||||
title: str = ""
|
||||
title_en: str = ""
|
||||
content: str = ""
|
||||
content_en: str = ""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class FortuneIn(BaseModel):
|
||||
zodiac_code: str = Field(min_length=2, max_length=16)
|
||||
scope: str = Field(pattern="^(month|ym)$")
|
||||
period: str = Field(min_length=2, max_length=7, description="month 存 '11',ym 存 '2026-11'")
|
||||
title: str = Field(default="", max_length=64)
|
||||
title_en: str = Field(default="", max_length=128)
|
||||
content: str = ""
|
||||
content_en: str = ""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class FortunePatch(BaseModel):
|
||||
title: str | None = Field(default=None, max_length=64)
|
||||
title_en: str | None = Field(default=None, max_length=128)
|
||||
content: str | None = None
|
||||
content_en: str | None = None
|
||||
enabled: bool | None = None
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
"""固件管理的出入参。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class FirmwareOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: uuid.UUID
|
||||
model: str
|
||||
version: str
|
||||
channel: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
notes: str = ""
|
||||
notes_en: str = ""
|
||||
min_version: str = ""
|
||||
published: bool
|
||||
download_count: int = 0
|
||||
created_at: datetime | None = None
|
||||
published_at: datetime | None = None
|
||||
# 运行时补的统计:这个版本上跑着多少台设备
|
||||
device_count: int = 0
|
||||
|
||||
|
||||
class FirmwarePatch(BaseModel):
|
||||
notes: str | None = None
|
||||
notes_en: str | None = None
|
||||
channel: str | None = Field(default=None, pattern="^(stable|beta)$")
|
||||
min_version: str | None = None
|
||||
published: bool | None = None
|
||||
|
||||
|
||||
class UploadForm(BaseModel):
|
||||
"""multipart 表单里的文本字段(FastAPI 用 Form(...) 逐个取,这里只作说明与校验)。"""
|
||||
|
||||
version: str
|
||||
model: str = "JC3636K518C_I_W"
|
||||
channel: str = "stable"
|
||||
notes: str = ""
|
||||
notes_en: str = ""
|
||||
min_version: str = ""
|
||||
publish: bool = False
|
||||
|
||||
|
||||
class UpgradeIn(BaseModel):
|
||||
firmware_id: uuid.UUID
|
||||
|
||||
|
||||
class RolloutIn(BaseModel):
|
||||
firmware_id: uuid.UUID
|
||||
# 不传 = 所有低于该版本的设备;传了只推给这些设备
|
||||
device_ids: list[uuid.UUID] | None = None
|
||||
include_offline: bool = True
|
||||
|
||||
|
||||
class DeviceUpgradeOut(BaseModel):
|
||||
id: uuid.UUID
|
||||
chip_id: str
|
||||
model: str
|
||||
fw_version: str
|
||||
target_version: str = ""
|
||||
upgrade_state: str = ""
|
||||
upgrade_error: str = ""
|
||||
upgrade_at: datetime | None = None
|
||||
boot_slot: str = ""
|
||||
fw_updated_at: datetime | None = None
|
||||
bound_user_id: uuid.UUID | None = None
|
||||
user_label: str = ""
|
||||
last_active_at: datetime | None = None
|
||||
|
||||
|
||||
class CheckOut(BaseModel):
|
||||
update: bool
|
||||
version: str = ""
|
||||
size: int = 0
|
||||
sha256: str = ""
|
||||
notes: str = ""
|
||||
url: str = ""
|
||||
mandatory: bool = False
|
||||
reason: str = ""
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
"""星盘最小实现:由「出生日期 + 出生时间 + 时区」算太阳/月亮所在星座。
|
||||
|
||||
算法用瑞士星历(Swiss Ephemeris)的 Moshier 解析式,不依赖星历数据文件:
|
||||
太阳黄经误差 < 1″,月亮 < 0.1″,比「按日期查表」的近似算法稳得多,
|
||||
临近星座交界(比如 3 月 21 日 0 点)也不会判错。
|
||||
|
||||
要点:
|
||||
* 出生时间按出生地时区解释成 UTC —— 1986~1991 年内地实行过夏令时,
|
||||
``zoneinfo`` 带历史规则,能自动扣掉那一小时;
|
||||
* 黄经 0° = 白羊座 0°,每 30° 一个星座,序号与 ``zodiac_signs.sort_order`` 一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, time, timezone
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
import swisseph as swe
|
||||
|
||||
# 黄经顺序,作为码表缺行时的兜底
|
||||
ZODIAC_ORDER: tuple[str, ...] = (
|
||||
"aries", "taurus", "gemini", "cancer", "leo", "virgo",
|
||||
"libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces",
|
||||
)
|
||||
|
||||
DEFAULT_TZ = "Asia/Shanghai"
|
||||
|
||||
# 不传出生时间时按中午 12 点算:此时太阳/月亮都在当日中间位置,
|
||||
# 交界日也不会因为「差几小时」翻到相邻星座
|
||||
DEFAULT_TIME = time(12, 0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AstroResult:
|
||||
sun_sign: str
|
||||
moon_sign: str
|
||||
sun_degree: float # 星座内度数 0~30
|
||||
moon_degree: float
|
||||
sun_lon: float # 绝对黄经 0~360
|
||||
moon_lon: float
|
||||
tz: str
|
||||
utc_time: str
|
||||
|
||||
|
||||
def _jd_ut(dt_local: datetime, tz_name: str) -> tuple[float, datetime]:
|
||||
try:
|
||||
tz = ZoneInfo(tz_name)
|
||||
except (ZoneInfoNotFoundError, ValueError):
|
||||
tz, tz_name = ZoneInfo(DEFAULT_TZ), DEFAULT_TZ
|
||||
local = dt_local if dt_local.tzinfo else dt_local.replace(tzinfo=tz)
|
||||
utc = local.astimezone(timezone.utc)
|
||||
hours = utc.hour + utc.minute / 60 + utc.second / 3600 + utc.microsecond / 3.6e9
|
||||
return swe.julday(utc.year, utc.month, utc.day, hours), utc
|
||||
|
||||
|
||||
def _sign(lon: float) -> tuple[str, float]:
|
||||
lon %= 360.0
|
||||
return ZODIAC_ORDER[int(lon // 30.0) % 12], round(lon % 30.0, 2)
|
||||
|
||||
|
||||
def compute(birthday: date, birth_time: time | None = None, tz: str = DEFAULT_TZ) -> AstroResult:
|
||||
jd, utc = _jd_ut(datetime.combine(birthday, birth_time or DEFAULT_TIME), tz)
|
||||
|
||||
# FLG_MOSEPH:强制内置解析式,不需要 sepl_*.se1,部署零外部文件
|
||||
flags = swe.FLG_MOSEPH | swe.FLG_SPEED
|
||||
sun_lon = swe.calc_ut(jd, swe.SUN, flags)[0][0] % 360.0
|
||||
moon_lon = swe.calc_ut(jd, swe.MOON, flags)[0][0] % 360.0
|
||||
|
||||
sun_sign, sun_deg = _sign(sun_lon)
|
||||
moon_sign, moon_deg = _sign(moon_lon)
|
||||
return AstroResult(
|
||||
sun_sign=sun_sign,
|
||||
moon_sign=moon_sign,
|
||||
sun_degree=sun_deg,
|
||||
moon_degree=moon_deg,
|
||||
sun_lon=round(sun_lon, 4),
|
||||
moon_lon=round(moon_lon, 4),
|
||||
tz=tz,
|
||||
utc_time=utc.isoformat(timespec="minutes"),
|
||||
)
|
||||
|
|
@ -0,0 +1,135 @@
|
|||
"""码表读取:城市(省/市/区县)与星座。
|
||||
|
||||
两张表都是「管理端维护、全站只读」的低频数据,读的时候走 Redis 缓存,
|
||||
管理端一改就 invalidate,下次请求重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import Region, ZodiacSign
|
||||
from app.services import redis_store
|
||||
|
||||
REGION_TREE_KEY = "meta:regions:tree"
|
||||
ZODIAC_KEY = "meta:zodiacs"
|
||||
CACHE_TTL = 3600
|
||||
|
||||
|
||||
# ---------------- 城市 ----------------
|
||||
async def get_region(db: AsyncSession, code: str | None) -> Region | None:
|
||||
if not code:
|
||||
return None
|
||||
return await db.get(Region, code)
|
||||
|
||||
|
||||
async def region_chain(db: AsyncSession, code: str | None) -> list[Region]:
|
||||
"""自顶向下的路径:省 → 市 → 区县(走到哪层算哪层)。"""
|
||||
chain: list[Region] = []
|
||||
seen: set[str] = set()
|
||||
cur = await get_region(db, code)
|
||||
while cur is not None and cur.code not in seen:
|
||||
chain.append(cur)
|
||||
seen.add(cur.code)
|
||||
cur = await get_region(db, cur.parent_code)
|
||||
chain.reverse()
|
||||
return chain
|
||||
|
||||
|
||||
async def resolve_place(db: AsyncSession, code: str | None) -> tuple[str | None, str | None, str]:
|
||||
"""返回 (城市名, 完整路径, 时区)。
|
||||
|
||||
城市名取路径上最靠下的「市级」节点;直辖市没有市级节点就用省名,
|
||||
这样天气接口拿到的始终是一个可查询的城市名。
|
||||
"""
|
||||
chain = await region_chain(db, code)
|
||||
if not chain:
|
||||
return None, None, "Asia/Shanghai"
|
||||
|
||||
city = next((r.name for r in reversed(chain) if r.level == 2), None)
|
||||
if city is None:
|
||||
city = next((r.name for r in reversed(chain) if r.level == 1), chain[-1].name)
|
||||
place = " ".join(r.name for r in chain)
|
||||
tz = chain[-1].timezone or "Asia/Shanghai"
|
||||
return city, place, tz
|
||||
|
||||
|
||||
async def region_tree(db: AsyncSession) -> list[dict[str, Any]]:
|
||||
cached = await redis_store.cache_get(REGION_TREE_KEY)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Region).where(Region.enabled.is_(True)).order_by(Region.sort_order, Region.code)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
nodes: dict[str, dict[str, Any]] = {
|
||||
r.code: {"code": r.code, "name": r.name, "level": r.level, "children": []} for r in rows
|
||||
}
|
||||
roots: list[dict[str, Any]] = []
|
||||
for r in rows:
|
||||
node = nodes[r.code]
|
||||
parent = nodes.get(r.parent_code or "")
|
||||
if parent is None:
|
||||
roots.append(node)
|
||||
else:
|
||||
parent["children"].append(node)
|
||||
|
||||
# 叶子节点不带空 children,前端 Cascader 才认得出「可选终点」
|
||||
def trim(items: list[dict[str, Any]]) -> None:
|
||||
for it in items:
|
||||
if it["children"]:
|
||||
trim(it["children"])
|
||||
else:
|
||||
it.pop("children", None)
|
||||
|
||||
trim(roots)
|
||||
await redis_store.cache_set(REGION_TREE_KEY, roots, CACHE_TTL)
|
||||
return roots
|
||||
|
||||
|
||||
# ---------------- 星座 ----------------
|
||||
async def zodiacs(db: AsyncSession, include_disabled: bool = False) -> list[dict[str, Any]]:
|
||||
cached = None if include_disabled else await redis_store.cache_get(ZODIAC_KEY)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
stmt = select(ZodiacSign).order_by(ZodiacSign.sort_order)
|
||||
if not include_disabled:
|
||||
stmt = stmt.where(ZodiacSign.enabled.is_(True))
|
||||
rows = (await db.execute(stmt)).scalars().all()
|
||||
data = [
|
||||
{
|
||||
"code": z.code,
|
||||
"name_cn": z.name_cn,
|
||||
"name_en": z.name_en,
|
||||
"symbol": z.symbol,
|
||||
"element": z.element,
|
||||
"start_month": z.start_month,
|
||||
"start_day": z.start_day,
|
||||
"end_month": z.end_month,
|
||||
"end_day": z.end_day,
|
||||
"date_range": f"{z.start_month:02d}-{z.start_day:02d} ~ {z.end_month:02d}-{z.end_day:02d}",
|
||||
"intro": z.intro,
|
||||
"sort_order": z.sort_order,
|
||||
"enabled": z.enabled,
|
||||
}
|
||||
for z in rows
|
||||
]
|
||||
if not include_disabled:
|
||||
await redis_store.cache_set(ZODIAC_KEY, data, CACHE_TTL)
|
||||
return data
|
||||
|
||||
|
||||
async def zodiac_map(db: AsyncSession) -> dict[str, dict[str, Any]]:
|
||||
return {z["code"]: z for z in await zodiacs(db)}
|
||||
|
||||
|
||||
async def invalidate() -> None:
|
||||
await redis_store.cache_del(REGION_TREE_KEY, ZODIAC_KEY)
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
"""固件包服务:版本比较、落盘、镜像校验、选版本逻辑。
|
||||
|
||||
为什么不用第三方 semver 库:设备固件版本就是 ``MAJOR.MINOR.PATCH`` 三段,
|
||||
带后缀的(``0.2.0-rc1``)只需要「比正式版小」这一条规则,二十行代码够了,
|
||||
少一个依赖对部署更友好。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import Device, Firmware
|
||||
|
||||
# 固件包落盘目录:默认 <项目根>/data/firmware(运行时资源,不入库)
|
||||
DATA_DIR = settings.data_dir / "firmware"
|
||||
|
||||
MAX_SIZE = 8 * 1024 * 1024 # 8 MB:app3M 分区上限 3 MB,留足余量但不至于被灌爆
|
||||
CHUNK = 256 * 1024 # 流式读写块大小
|
||||
|
||||
VERSION_RE = re.compile(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:-([0-9A-Za-z.\-]{1,16}))?$")
|
||||
|
||||
|
||||
class FirmwareError(ValueError):
|
||||
"""上传/校验失败,调用方直接转 400。"""
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 版本
|
||||
def parse_version(text: str) -> tuple[int, int, int, str]:
|
||||
"""``0.2.0-rc1`` -> (0, 2, 0, "rc1");预发布段为空表示正式版。"""
|
||||
m = VERSION_RE.match((text or "").strip())
|
||||
if not m:
|
||||
raise FirmwareError(f"版本号格式不对:{text!r},应为 0.1.2 或 0.2.0-rc1")
|
||||
return int(m.group(1)), int(m.group(2)), int(m.group(3)), (m.group(4) or "")
|
||||
|
||||
|
||||
def version_code(text: str) -> int:
|
||||
"""压成整数便于 SQL 排序。预发布版减一档,保证 0.2.0-rc1 < 0.2.0。"""
|
||||
major, minor, patch, pre = parse_version(text)
|
||||
code = major * 1_000_000 + minor * 1_000 + patch
|
||||
return code - 1 if pre else code
|
||||
|
||||
|
||||
def compare(a: str, b: str) -> int:
|
||||
"""a>b 返回 1,相等 0,小于 -1。占位/空串视为最小。"""
|
||||
if not a:
|
||||
return 0 if not b else -1
|
||||
if not b:
|
||||
return 1
|
||||
try:
|
||||
ca, cb = version_code(a), version_code(b)
|
||||
except FirmwareError:
|
||||
return 0
|
||||
return (ca > cb) - (ca < cb)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 镜像校验
|
||||
def check_image(head: bytes, size: int) -> None:
|
||||
"""ESP32 应用镜像以 0xE9 开头(magic + segment count)。
|
||||
|
||||
这一步能拦住 90% 的误传:传了 zip、传了 bootloader、传了别的项目的 bin,
|
||||
都是在这里被挡下的,不会等到设备端刷砖才发现。
|
||||
"""
|
||||
if not head:
|
||||
raise FirmwareError("文件是空的")
|
||||
if head[0] != 0xE9:
|
||||
raise FirmwareError("不是 ESP32 应用镜像(首字节应为 0xE9),请确认选的是 xxx.ino.bin")
|
||||
if size < 64 * 1024:
|
||||
raise FirmwareError(f"镜像只有 {size} 字节,太小了,多半传错了文件")
|
||||
if size > MAX_SIZE:
|
||||
raise FirmwareError(f"镜像 {size / 1048576:.1f} MB 超过 {MAX_SIZE // 1048576} MB 上限")
|
||||
|
||||
|
||||
def safe_name(version: str, sha: str) -> str:
|
||||
"""落盘名带 8 位哈希:同版本重传不会互相覆盖,也便于肉眼核对。"""
|
||||
return f"{version}-{sha[:8]}.bin"
|
||||
|
||||
|
||||
async def save_stream(stream, filename: str) -> tuple[Path, int, str]:
|
||||
"""把上传流写到磁盘,边写边算 sha256。
|
||||
|
||||
先写 ``.part`` 再 rename:中途断开不会留下半个 bin 被当成有效固件。
|
||||
"""
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
tmp = DATA_DIR / f".upload-{uuid.uuid4().hex}.part"
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
head = b""
|
||||
try:
|
||||
with tmp.open("wb") as f:
|
||||
while True:
|
||||
chunk = await stream.read(CHUNK)
|
||||
if not chunk:
|
||||
break
|
||||
if not head:
|
||||
head = chunk[:16]
|
||||
size += len(chunk)
|
||||
if size > MAX_SIZE:
|
||||
raise FirmwareError(f"文件超过 {MAX_SIZE // 1048576} MB 上限")
|
||||
digest.update(chunk)
|
||||
f.write(chunk)
|
||||
check_image(head, size)
|
||||
sha = digest.hexdigest()
|
||||
target = DATA_DIR / safe_name(Path(filename).stem, sha)
|
||||
shutil.move(tmp, target)
|
||||
return target, size, sha
|
||||
except Exception:
|
||||
tmp.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def path_of(fw: Firmware) -> Path:
|
||||
return DATA_DIR / fw.filename
|
||||
|
||||
|
||||
def remove_file(fw: Firmware) -> None:
|
||||
try:
|
||||
path_of(fw).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 选版本
|
||||
async def latest_published(db: AsyncSession, model: str, channel: str = "stable") -> Firmware | None:
|
||||
stmt = (
|
||||
select(Firmware)
|
||||
.where(
|
||||
Firmware.model == model,
|
||||
Firmware.channel == channel,
|
||||
Firmware.published.is_(True),
|
||||
)
|
||||
.order_by(Firmware.version_code.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return await db.scalar(stmt)
|
||||
|
||||
|
||||
async def resolve_for_device(db: AsyncSession, device: Device) -> tuple[Firmware | None, bool]:
|
||||
"""设备该升到哪一版。返回 (固件, 是否管理员点名下发)。
|
||||
|
||||
优先级:管理员指定目标 > 同机型同通道的最新已发布版。
|
||||
|
||||
点名下发允许「降级」(回滚到已知好版本),所以这里不比版本大小;
|
||||
自动更新则必须严格新于当前版本,否则设备会陷入「升了又升」的死循环。
|
||||
"""
|
||||
if device.target_firmware_id:
|
||||
fw = await db.get(Firmware, device.target_firmware_id)
|
||||
if fw is not None:
|
||||
return fw, True
|
||||
|
||||
fw = await latest_published(db, device.model or "JC3636K518C_I_W", "stable")
|
||||
if fw is None:
|
||||
return None, False
|
||||
if compare(fw.version, device.fw_version) <= 0:
|
||||
return None, False
|
||||
if fw.min_version and compare(device.fw_version, fw.min_version) < 0:
|
||||
# 跨版本太远:先让设备升到 min_version 那一版(如果它存在且已发布)
|
||||
step = await db.scalar(
|
||||
select(Firmware)
|
||||
.where(
|
||||
Firmware.model == fw.model,
|
||||
Firmware.channel == fw.channel,
|
||||
Firmware.version == fw.min_version,
|
||||
Firmware.published.is_(True),
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
return (step, False) if step else (fw, False)
|
||||
return fw, False
|
||||
|
||||
|
||||
async def device_counts(db: AsyncSession, model: str | None = None) -> dict[str, int]:
|
||||
"""按版本统计在线设备数,管理端列表里显示「已有多少台在这个版本」。"""
|
||||
stmt = select(Device.fw_version, Device.id)
|
||||
if model:
|
||||
stmt = stmt.where(Device.model == model)
|
||||
rows = (await db.execute(stmt)).all()
|
||||
out: dict[str, int] = {}
|
||||
for ver, _id in rows:
|
||||
out[ver or ""] = out.get(ver or "", 0) + 1
|
||||
return out
|
||||
|
||||
|
||||
def env_storage_hint() -> str:
|
||||
return os.fspath(DATA_DIR)
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
"""月度运势读取与内置模板。
|
||||
|
||||
取值顺序(device / web 共用):
|
||||
1. 管理端写的指定年月(scope='ym', period='2026-11');
|
||||
2. 管理端写的通用月度(scope='month', period='11');
|
||||
3. 内置模板(只在前端/设备端兜底展示,不入库,管理端看不到)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models import Fortune
|
||||
|
||||
# 内置兜底模板:按「元素 × 月份主题」拼装,保证 12 星座 × 12 月不重样。
|
||||
# 管理端写入了对应条目后,就不再走这份兜底。
|
||||
MONTH_THEMES = {
|
||||
1: ("收心规划", "对上一年的复盘会带来意外的清晰感", "Take stock of last year — it brings unexpected clarity"),
|
||||
2: ("温养关系", "亲近的人需要你多一句肯定的回应", "People close to you need one more word of affirmation"),
|
||||
3: ("开动新局", "酝酿已久的想法值得在本月落地", "Long-simmering ideas deserve to land this month"),
|
||||
4: ("稳步深耕", "别被热闹的选项带走,深耕手头的事", "Don't chase the shiny options — deepen what's at hand"),
|
||||
5: ("弹性调整", "计划外的变动其实是校准方向的机会", "Off-plan changes are chances to recalibrate"),
|
||||
6: ("广结善缘", "一次随手的分享会带来新的连接", "A casual share brings a new connection"),
|
||||
7: ("劳逸平衡", "身体发出的信号比日程表更值得听", "Listen to your body over your calendar"),
|
||||
8: ("果敢决断", "犹豫太久的事,本月给出明确答案", "Give a clear answer to what you've long postponed"),
|
||||
9: ("查漏补缺", "细节里的隐患会在本月浮出水面", "Hidden details surface this month — fix them early"),
|
||||
10: ("收获沉淀", "前几个月的投入开始给出复利", "Months of investment start paying compounding returns"),
|
||||
11: ("深谋远虑", "为明年埋线:学习、储蓄、健康都算", "Plant seeds for next year: learning, savings, health"),
|
||||
12: ("收束归零", "给未完成的事一个体面的收尾", "Give unfinished business a graceful close"),
|
||||
}
|
||||
|
||||
ELEMENT_ADVICE = {
|
||||
"火": ("节奏可以快,但别省略热身", "Keep the pace fast, but never skip the warm-up"),
|
||||
"土": ("把大目标切成可核对的周清单", "Slice big goals into weekly checkable lists"),
|
||||
"风": ("把想法讲出来,讨论是最好的打磨", "Talk it out — discussion is the best polish"),
|
||||
"水": ("记录情绪的波动,它是重要的数据", "Track your moods; they are important data"),
|
||||
}
|
||||
|
||||
|
||||
def generic_fortune(sign_name: str, element: str, month: int, lang: str = "zh") -> dict:
|
||||
"""没入库也没有管理端文案时的兜底,按元素+月份拼一段。"""
|
||||
theme_zh, theme_body_zh, theme_body_en = MONTH_THEMES.get(month, MONTH_THEMES[1])
|
||||
adv_zh, adv_en = ELEMENT_ADVICE.get(element, ELEMENT_ADVICE["风"])
|
||||
if lang == "en":
|
||||
return {
|
||||
"scope": "generic",
|
||||
"title": f"{theme_body_en.split('—')[0].strip()}" if "—" in theme_body_en else theme_body_en,
|
||||
"content": (
|
||||
f"{sign_name}, the theme of this month is “{theme_body_en}”. "
|
||||
f"{adv_en}."
|
||||
),
|
||||
}
|
||||
return {
|
||||
"scope": "generic",
|
||||
"title": f"本月主题:{theme_zh}",
|
||||
"content": (
|
||||
f"{theme_body_zh}。{adv_zh}。"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
async def for_user(
|
||||
db: AsyncSession,
|
||||
sign_code: str | None,
|
||||
year: int,
|
||||
month: int,
|
||||
lang: str = "zh",
|
||||
) -> dict | None:
|
||||
"""按优先级取某星座当月运势。sign_code 为空(用户没填生日)返回 None。"""
|
||||
if not sign_code:
|
||||
return None
|
||||
|
||||
rows = (
|
||||
await db.execute(
|
||||
select(Fortune).where(
|
||||
Fortune.zodiac_code == sign_code,
|
||||
Fortune.enabled.is_(True),
|
||||
Fortune.scope.in_(("ym", "month")),
|
||||
Fortune.period.in_((f"{year}-{month:02d}", f"{month:02d}")),
|
||||
)
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
pick = next((r for r in rows if r.scope == "ym"), None) or next(
|
||||
(r for r in rows if r.scope == "month"), None
|
||||
)
|
||||
if pick is None:
|
||||
return None
|
||||
|
||||
text = pick.content if lang != "en" or not pick.content_en else pick.content_en
|
||||
title = pick.title if lang != "en" or not pick.title_en else pick.title_en
|
||||
return {
|
||||
"scope": pick.scope,
|
||||
"period": pick.period,
|
||||
"title": title,
|
||||
"content": text,
|
||||
"updated_at": pick.updated_at.isoformat() if pick.updated_at else None,
|
||||
}
|
||||
|
|
@ -0,0 +1,282 @@
|
|||
"""媒体服务:落盘、图片自动处理、设备清单与同步状态。
|
||||
|
||||
图片「自动处理」的边界(服务端一次做足,设备端零处理):
|
||||
- 任何能解码的格式(jpg/png/webp/gif 首帧/bmp)统一转 JPEG;
|
||||
- 最长边压到 720px(360 圆屏 ×2 余量,相册放大不糊);
|
||||
- EXIF/旋转信息直接烧进像素(ImageOps.exif_transpose),设备端不用懂方向;
|
||||
- 质量按内容定:先试 85,大于 1.5MB 再降到 70 —— 圆屏上看不出差别,
|
||||
但 TF 卡和同步流量都省一半以上。
|
||||
|
||||
音乐不做任何处理:MP3 原样透传,解码在副控。但会抽取 ID3v2 里内嵌的
|
||||
专辑封面(APIC),压成 480px JPEG 存到 covers/,网页列表当缩略图用;
|
||||
设备端唱片机本来就自己解内嵌封面,不走这份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import Device, DeviceMedia, MediaFile
|
||||
|
||||
# media 落盘目录:默认 <项目根>/data/media(运行时资源,不入库)
|
||||
DATA_DIR = settings.data_dir / "media"
|
||||
COVERS_DIR = DATA_DIR / "covers"
|
||||
|
||||
MAX_MUSIC_BYTES = 32 * 1024 * 1024 # 32MB:一首 320kbps 无损时长的 MP3 也够
|
||||
MAX_IMAGE_BYTES = 15 * 1024 * 1024 # 15MB:原图可以大,处理后会被压小
|
||||
MAX_IMAGE_EDGE = 720
|
||||
|
||||
MUSIC_EXT = {".mp3"}
|
||||
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
|
||||
|
||||
VALID_NAME_CHARS = set(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
" ._-()[]{}&#'@!+,;=~"
|
||||
)
|
||||
|
||||
# FAT32 只禁这几个字符 + 控制符;中文、日文、emoji 都能存(SD_MMC 走 UTF-8 长文件名)。
|
||||
# 之前用白名单只留 ASCII,结果「演唱会.mp3」被洗成「____.mp3」——设备上认不出来,
|
||||
# 网页上也全是一排下划线。改成黑名单。
|
||||
FAT32_FORBIDDEN = set('/\\:*?"<>|')
|
||||
|
||||
|
||||
class MediaError(ValueError):
|
||||
"""上传/处理失败,API 层直接转 400。"""
|
||||
|
||||
|
||||
def kind_of(filename: str) -> str:
|
||||
ext = Path(filename).suffix.lower()
|
||||
if ext in MUSIC_EXT:
|
||||
return "music"
|
||||
if ext in IMAGE_EXT:
|
||||
return "image"
|
||||
raise MediaError(f"不支持的类型 {ext or '(无扩展名)'},仅支持 MP3 音乐和图片")
|
||||
|
||||
|
||||
def sanitize_name(filename: str) -> str:
|
||||
"""TF 卡是 FAT32:只挡 / \\ : * ? " < > | 和控制符,其余(中文等)原样保留。"""
|
||||
name = Path(filename.replace("\\", "/")).name.strip()
|
||||
if not name:
|
||||
raise MediaError("文件名不能为空")
|
||||
name = "".join("_" if (c in FAT32_FORBIDDEN or ord(c) < 32) else c for c in name)
|
||||
name = name.strip(" .") # FAT32 不接受文件名以点或空格结尾
|
||||
if not name:
|
||||
raise MediaError("文件名不合法")
|
||||
if len(name.encode("utf-8")) > 200: # FAT32 长文件名上限 255 字节,留余量
|
||||
stem, ext = Path(name).stem, Path(name).suffix
|
||||
name = stem[:40] + "-" + uuid.uuid4().hex[:6] + ext
|
||||
return name
|
||||
|
||||
|
||||
def process_image(data: bytes) -> tuple[bytes, int, int]:
|
||||
"""转 JPEG + 限边 + 烧方向。返回 (jpeg 数据, 宽, 高)。"""
|
||||
try:
|
||||
from PIL import Image, ImageOps
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise MediaError("服务端缺少 Pillow,无法处理图片(pip install Pillow)") from e
|
||||
|
||||
try:
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
img.thumbnail((MAX_IMAGE_EDGE, MAX_IMAGE_EDGE), Image.LANCZOS)
|
||||
except Exception as e:
|
||||
raise MediaError(f"图片无法解码:{e}") from e
|
||||
|
||||
out = io.BytesIO()
|
||||
img.save(out, "JPEG", quality=85, optimize=True)
|
||||
if out.tell() > 1024 * 1024:
|
||||
out = io.BytesIO()
|
||||
img.save(out, "JPEG", quality=70, optimize=True)
|
||||
w, h = img.size
|
||||
return out.getvalue(), w, h
|
||||
|
||||
|
||||
def crc32_of(data: bytes) -> int:
|
||||
return zlib.crc32(data) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def extract_cover(mp3: bytes, media_id: uuid.UUID) -> str:
|
||||
"""抽 MP3 内嵌封面(ID3v2 APIC),压到 480px JPEG。没有封面返回 ""。
|
||||
|
||||
封面只是网页缩略图,压小即可;失败的任何情况(无 ID3、无 APIC、
|
||||
图像解不开)都静默降级为无封面,绝不能因为封面坏而拒绝歌曲。
|
||||
"""
|
||||
try:
|
||||
from mutagen.id3 import ID3
|
||||
except ImportError: # pragma: no cover
|
||||
return ""
|
||||
try:
|
||||
id3 = ID3(io.BytesIO(mp3), translate=False)
|
||||
except Exception:
|
||||
return ""
|
||||
apics = id3.getall("APIC") if id3 else []
|
||||
if not apics:
|
||||
return ""
|
||||
data = apics[0].data # 有 front 就用 front,否则拿第一个
|
||||
for a in apics:
|
||||
if getattr(a, "picture_type", 0) == 3: # 3 = front cover
|
||||
data = a.data
|
||||
break
|
||||
try:
|
||||
from PIL import Image
|
||||
img = Image.open(io.BytesIO(data))
|
||||
img = ImageOps_exif(img)
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
img.thumbnail((480, 480), Image.LANCZOS)
|
||||
except Exception:
|
||||
return ""
|
||||
out = io.BytesIO()
|
||||
img.save(out, "JPEG", quality=82, optimize=True)
|
||||
COVERS_DIR.mkdir(parents=True, exist_ok=True)
|
||||
fname = f"{media_id.hex[:12]}-cover.jpg"
|
||||
(COVERS_DIR / fname).write_bytes(out.getvalue())
|
||||
return fname
|
||||
|
||||
|
||||
def ImageOps_exif(img):
|
||||
"""exif_transpose 的窄封装:Pillow 老版本没有这个函数时直接原样返回。"""
|
||||
try:
|
||||
from PIL import ImageOps
|
||||
return ImageOps.exif_transpose(img)
|
||||
except Exception:
|
||||
return img
|
||||
|
||||
|
||||
def remove_cover(mf: MediaFile) -> None:
|
||||
if mf.cover_file:
|
||||
try:
|
||||
(COVERS_DIR / mf.cover_file).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def save_bytes(kind: str, name: str, data: bytes) -> tuple[str, int, int]:
|
||||
"""落盘并返回 (filename, size, crc32)。"""
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"{uuid.uuid4().hex[:12]}-{kind}{Path(name).suffix.lower()}"
|
||||
(DATA_DIR / filename).write_bytes(data)
|
||||
return filename, len(data), crc32_of(data)
|
||||
|
||||
|
||||
def remove_file(mf: MediaFile) -> None:
|
||||
try:
|
||||
(DATA_DIR / mf.filename).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def path_of(mf: MediaFile) -> Path:
|
||||
return DATA_DIR / mf.filename
|
||||
|
||||
|
||||
def max_size_for(kind: str) -> int:
|
||||
return MAX_MUSIC_BYTES if kind == "music" else MAX_IMAGE_BYTES
|
||||
|
||||
|
||||
async def manifest_for_device(db: AsyncSession, device: Device) -> list[MediaFile]:
|
||||
"""设备该同步哪些文件:绑定用户媒体库全量(设备端自己 diff,服务端不算差集)。"""
|
||||
if not device.bound_user_id:
|
||||
return []
|
||||
stmt = select(MediaFile).where(MediaFile.owner_user_id == device.bound_user_id).order_by(MediaFile.name)
|
||||
return list((await db.execute(stmt)).scalars())
|
||||
|
||||
|
||||
def manifest_rev(files: list[MediaFile]) -> str:
|
||||
"""清单指纹:内容、名字、数量任一变化都会变。
|
||||
|
||||
设备端只做字符串比较(快速路径),网页端也拿它判断「有没有删除/改名
|
||||
这类不体现在待下载数量里的变更」。设备同步完把 rev 回报上来。
|
||||
"""
|
||||
h = 0
|
||||
for f in sorted(files, key=lambda x: str(x.id)):
|
||||
h = zlib.crc32(f"{f.id}:{f.name}:{f.size}:{f.crc32}".encode(), h)
|
||||
return f"{h & 0xFFFFFFFF:08x}-{len(files):04x}"
|
||||
|
||||
|
||||
async def pending_for_device(
|
||||
db: AsyncSession, device: Device
|
||||
) -> tuple[list[MediaFile], list[MediaFile]]:
|
||||
"""返回 (待同步文件, 全量清单)。
|
||||
|
||||
待同步 = 清单里有、设备还没回报 synced 的;删除/改名不体现在这里,
|
||||
但会让 rev 变化,网页端据此提示「有变更待同步」。
|
||||
"""
|
||||
files = await manifest_for_device(db, device)
|
||||
if not files:
|
||||
return [], files
|
||||
synced = set(
|
||||
(
|
||||
await db.execute(
|
||||
select(DeviceMedia.media_id).where(
|
||||
DeviceMedia.device_id == device.id, DeviceMedia.state == "synced"
|
||||
)
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
return [f for f in files if f.id not in synced], files
|
||||
|
||||
|
||||
async def apply_report(
|
||||
db: AsyncSession,
|
||||
device: Device,
|
||||
synced: list[uuid.UUID],
|
||||
deleted: list[uuid.UUID],
|
||||
seq: int = 0,
|
||||
rev: str = "",
|
||||
) -> None:
|
||||
"""设备回报同步结果:upsert synced、删除已消失的记录。
|
||||
|
||||
只认属于该设备绑定用户的 media_id,防串库。``seq`` / ``rev`` 用来推进
|
||||
同步游标——设备只在用户点了「同步」之后才会走这一步。
|
||||
"""
|
||||
if device.bound_user_id is None:
|
||||
raise HTTPException(409, "device not bound")
|
||||
|
||||
owner_ids = set(
|
||||
(await db.execute(select(MediaFile.id).where(MediaFile.owner_user_id == device.bound_user_id))).scalars()
|
||||
)
|
||||
|
||||
for mid in synced:
|
||||
if mid not in owner_ids:
|
||||
continue
|
||||
row = await db.get(DeviceMedia, (device.id, mid))
|
||||
if row is None:
|
||||
db.add(DeviceMedia(device_id=device.id, media_id=mid, state="synced"))
|
||||
else:
|
||||
row.state = "synced"
|
||||
|
||||
for mid in deleted:
|
||||
row = await db.get(DeviceMedia, (device.id, mid))
|
||||
if row is not None:
|
||||
await db.delete(row)
|
||||
|
||||
if seq > 0:
|
||||
device.media_sync_ack = seq
|
||||
if rev:
|
||||
device.media_synced_rev = rev
|
||||
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def sync_states(db: AsyncSession, user_id: uuid.UUID) -> dict[uuid.UUID, int]:
|
||||
"""用户各媒体文件「已在多少台设备上」。网页列表的同步徽标数据源。"""
|
||||
stmt = (
|
||||
select(DeviceMedia.media_id)
|
||||
.join(Device, Device.id == DeviceMedia.device_id)
|
||||
.where(Device.bound_user_id == user_id, DeviceMedia.state == "synced")
|
||||
)
|
||||
out: dict[uuid.UUID, int] = {}
|
||||
for mid in (await db.execute(stmt)).scalars():
|
||||
out[mid] = out.get(mid, 0) + 1
|
||||
return out
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
"""Redis 访问层:会话、设备 token、配对码、限流、天气结果缓存。
|
||||
|
||||
平台配置(settings 表)不在此列——配置一律直读库,见文件内注释。
|
||||
键规划见 01-总体设计.md 4.1,键名与文档保持一致,便于运维排查。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import redis.asyncio as aioredis
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_client: aioredis.Redis | None = None
|
||||
|
||||
|
||||
def client() -> aioredis.Redis:
|
||||
global _client
|
||||
if _client is None:
|
||||
_client = aioredis.from_url(
|
||||
settings.redis_url,
|
||||
encoding="utf-8",
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=3,
|
||||
socket_timeout=3,
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
async def close() -> None:
|
||||
global _client
|
||||
if _client is not None:
|
||||
await _client.aclose()
|
||||
_client = None
|
||||
|
||||
|
||||
async def ping() -> bool:
|
||||
try:
|
||||
return bool(await client().ping())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ---------------- 会话(Web) ----------------
|
||||
async def save_session(token_hash: str, user_id: str) -> None:
|
||||
await client().set(f"sess:{token_hash}", user_id, ex=settings.session_ttl_seconds)
|
||||
|
||||
|
||||
async def load_session(token_hash: str) -> str | None:
|
||||
key = f"sess:{token_hash}"
|
||||
uid = await client().get(key)
|
||||
if uid:
|
||||
# 滑动续期:活跃用户不会中途掉线
|
||||
await client().expire(key, settings.session_ttl_seconds)
|
||||
return uid
|
||||
|
||||
|
||||
async def drop_session(token_hash: str) -> None:
|
||||
await client().delete(f"sess:{token_hash}")
|
||||
|
||||
|
||||
async def revoke_sessions_of(user_id: str) -> int:
|
||||
"""停用账号时踢掉它所有 Web 会话(sess:* 的 value 就是 user_id)。"""
|
||||
n = 0
|
||||
async for key in client().scan_iter(match="sess:*", count=200):
|
||||
if await client().get(key) == user_id:
|
||||
await client().delete(key)
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
# ---------------- 设备 token ----------------
|
||||
async def save_device_token(device_id: str, token_hash: str) -> None:
|
||||
await client().set(f"dtoken:{device_id}:{token_hash}", "1")
|
||||
|
||||
|
||||
async def load_device_token(device_id: str, token_hash: str) -> bool:
|
||||
return bool(await client().exists(f"dtoken:{device_id}:{token_hash}"))
|
||||
|
||||
|
||||
async def revoke_device_tokens(device_id: str) -> int:
|
||||
"""解绑/停用用户时吊销该设备全部 token。"""
|
||||
pattern = f"dtoken:{device_id}:*"
|
||||
n = 0
|
||||
async for key in client().scan_iter(match=pattern, count=200):
|
||||
await client().delete(key)
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
# ---------------- 扫码登录票据(设备屏上的二维码 → Web 会话) ----------------
|
||||
# 一码一用:设备每次打开二维码都重新申请,手机扫完即作废,
|
||||
# 所以码即便被旁人拍到,也只有第一个点开的人能换到会话。
|
||||
async def put_web_login(code: str, user_id: str, device_id: str, ttl: int) -> None:
|
||||
# 同一台设备只保留最新一张:屏幕上换过码,旧码(哪怕被截图拍下)立刻失效
|
||||
prev = await client().get(f"wlogin:dev:{device_id}")
|
||||
if prev and prev != code:
|
||||
await client().delete(f"wlogin:{prev}")
|
||||
await client().set(f"wlogin:{code}", json.dumps({"user_id": user_id, "device_id": device_id}), ex=ttl)
|
||||
await client().set(f"wlogin:dev:{device_id}", code, ex=ttl)
|
||||
|
||||
|
||||
async def pop_web_login(code: str) -> dict[str, Any] | None:
|
||||
key = f"wlogin:{code}"
|
||||
pipe = client().pipeline()
|
||||
pipe.get(key)
|
||||
pipe.delete(key)
|
||||
raw, _ = await pipe.execute()
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
# ---------------- 配对码 ----------------
|
||||
async def put_pair(code: str, payload: dict[str, Any], ttl: int) -> None:
|
||||
await client().set(f"pair:{code}", json.dumps(payload), ex=ttl)
|
||||
await client().delete(f"pair:try:{code}")
|
||||
|
||||
|
||||
async def get_pair(code: str) -> dict[str, Any] | None:
|
||||
raw = await client().get(f"pair:{code}")
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
async def mark_pair_bound(code: str, user_id: str) -> None:
|
||||
"""记账消费:码本身保留一小段 claim 窗口,供设备换 token。"""
|
||||
raw = await client().get(f"pair:{code}")
|
||||
if not raw:
|
||||
return
|
||||
data = json.loads(raw)
|
||||
data["bound_user_id"] = user_id
|
||||
await client().set(f"pair:{code}", json.dumps(data), ex=settings.pair_claim_window_seconds)
|
||||
await client().set(f"pair:claimed:{code}", user_id, ex=settings.pair_claim_window_seconds)
|
||||
|
||||
|
||||
async def consume_pair(code: str) -> None:
|
||||
await client().delete(f"pair:{code}", f"pair:try:{code}")
|
||||
|
||||
|
||||
async def bump_pair_try(code: str) -> int:
|
||||
"""每设备限速 5 次/分钟的简单实现。"""
|
||||
key = f"pair:try:{code}"
|
||||
n = await client().incr(key)
|
||||
if n == 1:
|
||||
await client().expire(key, 60)
|
||||
return int(n)
|
||||
|
||||
|
||||
# ---------------- 平台设置:不入缓存 ----------------
|
||||
# 平台配置(qweather.key/host 等)一律直读 settings 表,Redis 不参与。
|
||||
# 教训:曾把文档示例 Host 写进 settings:qweather.*,脏缓存压住库和 .env,
|
||||
# 导致和风持续 401 且改 .env 无效。运维配置写入频次极低,省这次主键查询不划算。
|
||||
|
||||
|
||||
# ---------------- 通用读缓存(码表等) ----------------
|
||||
async def cache_get(key: str) -> Any | None:
|
||||
raw = await client().get(f"cache:{key}")
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
async def cache_set(key: str, value: Any, ttl: int = 3600) -> None:
|
||||
await client().set(f"cache:{key}", json.dumps(value, ensure_ascii=False), ex=ttl)
|
||||
|
||||
|
||||
async def cache_del(*keys: str) -> None:
|
||||
if keys:
|
||||
await client().delete(*[f"cache:{k}" for k in keys])
|
||||
|
||||
|
||||
# ---------------- 天气缓存 ----------------
|
||||
async def get_weather(city: str) -> dict[str, Any] | None:
|
||||
raw = await client().get(f"weather:{city}")
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
|
||||
async def set_weather(city: str, payload: dict[str, Any]) -> None:
|
||||
await client().set(
|
||||
f"weather:{city}", json.dumps(payload, ensure_ascii=False), ex=settings.weather_cache_seconds
|
||||
)
|
||||
|
||||
|
||||
async def clear_weather_cache() -> int:
|
||||
"""改了 Key/Host 之后清空天气缓存,避免继续吐旧数据。"""
|
||||
n = 0
|
||||
async for key in client().scan_iter(match="weather:*", count=200):
|
||||
await client().delete(key)
|
||||
n += 1
|
||||
return n
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
"""和风天气聚合:服务端持有 Key/Host,设备只拿精简结果。
|
||||
|
||||
配置优先级:平台设置(库)> .env;配置直读库不缓存,只有查询结果进 Redis。
|
||||
缓存键 ``weather:{city}``,TTL 30 分钟(01-总体设计.md 3.4)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import PlatformSetting
|
||||
from app.services import redis_store
|
||||
|
||||
|
||||
class WeatherNotConfigured(RuntimeError):
|
||||
"""缺 API Host:和风新账号必须用专属域名,否则一律 403 Invalid Host。"""
|
||||
|
||||
|
||||
class WeatherUpstreamError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def _platform_value(db: AsyncSession, key: str) -> str | None:
|
||||
"""平台配置直读库,不走 Redis。
|
||||
|
||||
配置是运维级的低频写入,读一次主键查询成本可忽略;一旦进缓存,一条写错的
|
||||
值(如文档示例 Host ``abc1234xyz.re.qweatherapi.com``)会压住库和 .env,
|
||||
只能手动清 Redis 才能恢复——这类故障不值得为省一次查询去承担。
|
||||
"""
|
||||
row = await db.get(PlatformSetting, key)
|
||||
return str(row.value) if row and row.value else None
|
||||
|
||||
|
||||
async def _conf(db: AsyncSession) -> tuple[str, str]:
|
||||
key = await _platform_value(db, "qweather.key") or settings.qweather_key
|
||||
host = await _platform_value(db, "qweather.host") or settings.qweather_host
|
||||
if not key or not host:
|
||||
raise WeatherNotConfigured(
|
||||
"和风天气未配置:登录和风控制台 → 设置,复制账号专属 API Host"
|
||||
"(形如 abc1234xyz.re.qweatherapi.com)填入 QWEATHER_HOST 或管理端设置"
|
||||
)
|
||||
h = host.strip().rstrip("/")
|
||||
if not h.startswith(("http://", "https://")):
|
||||
h = "https://" + h
|
||||
return key, h
|
||||
|
||||
|
||||
async def _get(http: httpx.AsyncClient, url: str, params: dict[str, Any], key: str = "") -> dict[str, Any]:
|
||||
# 和风新版:API Key 走 X-QW-Api-Key 头;JWT 走 Authorization: Bearer。
|
||||
# 早期文档里的 ?key= 查询参数对新建项目已不再生效(会返回 401),这里不再用。
|
||||
headers: dict[str, str] = {}
|
||||
if key:
|
||||
if key.count(".") == 2 and len(key) > 80: # JWT:xxx.yyy.zzz
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
else:
|
||||
headers["X-QW-Api-Key"] = key
|
||||
|
||||
resp = await http.get(url, params=params, headers=headers)
|
||||
if resp.status_code >= 400:
|
||||
raise WeatherUpstreamError(f"和风返回 HTTP {resp.status_code}")
|
||||
data = resp.json()
|
||||
# 新版错误体是 {"error": {"status": 403, "title": ...}}
|
||||
if isinstance(data, dict) and "error" in data:
|
||||
err = data["error"]
|
||||
raise WeatherUpstreamError(
|
||||
f"和风错误 {err.get('status')}: {err.get('title', '')} {err.get('detail', '')}".strip()
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
async def _location_id(http: httpx.AsyncClient, host: str, key: str, city: str) -> tuple[str, str]:
|
||||
"""城市名 → LocationID。返回 (id, 规范名)。"""
|
||||
data = await _get(http, f"{host}/geo/v2/city/lookup", {"location": city, "number": 1, "lang": "zh"}, key)
|
||||
items = data.get("location") or []
|
||||
if not items:
|
||||
raise WeatherUpstreamError(f"找不到城市:{city}")
|
||||
return items[0]["id"], items[0]["name"]
|
||||
|
||||
|
||||
def _slim(city: str, loc_id: str, now: dict[str, Any], hourly: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""设备端要的字段越少越好:360×360 屏只放得下这些。"""
|
||||
return {
|
||||
"ok": True,
|
||||
"city": city,
|
||||
"location_id": loc_id,
|
||||
"temp": int(now.get("temp", 0)),
|
||||
"feels": int(now.get("feelsLike", 0)),
|
||||
"text": now.get("text", ""),
|
||||
"code": now.get("icon", ""), # 和风图标码,固件据此画天气图标
|
||||
"humidity": int(now.get("humidity", 0)),
|
||||
"wind_dir": now.get("windDir", ""),
|
||||
"wind_scale": now.get("windScale", ""),
|
||||
"obs_time": now.get("obsTime", ""),
|
||||
"hourly": [
|
||||
{"time": h.get("fxTime", "")[11:16], "temp": int(h.get("temp", 0)),
|
||||
"text": h.get("text", ""), "code": h.get("icon", ""), "pop": int(h.get("pop", 0) or 0)}
|
||||
for h in hourly[:3]
|
||||
],
|
||||
"source": "qweather",
|
||||
}
|
||||
|
||||
|
||||
async def is_configured(db: AsyncSession) -> bool:
|
||||
"""有效配置(管理端设置优先)是否齐备,供 /healthz 使用。"""
|
||||
try:
|
||||
await _conf(db)
|
||||
return True
|
||||
except WeatherNotConfigured:
|
||||
return False
|
||||
|
||||
|
||||
async def now(db: AsyncSession, city: str) -> dict[str, Any]:
|
||||
cached = await redis_store.get_weather(city)
|
||||
if cached:
|
||||
cached["cached"] = True
|
||||
return cached
|
||||
|
||||
key, host = await _conf(db)
|
||||
timeout = httpx.Timeout(8.0, connect=5.0)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, headers={"Accept-Encoding": "gzip"}) as http:
|
||||
loc_id, name = await _location_id(http, host, key, city)
|
||||
current = await _get(http, f"{host}/v7/weather/now", {"location": loc_id, "lang": "zh"}, key)
|
||||
try:
|
||||
f24 = await _get(http, f"{host}/v7/weather/24h", {"location": loc_id, "lang": "zh"}, key)
|
||||
hourly = f24.get("hourly") or []
|
||||
except WeatherUpstreamError:
|
||||
hourly = [] # 24h 可能是付费套餐,缺了不影响当前天气
|
||||
except httpx.HTTPError as exc:
|
||||
# DNS/连接/超时都归到上游不可用,让设备拿到 502 而不是 500
|
||||
raise WeatherUpstreamError(f"和风请求失败:{exc.__class__.__name__}") from exc
|
||||
|
||||
payload = _slim(name or city, loc_id, current.get("now") or {}, hourly)
|
||||
await redis_store.set_weather(city, payload)
|
||||
return payload
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
"""Alembic 环境:异步引擎 + 从 .env 取连接串。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.session import Base
|
||||
import app.models # noqa: F401 确保所有表被导入
|
||||
|
||||
config = context.config
|
||||
config.set_main_option("sqlalchemy.url", settings.database_url)
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=settings.database_url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
compare_type=True,
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection: Connection) -> None:
|
||||
context.configure(connection=connection, target_metadata=target_metadata, compare_type=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
connectable = async_engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: str | None = ${repr(down_revision)}
|
||||
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
"""media files and device media
|
||||
|
||||
Revision ID: 067c3af368f8
|
||||
Revises: 602dc965eae4
|
||||
Create Date: 2026-11-05 11:16:35.755056
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = '067c3af368f8'
|
||||
down_revision: str | None = '602dc965eae4'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('media_files',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('owner_user_id', sa.UUID(), nullable=False),
|
||||
sa.Column('kind', sa.String(length=8), nullable=False),
|
||||
sa.Column('name', sa.String(length=160), nullable=False),
|
||||
sa.Column('size', sa.BigInteger(), nullable=False),
|
||||
sa.Column('crc32', sa.BigInteger(), nullable=False),
|
||||
sa.Column('filename', sa.String(length=128), nullable=False),
|
||||
sa.Column('original_name', sa.String(length=160), nullable=False),
|
||||
sa.Column('width', sa.Integer(), nullable=False),
|
||||
sa.Column('height', sa.Integer(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id'], name=op.f('fk_media_files_owner_user_id_users'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_media_files')),
|
||||
sa.UniqueConstraint('owner_user_id', 'name', name='uq_media_name')
|
||||
)
|
||||
op.create_index(op.f('ix_media_files_owner_user_id'), 'media_files', ['owner_user_id'], unique=False)
|
||||
op.create_table('device_media',
|
||||
sa.Column('device_id', sa.UUID(), nullable=False),
|
||||
sa.Column('media_id', sa.UUID(), nullable=False),
|
||||
sa.Column('state', sa.String(length=12), nullable=False),
|
||||
sa.Column('synced_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['device_id'], ['devices.id'], name=op.f('fk_device_media_device_id_devices'), ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['media_id'], ['media_files.id'], name=op.f('fk_device_media_media_id_media_files'), ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('device_id', 'media_id', name=op.f('pk_device_media')),
|
||||
sa.UniqueConstraint('device_id', 'media_id', name='uq_device_media')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('device_media')
|
||||
op.drop_index(op.f('ix_media_files_owner_user_id'), table_name='media_files')
|
||||
op.drop_table('media_files')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
"""init users devices settings
|
||||
|
||||
Revision ID: 254651241d66
|
||||
Revises:
|
||||
Create Date: 2026-11-04 11:31:24.668389
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = '254651241d66'
|
||||
down_revision: str | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('settings',
|
||||
sa.Column('key', sa.String(length=64), nullable=False),
|
||||
sa.Column('value', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||
sa.Column('updated_by', sa.UUID(), nullable=True),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('key', name=op.f('pk_settings'))
|
||||
)
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('email', sa.String(length=190), nullable=True),
|
||||
sa.Column('phone', sa.String(length=32), nullable=True),
|
||||
sa.Column('password_hash', sa.String(length=128), nullable=False),
|
||||
sa.Column('nickname', sa.String(length=64), nullable=False),
|
||||
sa.Column('real_name', sa.String(length=64), nullable=True),
|
||||
sa.Column('birthday', sa.Date(), nullable=True),
|
||||
sa.Column('birth_time', sa.Time(), nullable=True),
|
||||
sa.Column('birth_city', sa.String(length=64), nullable=True),
|
||||
sa.Column('role', sa.String(length=16), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_users'))
|
||||
)
|
||||
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
|
||||
op.create_index(op.f('ix_users_phone'), 'users', ['phone'], unique=True)
|
||||
op.create_table('devices',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('chip_id', sa.String(length=32), nullable=False),
|
||||
sa.Column('model', sa.String(length=64), nullable=False),
|
||||
sa.Column('fw_version', sa.String(length=32), nullable=False),
|
||||
sa.Column('bound_user_id', sa.UUID(), nullable=True),
|
||||
sa.Column('bound_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('last_active_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.ForeignKeyConstraint(['bound_user_id'], ['users.id'], name=op.f('fk_devices_bound_user_id_users'), ondelete='SET NULL'),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_devices'))
|
||||
)
|
||||
op.create_index(op.f('ix_devices_bound_user_id'), 'devices', ['bound_user_id'], unique=False)
|
||||
op.create_index(op.f('ix_devices_chip_id'), 'devices', ['chip_id'], unique=True)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_devices_chip_id'), table_name='devices')
|
||||
op.drop_index(op.f('ix_devices_bound_user_id'), table_name='devices')
|
||||
op.drop_table('devices')
|
||||
op.drop_index(op.f('ix_users_phone'), table_name='users')
|
||||
op.drop_index(op.f('ix_users_email'), table_name='users')
|
||||
op.drop_table('users')
|
||||
op.drop_table('settings')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
"""regions zodiac profile astro
|
||||
|
||||
Revision ID: 30eef1366efd
|
||||
Revises: 254651241d66
|
||||
Create Date: 2026-11-04 13:19:49.504045
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = '30eef1366efd'
|
||||
down_revision: str | None = '254651241d66'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('regions',
|
||||
sa.Column('code', sa.String(length=12), nullable=False),
|
||||
sa.Column('name', sa.String(length=64), nullable=False),
|
||||
sa.Column('level', sa.Integer(), nullable=False),
|
||||
sa.Column('parent_code', sa.String(length=12), nullable=True),
|
||||
sa.Column('timezone', sa.String(length=64), nullable=False),
|
||||
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('code', name=op.f('pk_regions'))
|
||||
)
|
||||
op.create_index(op.f('ix_regions_name'), 'regions', ['name'], unique=False)
|
||||
op.create_index(op.f('ix_regions_parent_code'), 'regions', ['parent_code'], unique=False)
|
||||
op.create_table('zodiac_signs',
|
||||
sa.Column('code', sa.String(length=16), nullable=False),
|
||||
sa.Column('name_cn', sa.String(length=16), nullable=False),
|
||||
sa.Column('name_en', sa.String(length=32), nullable=False),
|
||||
sa.Column('symbol', sa.String(length=8), nullable=False),
|
||||
sa.Column('element', sa.String(length=8), nullable=False),
|
||||
sa.Column('start_month', sa.Integer(), nullable=False),
|
||||
sa.Column('start_day', sa.Integer(), nullable=False),
|
||||
sa.Column('end_month', sa.Integer(), nullable=False),
|
||||
sa.Column('end_day', sa.Integer(), nullable=False),
|
||||
sa.Column('intro', sa.Text(), nullable=False),
|
||||
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('code', name=op.f('pk_zodiac_signs'))
|
||||
)
|
||||
op.add_column('users', sa.Column('birth_region_code', sa.String(length=12), nullable=True))
|
||||
op.add_column('users', sa.Column('birth_place', sa.String(length=128), nullable=True))
|
||||
op.add_column('users', sa.Column('residence_region_code', sa.String(length=12), nullable=True))
|
||||
op.add_column('users', sa.Column('residence_city', sa.String(length=64), nullable=True))
|
||||
op.add_column('users', sa.Column('residence_place', sa.String(length=128), nullable=True))
|
||||
op.add_column('users', sa.Column('sun_sign', sa.String(length=16), nullable=True))
|
||||
op.add_column('users', sa.Column('moon_sign', sa.String(length=16), nullable=True))
|
||||
op.add_column('users', sa.Column('sun_degree', sa.Numeric(precision=6, scale=2), nullable=True))
|
||||
op.add_column('users', sa.Column('moon_degree', sa.Numeric(precision=6, scale=2), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column('users', 'moon_degree')
|
||||
op.drop_column('users', 'sun_degree')
|
||||
op.drop_column('users', 'moon_sign')
|
||||
op.drop_column('users', 'sun_sign')
|
||||
op.drop_column('users', 'residence_place')
|
||||
op.drop_column('users', 'residence_city')
|
||||
op.drop_column('users', 'residence_region_code')
|
||||
op.drop_column('users', 'birth_place')
|
||||
op.drop_column('users', 'birth_region_code')
|
||||
op.drop_table('zodiac_signs')
|
||||
op.drop_index(op.f('ix_regions_parent_code'), table_name='regions')
|
||||
op.drop_index(op.f('ix_regions_name'), table_name='regions')
|
||||
op.drop_table('regions')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
"""device media sync cursor
|
||||
|
||||
Revision ID: 3dd02ef90e3c
|
||||
Revises: 067c3af368f8
|
||||
Create Date: 2026-11-05 12:34:01.645998
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = '3dd02ef90e3c'
|
||||
down_revision: str | None = '067c3af368f8'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# 已有设备行,必须带 server_default 才能加非空列
|
||||
# (device_media 的主键本来就是 (device_id, media_id),autogenerate 想补的
|
||||
# 冗余 unique 约束不加。)
|
||||
op.add_column('devices', sa.Column('media_sync_seq', sa.Integer(), nullable=False, server_default='0'))
|
||||
op.add_column('devices', sa.Column('media_sync_ack', sa.Integer(), nullable=False, server_default='0'))
|
||||
op.add_column('devices', sa.Column('media_synced_rev', sa.String(length=32), nullable=False, server_default=''))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('devices', 'media_synced_rev')
|
||||
op.drop_column('devices', 'media_sync_ack')
|
||||
op.drop_column('devices', 'media_sync_seq')
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
"""media file cover
|
||||
|
||||
Revision ID: 464bf9d382f4
|
||||
Revises: 3dd02ef90e3c
|
||||
Create Date: 2026-11-05 14:10:17.405159
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = '464bf9d382f4'
|
||||
down_revision: str | None = '3dd02ef90e3c'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_unique_constraint('uq_device_media', 'device_media', ['device_id', 'media_id'])
|
||||
op.add_column('media_files', sa.Column('cover_file', sa.String(length=128), nullable=False, server_default=''))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column('media_files', 'cover_file')
|
||||
op.drop_constraint('uq_device_media', 'device_media', type_='unique')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
"""firmwares and device upgrade state
|
||||
|
||||
Revision ID: 602dc965eae4
|
||||
Revises: d8b20b1fc56c
|
||||
Create Date: 2026-11-05 09:19:47.600266
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = '602dc965eae4'
|
||||
down_revision: str | None = 'd8b20b1fc56c'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('firmwares',
|
||||
sa.Column('id', sa.UUID(), nullable=False),
|
||||
sa.Column('model', sa.String(length=64), nullable=False),
|
||||
sa.Column('version', sa.String(length=32), nullable=False),
|
||||
sa.Column('version_code', sa.Integer(), nullable=False),
|
||||
sa.Column('channel', sa.String(length=16), nullable=False),
|
||||
sa.Column('size_bytes', sa.BigInteger(), nullable=False),
|
||||
sa.Column('sha256', sa.String(length=64), nullable=False),
|
||||
sa.Column('filename', sa.String(length=128), nullable=False),
|
||||
sa.Column('original_name', sa.String(length=160), nullable=False),
|
||||
sa.Column('notes', sa.Text(), nullable=False),
|
||||
sa.Column('notes_en', sa.Text(), nullable=False),
|
||||
sa.Column('min_version', sa.String(length=32), nullable=False),
|
||||
sa.Column('published', sa.Boolean(), nullable=False),
|
||||
sa.Column('download_count', sa.Integer(), nullable=False),
|
||||
sa.Column('created_by', sa.UUID(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.Column('published_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_firmwares')),
|
||||
sa.UniqueConstraint('model', 'channel', 'version', name='uq_firmware_version')
|
||||
)
|
||||
op.create_index(op.f('ix_firmwares_model'), 'firmwares', ['model'], unique=False)
|
||||
op.create_index(op.f('ix_firmwares_published'), 'firmwares', ['published'], unique=False)
|
||||
op.create_index(op.f('ix_firmwares_version_code'), 'firmwares', ['version_code'], unique=False)
|
||||
op.add_column('devices', sa.Column('target_firmware_id', sa.UUID(), nullable=True))
|
||||
# 已有设备行必须给默认值,否则 NOT NULL 加列会直接失败
|
||||
op.add_column('devices', sa.Column('target_version', sa.String(length=32), nullable=False, server_default=''))
|
||||
op.add_column('devices', sa.Column('upgrade_state', sa.String(length=16), nullable=False, server_default=''))
|
||||
op.add_column('devices', sa.Column('upgrade_error', sa.String(length=160), nullable=False, server_default=''))
|
||||
op.add_column('devices', sa.Column('upgrade_at', sa.DateTime(timezone=True), nullable=True))
|
||||
op.add_column('devices', sa.Column('boot_slot', sa.String(length=8), nullable=False, server_default=''))
|
||||
op.add_column('devices', sa.Column('fw_updated_at', sa.DateTime(timezone=True), nullable=True))
|
||||
op.create_index(op.f('ix_devices_target_firmware_id'), 'devices', ['target_firmware_id'], unique=False)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_devices_target_firmware_id'), table_name='devices')
|
||||
op.drop_column('devices', 'fw_updated_at')
|
||||
op.drop_column('devices', 'boot_slot')
|
||||
op.drop_column('devices', 'upgrade_at')
|
||||
op.drop_column('devices', 'upgrade_error')
|
||||
op.drop_column('devices', 'upgrade_state')
|
||||
op.drop_column('devices', 'target_version')
|
||||
op.drop_column('devices', 'target_firmware_id')
|
||||
op.drop_index(op.f('ix_firmwares_version_code'), table_name='firmwares')
|
||||
op.drop_index(op.f('ix_firmwares_published'), table_name='firmwares')
|
||||
op.drop_index(op.f('ix_firmwares_model'), table_name='firmwares')
|
||||
op.drop_table('firmwares')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
"""user timezone zodiac fortunes
|
||||
|
||||
Revision ID: d8b20b1fc56c
|
||||
Revises: 30eef1366efd
|
||||
Create Date: 2026-11-04 13:58:04.178022
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision: str = 'd8b20b1fc56c'
|
||||
down_revision: str | None = '30eef1366efd'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('zodiac_fortunes',
|
||||
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column('zodiac_code', sa.String(length=16), nullable=False),
|
||||
sa.Column('scope', sa.String(length=8), nullable=False),
|
||||
sa.Column('period', sa.String(length=7), nullable=False),
|
||||
sa.Column('title', sa.String(length=64), nullable=False),
|
||||
sa.Column('title_en', sa.String(length=128), nullable=False),
|
||||
sa.Column('content', sa.Text(), nullable=False),
|
||||
sa.Column('content_en', sa.Text(), nullable=False),
|
||||
sa.Column('enabled', sa.Boolean(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id', name=op.f('pk_zodiac_fortunes')),
|
||||
sa.UniqueConstraint('zodiac_code', 'scope', 'period', name='uq_fortune_period')
|
||||
)
|
||||
op.create_index(op.f('ix_zodiac_fortunes_zodiac_code'), 'zodiac_fortunes', ['zodiac_code'], unique=False)
|
||||
op.add_column('users', sa.Column('timezone', sa.String(length=64), nullable=True))
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_column('users', 'timezone')
|
||||
op.drop_index(op.f('ix_zodiac_fortunes_zodiac_code'), table_name='zodiac_fortunes')
|
||||
op.drop_table('zodiac_fortunes')
|
||||
# ### end Alembic commands ###
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
"""建管理员账号(幂等):已存在则重置口令并提权。
|
||||
|
||||
用法(在 server/ 下):
|
||||
../.venv/bin/python scripts/create_admin.py --account admin@nexbuddy.com --password 'NexBuddy2026'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy import select # noqa: E402
|
||||
|
||||
from app.core.security import hash_password # noqa: E402
|
||||
from app.db.session import SessionLocal, dispose_engine # noqa: E402
|
||||
from app.models import User # noqa: E402
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--account", required=True, help="邮箱或手机号")
|
||||
ap.add_argument("--password", required=True)
|
||||
ap.add_argument("--nickname", default="管理员")
|
||||
args = ap.parse_args()
|
||||
|
||||
account = args.account.strip()
|
||||
is_email = "@" in account
|
||||
field = User.email if is_email else User.phone
|
||||
value = account.lower() if is_email else account
|
||||
|
||||
async with SessionLocal() as db:
|
||||
user = await db.scalar(select(User).where(field == value))
|
||||
if user is None:
|
||||
user = User(
|
||||
email=value if is_email else None,
|
||||
phone=None if is_email else value,
|
||||
password_hash=hash_password(args.password),
|
||||
nickname=args.nickname,
|
||||
role="admin",
|
||||
status="active",
|
||||
)
|
||||
db.add(user)
|
||||
action = "created"
|
||||
else:
|
||||
user.password_hash = hash_password(args.password)
|
||||
user.role = "admin"
|
||||
user.status = "active"
|
||||
action = "updated"
|
||||
await db.commit()
|
||||
print(f"{action}: {value} (role=admin)")
|
||||
|
||||
await dispose_engine()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
"""初始化码表:城市(GB/T 2260 三级)+ 12 星座。
|
||||
|
||||
用法(在 server/ 下):
|
||||
../.venv/bin/python scripts/seed_catalog.py # 只补缺
|
||||
../.venv/bin/python scripts/seed_catalog.py --force # 覆盖为内置值
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy import select # noqa: E402
|
||||
|
||||
from app.core.config import settings # noqa: E402
|
||||
from app.db.session import SessionLocal, dispose_engine # noqa: E402
|
||||
from app.models import Region, ZodiacSign # noqa: E402
|
||||
|
||||
DATA = settings.data_dir / "regions.json"
|
||||
|
||||
ZODIACS = [
|
||||
("aries", "白羊座", "Aries", "♈", "火", 3, 21, 4, 19, "直接、行动力强,喜欢把想法立刻变成行动。"),
|
||||
("taurus", "金牛座", "Taurus", "♉", "土", 4, 20, 5, 20, "稳定、务实,重视感官体验与确定感。"),
|
||||
("gemini", "双子座", "Gemini", "♊", "风", 5, 21, 6, 21, "好奇、灵活,靠信息和交流理解世界。"),
|
||||
("cancer", "巨蟹座", "Cancer", "♋", "水", 6, 22, 7, 22, "敏感、护家,用情感记忆把人和人连起来。"),
|
||||
("leo", "狮子座", "Leo", "♌", "火", 7, 23, 8, 22, "热情、慷慨,需要被看见也愿意照亮别人。"),
|
||||
("virgo", "处女座", "Virgo", "♍", "土", 8, 23, 9, 22, "细致、讲方法,习惯把混乱整理成秩序。"),
|
||||
("libra", "天秤座", "Libra", "♎", "风", 9, 23, 10, 23, "讲平衡、重关系,天生在找那个刚刚好的点。"),
|
||||
("scorpio", "天蝎座", "Scorpio", "♏", "水", 10, 24, 11, 22, "专注、深刻,一旦投入就要看到底。"),
|
||||
("sagittarius", "射手座", "Sagittarius", "♐", "火", 11, 23, 12, 21, "乐观、向外,永远在去更远处的路上。"),
|
||||
("capricorn", "摩羯座", "Capricorn", "♑", "土", 12, 22, 1, 19, "克制、有耐心,用时间换成果。"),
|
||||
("aquarius", "水瓶座", "Aquarius", "♒", "风", 1, 20, 2, 18, "独立、理性,习惯站在局外看规则。"),
|
||||
("pisces", "双鱼座", "Pisces", "♓", "水", 2, 19, 3, 20, "共情、想象丰富,容易接收别人的情绪。"),
|
||||
]
|
||||
|
||||
|
||||
async def seed_regions(force: bool) -> tuple[int, int]:
|
||||
rows = json.loads(DATA.read_text("utf-8"))
|
||||
added = updated = 0
|
||||
async with SessionLocal() as db:
|
||||
existing = {r.code: r for r in (await db.execute(select(Region))).scalars().all()}
|
||||
for row in rows:
|
||||
cur = existing.get(row["code"])
|
||||
if cur is None:
|
||||
db.add(Region(**row))
|
||||
added += 1
|
||||
elif force:
|
||||
cur.name = row["name"]
|
||||
cur.level = row["level"]
|
||||
cur.parent_code = row["parent_code"]
|
||||
cur.timezone = row["timezone"]
|
||||
cur.sort_order = row["sort_order"]
|
||||
updated += 1
|
||||
await db.commit()
|
||||
return added, updated
|
||||
|
||||
|
||||
async def seed_zodiacs(force: bool) -> tuple[int, int]:
|
||||
added = updated = 0
|
||||
async with SessionLocal() as db:
|
||||
existing = {z.code: z for z in (await db.execute(select(ZodiacSign))).scalars().all()}
|
||||
for order, (code, cn, en, sym, el, sm, sd, em, ed, intro) in enumerate(ZODIACS):
|
||||
cur = existing.get(code)
|
||||
if cur is None:
|
||||
db.add(ZodiacSign(
|
||||
code=code, name_cn=cn, name_en=en, symbol=sym, element=el,
|
||||
start_month=sm, start_day=sd, end_month=em, end_day=ed,
|
||||
intro=intro, sort_order=order, enabled=True,
|
||||
))
|
||||
added += 1
|
||||
elif force:
|
||||
cur.name_cn, cur.name_en, cur.symbol, cur.element = cn, en, sym, el
|
||||
cur.start_month, cur.start_day, cur.end_month, cur.end_day = sm, sd, em, ed
|
||||
cur.intro, cur.sort_order = intro, order
|
||||
updated += 1
|
||||
await db.commit()
|
||||
return added, updated
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--force", action="store_true", help="覆盖已有记录的展示字段")
|
||||
args = ap.parse_args()
|
||||
|
||||
a1, u1 = await seed_regions(args.force)
|
||||
a2, u2 = await seed_zodiacs(args.force)
|
||||
print(f"regions: +{a1} ~{u1}")
|
||||
print(f"zodiacs: +{a2} ~{u2}")
|
||||
await dispose_engine()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
"""灌内置月度运势:12 星座 × 12 通用月度,中英各一份。
|
||||
|
||||
只灌 scope='month' 的通用模板(每年都适用);指定年月的运势由管理端按需写。
|
||||
已有条目不覆盖,--force 才覆盖。用法:../.venv/bin/python scripts/seed_fortunes.py [--force]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy import select # noqa: E402
|
||||
|
||||
from app.db.session import SessionLocal # noqa: E402
|
||||
from app.models import Fortune, ZodiacSign # noqa: E402
|
||||
from app.services.fortune import ELEMENT_ADVICE, MONTH_THEMES # noqa: E402
|
||||
|
||||
FORCE = "--force" in sys.argv
|
||||
|
||||
# 每个星座开个头,避免 144 条看起来像复制粘贴
|
||||
SIGN_LEADS = {
|
||||
"aries": ("势头很足", "Momentum is on your side"),
|
||||
"taurus": ("步子稳了", "Your footing is steady"),
|
||||
"gemini": ("想法多起来", "Ideas keep flowing"),
|
||||
"cancer": ("心绪安定", "Your mind settles"),
|
||||
"leo": ("气场全开", "Your presence is full-on"),
|
||||
"virgo": ("细节盘顺", "Details fall into place"),
|
||||
"libra": ("关系回暖", "Relationships warm up"),
|
||||
"scorpio": ("直觉在线", "Your intuition is sharp"),
|
||||
"sagittarius": ("视野打开", "Your horizon widens"),
|
||||
"capricorn": ("积累见效", "Your efforts compound"),
|
||||
"aquarius": ("思路清奇", "Fresh angles find you"),
|
||||
"pisces": ("感受力强", "Your sensitivity peaks"),
|
||||
}
|
||||
|
||||
|
||||
# 英文主题短名(做标题用;正文的 body_en 太长,塞进标题会变双冒号长句)
|
||||
THEME_EN = {
|
||||
1: "Reset & plan", 2: "Nurture bonds", 3: "Start something", 4: "Go deep",
|
||||
5: "Stay flexible", 6: "Widen your circle", 7: "Rest & recover", 8: "Decide boldly",
|
||||
9: "Fix the gaps", 10: "Harvest", 11: "Think ahead", 12: "Close the loop",
|
||||
}
|
||||
|
||||
|
||||
def build(sign: dict) -> dict:
|
||||
m_th = MONTH_THEMES # month -> (主题zh, 正文zh, 正文en)
|
||||
month = int(sign["period"])
|
||||
lead_zh, lead_en = SIGN_LEADS[sign["zodiac_code"]]
|
||||
adv_zh, adv_en = ELEMENT_ADVICE.get(sign["element"] or "风", ELEMENT_ADVICE["风"])
|
||||
theme_zh, body_zh, body_en = m_th[month]
|
||||
title_zh = f"{lead_zh}:{theme_zh}"
|
||||
title_en = f"{lead_en} · {THEME_EN[month]}"
|
||||
return {
|
||||
"title": title_zh,
|
||||
"title_en": title_en,
|
||||
"content": f"{lead_zh}。{body_zh}。{adv_zh}。",
|
||||
"content_en": f"{lead_en}. {body_en}. {adv_en}.",
|
||||
}
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with SessionLocal() as db:
|
||||
zmap = {z.code: z for z in (await db.execute(select(ZodiacSign))).scalars().all()}
|
||||
existing = {
|
||||
(f.zodiac_code, f.period)
|
||||
for f in (await db.execute(select(Fortune).where(Fortune.scope == "month"))).scalars()
|
||||
}
|
||||
added = skipped = 0
|
||||
for z in zmap.values():
|
||||
if not z.enabled:
|
||||
continue
|
||||
for month in range(1, 13):
|
||||
key = (z.code, f"{month:02d}")
|
||||
if key in existing and not FORCE:
|
||||
skipped += 1
|
||||
continue
|
||||
if key in existing:
|
||||
row = (
|
||||
await db.execute(
|
||||
select(Fortune).where(
|
||||
Fortune.zodiac_code == z.code,
|
||||
Fortune.scope == "month",
|
||||
Fortune.period == key[1],
|
||||
)
|
||||
)
|
||||
).scalars().first()
|
||||
data = build({"zodiac_code": z.code, "element": z.element, "period": key[1]})
|
||||
row.title, row.title_en = data["title"], data["title_en"]
|
||||
row.content, row.content_en = data["content"], data["content_en"]
|
||||
continue
|
||||
data = build({"zodiac_code": z.code, "element": z.element, "period": key[1]})
|
||||
db.add(Fortune(zodiac_code=z.code, scope="month", period=key[1], **data))
|
||||
added += 1
|
||||
await db.commit()
|
||||
print(f"added {added}, skipped {skipped}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
|
@ -0,0 +1,345 @@
|
|||
"""端到端冒烟:注册 → 发码 → 绑定 → 换 token → 资料/星盘 → 天气 → 解绑 → 码表管理。
|
||||
|
||||
用法:
|
||||
../.venv/bin/python scripts/smoke.py [http://127.0.0.1:8100]
|
||||
|
||||
管理端用例需要管理员账号,默认取环境变量 ADMIN_ACCOUNT / ADMIN_PASSWORD,
|
||||
不传则跳过那几条(不算失败)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8100").rstrip("/")
|
||||
ADMIN_ACCOUNT = os.getenv("ADMIN_ACCOUNT", "admin@nexbuddy.com")
|
||||
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "NexBuddy2026")
|
||||
CHIP = f"SMOKE{random.randint(0x10000000, 0x7FFFFFFF):08X}" # 13 chars,模拟 efuse MAC
|
||||
ACCOUNT = f"smoke{int(time.time())}@test.local"
|
||||
PASSWORD = "smoke-pass-123"
|
||||
|
||||
ok_count = 0
|
||||
|
||||
|
||||
def step(name: str, cond: bool, extra: str = "") -> None:
|
||||
global ok_count
|
||||
mark = "PASS" if cond else "FAIL"
|
||||
print(f"[{mark}] {name} {extra}")
|
||||
if cond:
|
||||
ok_count += 1
|
||||
else:
|
||||
raise SystemExit(f"中止于:{name}")
|
||||
|
||||
|
||||
with httpx.Client(base_url=BASE, timeout=15) as c:
|
||||
h = c.get("/healthz").json()
|
||||
step("healthz", h["ok"] and h["db"] and h["redis"], f"weather_ready={h['weather_ready']}")
|
||||
|
||||
r = c.post("/api/auth/register", json={"account": ACCOUNT, "password": PASSWORD, "nickname": "冒烟用户"})
|
||||
step("register", r.status_code == 201, f"{r.status_code}")
|
||||
web = r.json()
|
||||
u_tok = {"Authorization": f"Bearer {web['token']}"}
|
||||
step("first user is admin", web["user"]["role"] in ("admin", "user"), web["user"]["role"])
|
||||
|
||||
r = c.post("/api/auth/login", json={"account": ACCOUNT, "password": PASSWORD})
|
||||
step("login", r.status_code == 200, f"{r.status_code}")
|
||||
|
||||
r = c.post("/api/auth/login", json={"account": ACCOUNT, "password": "wrong-pass"})
|
||||
step("wrong password rejected", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
r = c.post("/device/v1/pair/code", json={"chip_id": CHIP, "fw_version": "0.1.0"})
|
||||
step("device asks code", r.status_code == 200, f"{r.status_code}")
|
||||
code = r.json()["code"]
|
||||
print(f" code = {code}")
|
||||
|
||||
r = c.get("/device/v1/pair/status", params={"code": code, "chip_id": CHIP})
|
||||
step("status waiting", r.json()["status"] == "waiting")
|
||||
|
||||
r = c.post("/api/devices/pair", json={"code": "000000"}, headers=u_tok)
|
||||
step("bad code rejected", r.status_code == 404, f"{r.status_code}")
|
||||
|
||||
r = c.post("/api/devices/pair", json={"code": code}, headers=u_tok)
|
||||
step("web binds device", r.status_code == 200, f"{r.status_code}")
|
||||
device_id = r.json()["id"]
|
||||
|
||||
r = c.get("/device/v1/pair/status", params={"code": code, "chip_id": CHIP})
|
||||
step("status bound", r.json()["status"] == "bound")
|
||||
|
||||
r = c.post("/device/v1/pair/claim", json={"code": code, "chip_id": CHIP})
|
||||
step("device claims token", r.status_code == 200, f"{r.status_code}")
|
||||
d_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
r = c.get("/device/v1/profile", headers=d_tok)
|
||||
step("device profile", r.status_code == 200 and r.json()["nickname"] == "冒烟用户")
|
||||
|
||||
r = c.get("/device/v1/profile", headers={"Authorization": "Bearer 00000000-0000-0000-0000-000000000000:bogus"})
|
||||
step("bogus device token rejected", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
r = c.get("/device/v1/weather", headers=d_tok)
|
||||
if r.status_code == 200:
|
||||
w = r.json()
|
||||
step("device weather", True, f"{w['city']} {w['temp']}°C {w['text']}")
|
||||
else:
|
||||
# 缺 Host → 503,凭据/配额问题 → 502,都应该是明确的上游错误而不是 500
|
||||
step("weather degrades cleanly", r.status_code in (502, 503),
|
||||
f"{r.status_code} {r.json().get('detail','')[:60]}")
|
||||
|
||||
r = c.get("/api/devices", headers=u_tok)
|
||||
step("device list", r.status_code == 200 and len(r.json()) == 1)
|
||||
|
||||
r = c.get("/api/meta/regions/tree", headers=u_tok)
|
||||
tree = r.json()
|
||||
step("region tree", r.status_code == 200 and tree["count"] > 3000, f"{tree['count']} 条")
|
||||
|
||||
r = c.get("/api/meta/zodiacs", headers=u_tok)
|
||||
step("zodiac table", r.status_code == 200 and r.json()["count"] == 12, f"{r.json()['count']} 个")
|
||||
|
||||
# 1995-06-18 中午出生在杭州:太阳必在双子,月亮由出生时间决定
|
||||
r = c.put("/api/user/profile", json={
|
||||
"birthday": "1995-06-18", "birth_time": "09:20",
|
||||
"birth_region_code": "330106", "residence_region_code": "310000",
|
||||
}, headers=u_tok)
|
||||
u = r.json()
|
||||
step("profile with region", r.status_code == 200 and u["birth_place"] == "浙江省 杭州市 西湖区",
|
||||
f'{u.get("birth_place")}')
|
||||
step("sun sign computed", u.get("sun_sign") == "gemini" and u.get("sun_sign_name") == "双子座",
|
||||
f'{u.get("sun_sign_name")} {u.get("sun_degree")}°')
|
||||
step("moon sign computed", bool(u.get("moon_sign_name")), f'{u.get("moon_sign_name")} {u.get("moon_degree")}°')
|
||||
step("residence resolved", u.get("residence_city") == "上海市", str(u.get("residence_city")))
|
||||
|
||||
r = c.post("/api/meta/astro/preview", json={
|
||||
"birthday": "1990-01-20", "birth_time": "23:50", "birth_region_code": "330106",
|
||||
}, headers=u_tok)
|
||||
step("astro preview", r.status_code == 200 and r.json()["sun"]["code"] == "aquarius",
|
||||
f'{r.json()["sun"]["name"]}')
|
||||
|
||||
# 居住时区:合法值生效,非法值 400
|
||||
r = c.put("/api/user/profile", json={"timezone": "Asia/Tokyo"}, headers=u_tok)
|
||||
step("timezone saved", r.status_code == 200 and r.json()["timezone"] == "Asia/Tokyo",
|
||||
str(r.json().get("timezone")))
|
||||
r = c.put("/api/user/profile", json={"timezone": "Mars/Olympus"}, headers=u_tok)
|
||||
step("bad timezone rejected", r.status_code == 400, f"{r.status_code}")
|
||||
c.put("/api/user/profile", json={"timezone": "Asia/Shanghai"}, headers=u_tok)
|
||||
|
||||
# 本月运势(Web 端)
|
||||
r = c.get("/api/meta/fortune", params={"lang": "zh"}, headers=u_tok)
|
||||
f_zh = r.json()
|
||||
step("my fortune zh", r.status_code == 200 and f_zh["fortune"] and len(f_zh["fortune"]["content"]) > 10,
|
||||
f'{f_zh["period"]} {f_zh["fortune"]["title"]}')
|
||||
r = c.get("/api/meta/fortune", params={"lang": "en"}, headers=u_tok)
|
||||
step("my fortune en", r.status_code == 200 and "the" in r.json()["fortune"]["content"].lower(),
|
||||
r.json()["fortune"]["title"][:40])
|
||||
|
||||
# 设备端星盘:太阳/月亮 + 本月运势,中英文各一次
|
||||
r = c.get("/device/v1/astro", headers=d_tok)
|
||||
a = r.json()
|
||||
step("device astro", r.status_code == 200 and a["sun"]["name"] == "双子座" and a["moon"]["name"],
|
||||
f'☉{a["sun"]["name"]} ☽{a["moon"]["name"]} {a["period"]}')
|
||||
step("device astro fortune", bool(a["fortune"]) and len(a["fortune"]["content"]) > 10,
|
||||
a["fortune"]["title"][:30])
|
||||
r = c.get("/device/v1/astro", params={"lang": "en"}, headers=d_tok)
|
||||
step("device astro en", r.status_code == 200 and r.json()["sun"]["name"] == "Gemini",
|
||||
r.json()["sun"]["name"])
|
||||
|
||||
r = c.get("/api/admin/regions", headers=u_tok)
|
||||
step("admin blocked for normal user", r.status_code == 403, f"{r.status_code}")
|
||||
|
||||
# 管理端:管理员登录后做一轮码表增删
|
||||
r = c.post("/api/auth/login", json={"account": ADMIN_ACCOUNT, "password": ADMIN_PASSWORD})
|
||||
if r.status_code == 200 and r.json()["user"]["role"] == "admin":
|
||||
a_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
tmp_code = f"99{random.randint(1000, 9999)}"
|
||||
r = c.post("/api/admin/regions", json={"code": tmp_code, "name": "冒烟地区", "level": 3,
|
||||
"parent_code": "330100"}, headers=a_tok)
|
||||
step("admin create region", r.status_code == 200, f"{r.status_code}")
|
||||
r = c.put(f"/api/admin/regions/{tmp_code}", json={"name": "冒烟地区2"}, headers=a_tok)
|
||||
step("admin update region", r.status_code == 200)
|
||||
r = c.delete(f"/api/admin/regions/{tmp_code}", headers=a_tok)
|
||||
step("admin delete region", r.status_code == 200)
|
||||
r = c.get("/api/admin/zodiacs", headers=a_tok)
|
||||
step("admin zodiac list", r.status_code == 200 and len(r.json()["items"]) == 12)
|
||||
|
||||
# 用户与设备管理
|
||||
r = c.get("/api/admin/users", headers=a_tok)
|
||||
users = r.json()["items"]
|
||||
me = next((u for u in users if u["email"] == ACCOUNT), None)
|
||||
step("admin user list with devices", r.status_code == 200 and me is not None and len(me["devices"]) == 1,
|
||||
f'{len(users)} 用户')
|
||||
|
||||
# 运势:写一条指定年月,设备端应立即取到它
|
||||
tmp_period = f"2099-{random.randint(1, 12):02d}"
|
||||
r = c.post("/api/admin/fortunes", json={
|
||||
"zodiac_code": "gemini", "scope": "ym", "period": tmp_period,
|
||||
"title": "冒烟运势", "content": "这是冒烟测试写入的指定年月运势文案。",
|
||||
"title_en": "Smoke", "content_en": "Smoke test monthly fortune.",
|
||||
}, headers=a_tok)
|
||||
step("admin create fortune", r.status_code == 200, tmp_period)
|
||||
r = c.get("/api/admin/fortunes", params={"zodiac_code": "gemini", "scope": "ym"}, headers=a_tok)
|
||||
row = next((x for x in r.json()["items"] if x["period"] == tmp_period), None)
|
||||
step("admin list fortune", row is not None)
|
||||
# 2099 年不会影响设备端「当月」,只验证 CRUD
|
||||
r = c.put(f"/api/admin/fortunes/{row['id']}", json={"title": "冒烟运势2"}, headers=a_tok)
|
||||
step("admin update fortune", r.status_code == 200)
|
||||
r = c.delete(f"/api/admin/fortunes/{row['id']}", headers=a_tok)
|
||||
step("admin delete fortune", r.status_code == 200)
|
||||
|
||||
# ---- 固件管理:上传 → 校验拦截 → 下发 → 设备检查/下载/上报 → 清理 ----
|
||||
# 用 beta 通道 + 9.9.x:不会污染 stable 的「自动更新最新版」,
|
||||
# 否则真机下次 check 就会去下载这个假镜像。版本号带随机尾数,
|
||||
# 上一轮若中途失败留下 9.9.x 也不会撞唯一约束。
|
||||
fw_ver = f"9.9.{random.randint(100, 999)}"
|
||||
fake = b"\xe9" + os.urandom(128 * 1024 - 1)
|
||||
files = {"file": ("smoke-fw.bin", fake, "application/octet-stream")}
|
||||
form = {"version": fw_ver, "channel": "beta", "notes": "冒烟固件", "publish": "true"}
|
||||
r = c.post("/api/admin/firmwares", files=files, data=form, headers=a_tok)
|
||||
step("admin upload firmware", r.status_code == 200, r.json().get("detail", "")[:40])
|
||||
|
||||
r = c.post("/api/admin/firmwares", files={"file": ("dup.bin", fake, "application/octet-stream")},
|
||||
data=form, headers=a_tok)
|
||||
step("duplicate version rejected", r.status_code == 409, f"{r.status_code}")
|
||||
|
||||
r = c.post("/api/admin/firmwares", files={"file": ("x.bin", b"not-an-image", "application/octet-stream")},
|
||||
data={**form, "version": "9.9.998"}, headers=a_tok)
|
||||
step("non-esp32 image rejected", r.status_code == 400, r.json().get("detail", "")[:40])
|
||||
|
||||
r = c.post("/api/admin/firmwares", files={"file": ("x.bin", fake, "application/octet-stream")},
|
||||
data={**form, "version": "v1"}, headers=a_tok)
|
||||
step("bad version rejected", r.status_code == 400, r.json().get("detail", "")[:40])
|
||||
|
||||
r = c.get("/api/admin/firmwares", headers=a_tok)
|
||||
fw = next((x for x in r.json()["items"] if x["version"] == fw_ver), None)
|
||||
step("admin firmware list", fw is not None and fw["size_bytes"] == len(fake))
|
||||
fw_id = fw["id"]
|
||||
|
||||
# beta 包不进自动更新通道(stable 上若有已发布新版,这里只会给那一版,绝不会给 9.9.x)
|
||||
r = c.get("/device/v1/firmware/check", headers=d_tok)
|
||||
step("beta not auto-delivered", r.json().get("version") != fw_ver,
|
||||
f'update={r.json()["update"]} version={r.json().get("version") or "-"}')
|
||||
|
||||
r = c.post(f"/api/admin/devices/{device_id}/upgrade", json={"firmware_id": fw_id}, headers=a_tok)
|
||||
step("admin push upgrade", r.status_code == 200, r.json().get("detail", ""))
|
||||
|
||||
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
|
||||
step("delete blocked while targeted", r.status_code == 400, f"{r.status_code}")
|
||||
|
||||
r = c.get("/device/v1/firmware/check", headers=d_tok)
|
||||
chk = r.json()
|
||||
step("device sees forced update", chk["update"] and chk["version"] == fw_ver and chk["mandatory"],
|
||||
f'{chk["version"]} {chk["size"]}B')
|
||||
|
||||
r = c.get(chk["url"], headers=d_tok)
|
||||
got = hashlib.sha256(r.content).hexdigest()
|
||||
step("device downloads image", r.status_code == 200 and got == fw["sha256"] and len(r.content) == len(fake),
|
||||
f"{len(r.content)}B")
|
||||
|
||||
r = c.post("/device/v1/firmware/report", json={"version": fw_ver, "status": "success", "slot": "app0"},
|
||||
headers=d_tok)
|
||||
step("device reports success", r.status_code == 200 and r.json()["state"] == "success")
|
||||
|
||||
r = c.get("/api/admin/devices/upgrades", headers=a_tok)
|
||||
up = next((x for x in r.json()["items"] if x["id"] == device_id), None)
|
||||
step("admin sees new version", up is not None and up["fw_version"] == fw_ver and up["boot_slot"] == "app0",
|
||||
f'{up["fw_version"]} {up["upgrade_state"]}')
|
||||
|
||||
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
|
||||
step("admin delete firmware", r.status_code == 200, f"{r.status_code}")
|
||||
else:
|
||||
print("[SKIP] 管理员用例(账号不可用)")
|
||||
|
||||
# ---- TF 卡媒体:上传 → 清单 → 设备下载/回报 → 删除 → 清单消失 ----
|
||||
import io
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
# 图片:真实 PNG(32x48),服务端应转成 JPEG 并回填尺寸
|
||||
img = Image.new("RGB", (32, 48), (200, 60, 60))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "PNG")
|
||||
r = c.post("/api/media", files={"file": ("smoke-photo.png", buf.getvalue(), "image/png")}, headers=u_tok)
|
||||
step("upload image -> jpeg", r.status_code == 201 and r.json()["kind"] == "image" and r.json()["width"] == 32,
|
||||
f'{r.json().get("kind")} {r.json().get("width")}x{r.json().get("height")} {r.json().get("size")}B')
|
||||
img_id = r.json()["id"]
|
||||
|
||||
# 音乐:假 MP3(服务端不解码,只透传)
|
||||
mp3 = b"\xff\xfb\x90\x00" + os.urandom(64 * 1024)
|
||||
r = c.post("/api/media", files={"file": ("smoke-song.mp3", mp3, "audio/mpeg")}, headers=u_tok)
|
||||
step("upload music", r.status_code == 201 and r.json()["kind"] == "music", r.json().get("name", ""))
|
||||
song_id = r.json()["id"]
|
||||
|
||||
r = c.post("/api/media", files={"file": ("virus.exe", b"MZxxxx", "application/x-exe")}, headers=u_tok)
|
||||
step("bad type rejected", r.status_code == 400, r.json().get("detail", "")[:40])
|
||||
|
||||
# 同名重传 = 替换:id 不变、内容更新
|
||||
mp3b = b"\xff\xfb\x90\x00" + os.urandom(48 * 1024)
|
||||
r = c.post("/api/media", files={"file": ("smoke-song.mp3", mp3b, "audio/mpeg")}, headers=u_tok)
|
||||
step("same-name replace", r.status_code == 201 and r.json()["id"] == song_id and r.json()["size"] == len(mp3b),
|
||||
f'{r.json().get("size")}B')
|
||||
song_crc = r.json()["crc32"]
|
||||
|
||||
r = c.get("/api/media", headers=u_tok)
|
||||
step("media list", r.status_code == 200 and len(r.json()) == 2 and all(x["synced_devices"] == 0 for x in r.json()))
|
||||
|
||||
# 用户进「TF 卡文件」模块:先看到待同步数量,点「立即同步」才下发任务
|
||||
r = c.get(f"/api/devices/{device_id}/media/pending", headers=u_tok)
|
||||
st = r.json()
|
||||
step("web pending check", r.status_code == 200 and st["pending"] == 2 and st["seq"] == 0,
|
||||
f'pending={st["pending"]} seq={st["seq"]}')
|
||||
r = c.post(f"/api/devices/{device_id}/media/sync", headers=u_tok)
|
||||
step("web triggers sync", r.status_code == 200 and r.json()["seq"] == 1, f'seq={r.json().get("seq")}')
|
||||
r = c.get("/device/v1/media/pending", headers=d_tok)
|
||||
st = r.json()
|
||||
step("device sees request", st["seq"] == 1 and st["ack"] == 0, f'seq={st["seq"]} ack={st["ack"]}')
|
||||
sync_seq = st["seq"]
|
||||
|
||||
r = c.get("/device/v1/media/manifest", headers=d_tok)
|
||||
man = r.json()
|
||||
names = [x["name"] for x in man["items"]]
|
||||
step("device manifest", r.status_code == 200 and len(man["items"]) == 2 and "smoke-song.mp3" in names,
|
||||
f'rev={man["rev"]} {names}')
|
||||
|
||||
r = c.get(next(x["url"] for x in man["items"] if x["name"] == "smoke-song.mp3"), headers=d_tok)
|
||||
step("device downloads media", r.status_code == 200 and (zlib.crc32(r.content) & 0xFFFFFFFF) == song_crc,
|
||||
f"{len(r.content)}B")
|
||||
|
||||
r = c.post(
|
||||
"/device/v1/media/report",
|
||||
json={"synced": [img_id, song_id], "deleted": [], "seq": sync_seq, "rev": man["rev"]},
|
||||
headers=d_tok,
|
||||
)
|
||||
step("device reports sync", r.status_code == 200 and r.json()["synced"] == 2 and r.json()["ack"] == sync_seq,
|
||||
f'ack={r.json().get("ack")}')
|
||||
r = c.get(f"/api/devices/{device_id}/media/pending", headers=u_tok)
|
||||
st = r.json()
|
||||
step("web sees up to date", st["pending"] == 0 and st["rev"] == st["synced_rev"],
|
||||
f'pending={st["pending"]} rev={st["rev"]}')
|
||||
r = c.get("/api/media", headers=u_tok)
|
||||
step("web sees synced badge", all(x["synced_devices"] == 1 for x in r.json()),
|
||||
str([x["synced_devices"] for x in r.json()]))
|
||||
|
||||
# 用户删除 → 清单里消失 → 设备回报删除 → 徽标清零
|
||||
r = c.delete(f"/api/media/{img_id}", headers=u_tok)
|
||||
step("user deletes media", r.status_code == 204, f"{r.status_code}")
|
||||
r = c.get("/device/v1/media/manifest", headers=d_tok)
|
||||
man = r.json()
|
||||
step("manifest shrinks", len(man["items"]) == 1 and all(x["id"] != img_id for x in man["items"]),
|
||||
f'{len(man["items"])} items')
|
||||
r = c.post("/device/v1/media/report", json={"synced": [song_id], "deleted": [img_id]}, headers=d_tok)
|
||||
step("device reports deletion", r.status_code == 200 and r.json()["deleted"] == 1)
|
||||
|
||||
r = c.delete(f"/api/media/{song_id}", headers=u_tok)
|
||||
step("cleanup media", r.status_code == 204, f"{r.status_code}")
|
||||
|
||||
r = c.delete(f"/api/devices/{device_id}", headers=u_tok)
|
||||
step("unbind", r.status_code == 200, r.json().get("detail", ""))
|
||||
|
||||
r = c.get("/device/v1/profile", headers=d_tok)
|
||||
step("token revoked after unbind", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
print(f"\n{ok_count} 项全部通过 · chip_id={CHIP}")
|
||||
|
|
@ -0,0 +1,172 @@
|
|||
"""固件发布链路端到端冒烟:上传 → 发布 → 设备 check → 下载 → 上报 → 再 check。
|
||||
|
||||
用法(后端已 ./scripts/dev.sh 起来):
|
||||
.venv/bin/python scripts/smoke_firmware.py [http://127.0.0.1:8100]
|
||||
|
||||
管理端用例需要管理员账号,默认 admin@nexbuddy.com / NexBuddy2026。
|
||||
脚本会在库里留下一个 SMOKE-OTA 设备和一个 9.9.9 的固件包,跑完自动清掉。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8100").rstrip("/")
|
||||
ADMIN_ACCOUNT = os.getenv("ADMIN_ACCOUNT", "admin@nexbuddy.com")
|
||||
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "NexBuddy2026")
|
||||
CHIP = f"SMOKEOTA{random.randint(0x100000, 0xFFFFFF):06X}"
|
||||
ACCOUNT = f"otas{int(time.time())}@test.local"
|
||||
PASSWORD = "otas-pass-123"
|
||||
VERSION = f"9.9.{random.randint(1, 99)}"
|
||||
MODEL = "JC3636K518C_I_W"
|
||||
|
||||
# 假固件:真机不会拿它启动,这里只验服务端的字节流、sha、计数
|
||||
PAYLOAD = bytes([0xE9]) + os.urandom(200 * 1024)
|
||||
SHA = hashlib.sha256(PAYLOAD).hexdigest()
|
||||
|
||||
ok_count = 0
|
||||
|
||||
|
||||
def step(name: str, cond: bool, extra: str = "") -> None:
|
||||
global ok_count
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name} {extra}")
|
||||
if cond:
|
||||
ok_count += 1
|
||||
else:
|
||||
raise SystemExit(f"中止于:{name}")
|
||||
|
||||
|
||||
with httpx.Client(base_url=BASE, timeout=20) as c:
|
||||
# ---------------------------------------------------------------- 管理员
|
||||
r = c.post("/api/auth/login", json={"account": ADMIN_ACCOUNT, "password": ADMIN_PASSWORD})
|
||||
step("admin login", r.status_code == 200, f"{r.status_code}")
|
||||
a_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
# ---------------------------------------------------------------- 普通用户 + 绑一台假设备
|
||||
r = c.post("/api/auth/register", json={"account": ACCOUNT, "password": PASSWORD, "nickname": "OTA冒烟"})
|
||||
step("register user", r.status_code == 201, f"{r.status_code}")
|
||||
u_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
r = c.post("/device/v1/pair/code", json={"chip_id": CHIP, "model": MODEL, "fw_version": "0.1.0"})
|
||||
step("device asks code", r.status_code == 200, f"{r.status_code}")
|
||||
code = r.json()["code"]
|
||||
|
||||
r = c.post("/api/devices/pair", json={"code": code}, headers=u_tok)
|
||||
step("web binds device", r.status_code == 200, f"{r.status_code}")
|
||||
|
||||
r = c.post("/device/v1/pair/claim", json={"code": code, "chip_id": CHIP})
|
||||
step("device claims token", r.status_code == 200, f"{r.status_code}")
|
||||
d_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
# ---------------------------------------------------------------- 初始状态:接口可用(库里可能已经有别的已发布包)
|
||||
r = c.get("/device/v1/firmware/check", params={"current": "0.1.0", "lang": "zh"}, headers=d_tok)
|
||||
step("check reachable", r.status_code == 200 and "update" in r.json(), r.text[:90])
|
||||
print(f" 库里最新已发布:{r.json().get('version') or '(无)'}")
|
||||
|
||||
# ---------------------------------------------------------------- 上传(先不发布)
|
||||
files = {"file": (f"knob_os-{VERSION}.bin", PAYLOAD, "application/octet-stream")}
|
||||
data = {
|
||||
"version": VERSION,
|
||||
"model": MODEL,
|
||||
"channel": "stable",
|
||||
"notes": "冒烟用固件",
|
||||
"notes_en": "smoke firmware",
|
||||
"publish": "false",
|
||||
}
|
||||
r = c.post("/api/admin/firmwares", files=files, data=data, headers=a_tok)
|
||||
step("admin upload", r.status_code == 200, f"{r.status_code} {r.text[:120]}")
|
||||
|
||||
r = c.get("/api/admin/firmwares", headers=a_tok)
|
||||
rows = r.json()
|
||||
row = next((x for x in rows["items"] if x["version"] == VERSION), None)
|
||||
step("uploaded listed", row is not None)
|
||||
fw_id = row["id"]
|
||||
step("sha matches file", row["sha256"].lower() == SHA, f"{row['sha256'][:12]}… vs {SHA[:12]}…")
|
||||
step("size matches file", row["size_bytes"] == len(PAYLOAD), str(row["size_bytes"]))
|
||||
step("not published yet", row["published"] is False)
|
||||
|
||||
# 未发布 → 设备不该看见它(9.9.x 是最高的,一旦可见就会被选中)
|
||||
r = c.get("/device/v1/firmware/check", params={"current": "0.1.0"}, headers=d_tok)
|
||||
step("unpublished invisible", r.json().get("version") != VERSION, str(r.json().get("version")))
|
||||
|
||||
# ---------------------------------------------------------------- 发布
|
||||
r = c.put(f"/api/admin/firmwares/{fw_id}", json={"published": True}, headers=a_tok)
|
||||
step("publish", r.status_code == 200, f"{r.status_code}")
|
||||
|
||||
r = c.get("/device/v1/firmware/check", params={"current": "0.1.0", "lang": "zh"}, headers=d_tok)
|
||||
j = r.json()
|
||||
step("check -> update", j["update"] is True, j.get("version", ""))
|
||||
step("version correct", j["version"] == VERSION)
|
||||
step("size in payload", j["size"] == len(PAYLOAD), str(j["size"]))
|
||||
step("sha in payload", j["sha256"].lower() == SHA)
|
||||
step("url is relative", j["url"].startswith("/device/v1/firmware/"), j["url"])
|
||||
step("reason newer", j["reason"] in ("newer", "forced"), j["reason"])
|
||||
|
||||
# 同版本 → 不该再推
|
||||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||||
step("same version -> no update", r.json()["update"] is False)
|
||||
|
||||
# ---------------------------------------------------------------- 下载
|
||||
r = c.get(j["url"], headers=d_tok)
|
||||
step("download 200", r.status_code == 200, f"{r.status_code}")
|
||||
body = r.content
|
||||
step("download bytes match", body == PAYLOAD, f"{len(body)} bytes")
|
||||
step("download sha match", hashlib.sha256(body).hexdigest() == SHA)
|
||||
step("x-firmware-version header", r.headers.get("x-firmware-version") == VERSION,
|
||||
r.headers.get("x-firmware-version", "-"))
|
||||
|
||||
# 无 token → 401
|
||||
r = c.get(j["url"])
|
||||
step("download needs token", r.status_code in (401, 403), f"{r.status_code}")
|
||||
|
||||
# ---------------------------------------------------------------- 上报成功
|
||||
r = c.post("/device/v1/firmware/report",
|
||||
json={"version": VERSION, "status": "success", "slot": "app1"}, headers=d_tok)
|
||||
step("report success", r.status_code == 200 and r.json()["state"] == "success", r.text[:80])
|
||||
|
||||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||||
step("after report -> no update", r.json()["update"] is False)
|
||||
|
||||
# 设备列表里能看到新版本与槽位
|
||||
r = c.get("/api/admin/devices/upgrades", headers=a_tok)
|
||||
drows = r.json()
|
||||
items = drows["items"]
|
||||
dev = next((x for x in items if x["chip_id"] == CHIP), None)
|
||||
step("device row exists", dev is not None)
|
||||
step("device fw_version updated", dev and dev["fw_version"] == VERSION, (dev or {}).get("fw_version", "-"))
|
||||
step("device slot recorded", dev and dev["boot_slot"] == "app1", (dev or {}).get("boot_slot", "-"))
|
||||
step("upgrade_state success", dev and dev["upgrade_state"] == "success", (dev or {}).get("upgrade_state", "-"))
|
||||
|
||||
# ---------------------------------------------------------------- 上报失败
|
||||
r = c.post("/device/v1/firmware/report",
|
||||
json={"version": VERSION, "status": "failed", "error": "sha256 校验失败", "slot": "app1"},
|
||||
headers=d_tok)
|
||||
step("report failed", r.status_code == 200 and r.json()["state"] == "failed", r.text[:80])
|
||||
|
||||
# ---------------------------------------------------------------- 点名推送(强制)
|
||||
r = c.post(f"/api/admin/devices/{dev['id']}/upgrade",
|
||||
json={"firmware_id": fw_id}, headers=a_tok)
|
||||
step("force upgrade 200", r.status_code == 200, f"{r.status_code} {r.text[:100]}")
|
||||
r = c.get("/device/v1/firmware/check", params={"current": VERSION}, headers=d_tok)
|
||||
step("forced even if same version", r.json()["update"] is True and r.json()["mandatory"] is True,
|
||||
f"update={r.json().get('update')} mandatory={r.json().get('mandatory')}")
|
||||
|
||||
# 点名回滚到更低的版本也得能推(compare 会把 lower 判成"不升",点名要绕过它)
|
||||
r = c.post(f"/api/admin/firmwares/{fw_id}/rollout",
|
||||
json={"firmware_id": fw_id, "device_ids": [dev["id"]]}, headers=a_tok)
|
||||
step("rollout ok", r.status_code == 200, r.text[:80])
|
||||
|
||||
# ---------------------------------------------------------------- 清理
|
||||
r = c.delete(f"/api/admin/devices/{dev['id']}/upgrade", headers=a_tok)
|
||||
step("cancel target", r.status_code == 200, f"{r.status_code}")
|
||||
|
||||
r = c.delete(f"/api/admin/firmwares/{fw_id}", headers=a_tok)
|
||||
step("cleanup firmware", r.status_code == 200, f"{r.status_code} {r.text[:100]}")
|
||||
|
||||
print(f"\n全部通过:{ok_count} 项")
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
"""扫码免登录端到端:注册 → 配对 → 设备取票 → 手机端换会话 → 一次性校验。
|
||||
|
||||
用法:
|
||||
../.venv/bin/python scripts/smoke_weblogin.py [http://127.0.0.1:8100]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
|
||||
import httpx
|
||||
|
||||
BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8100").rstrip("/")
|
||||
CHIP = f"QRLOG{random.randint(0x10000000, 0x7FFFFFFF):08X}"
|
||||
ACCOUNT = f"qr{int(time.time())}@test.local"
|
||||
PASSWORD = "qr-pass-123"
|
||||
|
||||
ok_count = 0
|
||||
|
||||
|
||||
def step(name: str, cond: bool, extra: str = "") -> None:
|
||||
global ok_count
|
||||
print(f"[{'PASS' if cond else 'FAIL'}] {name} {extra}")
|
||||
if not cond:
|
||||
raise SystemExit(f"中止于:{name}")
|
||||
ok_count += 1
|
||||
|
||||
|
||||
with httpx.Client(base_url=BASE, timeout=15) as c:
|
||||
# ------------------------------------------------ 账号 + 设备配对
|
||||
r = c.post("/api/auth/register", json={"account": ACCOUNT, "password": PASSWORD, "nickname": "扫码用户"})
|
||||
step("register", r.status_code == 201, f"{r.status_code}")
|
||||
u_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
r = c.post("/device/v1/pair/code", json={"chip_id": CHIP, "fw_version": "0.2.0"})
|
||||
code = r.json()["code"]
|
||||
r = c.post("/api/devices/pair", json={"code": code}, headers=u_tok)
|
||||
step("web binds device", r.status_code == 200, f"{r.status_code}")
|
||||
device_id = r.json()["id"]
|
||||
|
||||
r = c.post("/device/v1/pair/claim", json={"code": code, "chip_id": CHIP})
|
||||
step("device claims token", r.status_code == 200, f"{r.status_code}")
|
||||
d_tok = {"Authorization": f"Bearer {r.json()['token']}"}
|
||||
|
||||
# ------------------------------------------------ 取票
|
||||
r = c.post("/device/v1/web-login/ticket", headers=d_tok)
|
||||
step("issue ticket", r.status_code == 200, f"{r.status_code} {r.text[:80]}")
|
||||
t = r.json()
|
||||
step("ticket shape", bool(t["code"]) and t["url"].endswith(f"/qr?t={t['code']}") and t["expires_in"] > 0,
|
||||
f"code={t['code']} url={t['url']}")
|
||||
step("ticket code charset", all(ch.isdigit() or ("A" <= ch <= "Z") for ch in t["code"]), t["code"])
|
||||
|
||||
# ------------------------------------------------ 手机端换会话
|
||||
r = c.post("/api/auth/qr-login", json={"code": t["code"]})
|
||||
step("qr-login ok", r.status_code == 200, f"{r.status_code}")
|
||||
sess = r.json()
|
||||
step("qr-login returns session", bool(sess["token"]) and sess["user"]["nickname"] == "扫码用户")
|
||||
|
||||
r = c.get("/api/user/profile", headers={"Authorization": f"Bearer {sess['token']}"})
|
||||
step("session usable", r.status_code == 200 and r.json()["nickname"] == "扫码用户")
|
||||
|
||||
# 手机端会话能直接看到这台设备
|
||||
r = c.get("/api/devices", headers={"Authorization": f"Bearer {sess['token']}"})
|
||||
step("session sees device", any(x["id"] == device_id for x in r.json()))
|
||||
|
||||
# ------------------------------------------------ 一次性
|
||||
r = c.post("/api/auth/qr-login", json={"code": t["code"]})
|
||||
step("ticket is one-shot", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
r = c.post("/api/auth/qr-login", json={"code": "ZZZZZZZZZZ"})
|
||||
step("unknown ticket rejected", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
# ------------------------------------------------ 新票据会作废旧码(同设备)
|
||||
r1 = c.post("/device/v1/web-login/ticket", headers=d_tok).json()
|
||||
r2 = c.post("/device/v1/web-login/ticket", headers=d_tok).json()
|
||||
step("new ticket differs", r1["code"] != r2["code"])
|
||||
step("newest ticket works", c.post("/api/auth/qr-login", json={"code": r2["code"]}).status_code == 200)
|
||||
r = c.post("/api/auth/qr-login", json={"code": r1["code"]})
|
||||
step("older ticket invalidated", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
# ------------------------------------------------ 未绑定设备不能取票
|
||||
chip2 = f"UNBND{random.randint(0x10000000, 0x7FFFFFFF):08X}"
|
||||
r = c.post("/device/v1/pair/code", json={"chip_id": chip2, "fw_version": "0.2.0"})
|
||||
r = c.post("/device/v1/pair/claim", json={"code": r.json()["code"], "chip_id": chip2})
|
||||
if r.status_code == 200:
|
||||
r = c.post("/device/v1/web-login/ticket", headers={"Authorization": f"Bearer {r.json()['token']}"})
|
||||
step("unbound device rejected", r.status_code == 409, f"{r.status_code}")
|
||||
|
||||
r = c.post("/device/v1/web-login/ticket")
|
||||
step("no token rejected", r.status_code == 401, f"{r.status_code}")
|
||||
|
||||
print(f"\n全部通过:{ok_count} 项")
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
node_modules/
|
||||
dist/
|
||||
.vite/
|
||||
*.local
|
||||
|
||||
# tsc 增量缓存
|
||||
tsconfig.tsbuildinfo
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#f6f7fb" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#0b0f19" media="(prefers-color-scheme: dark)" />
|
||||
<title>nex_buddy · 我的设备</title>
|
||||
<script>
|
||||
// 在 React 挂载前先定主题:否则深色系统下会先闪一帧白屏
|
||||
(function () {
|
||||
try {
|
||||
var saved = localStorage.getItem('nx.theme')
|
||||
var mode =
|
||||
saved === 'light' || saved === 'dark'
|
||||
? saved
|
||||
: window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
? 'dark'
|
||||
: 'light'
|
||||
document.documentElement.dataset.theme = mode
|
||||
document.documentElement.style.colorScheme = mode
|
||||
} catch (e) {}
|
||||
})()
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,26 @@
|
|||
{
|
||||
"name": "nex-buddy-web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"antd": "^5.22.0",
|
||||
"i18next": "^26.7.1",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-i18next": "^17.1.12",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.12",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.0.3"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import { Navigate, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import Login from './pages/Login'
|
||||
import QrLogin from './pages/QrLogin'
|
||||
import Bind from './pages/Bind'
|
||||
import Home from './pages/Home'
|
||||
import Admin from './pages/Admin'
|
||||
import { auth } from './api'
|
||||
|
||||
// 未登录一律回登录页,并把当前地址带进 ?next=,登录后原路返回
|
||||
function Guard({ children }: { children: React.ReactNode }) {
|
||||
const loc = useLocation()
|
||||
if (!auth.token) {
|
||||
const next = encodeURIComponent(loc.pathname + loc.search)
|
||||
return <Navigate to={`/login?next=${next}`} replace />
|
||||
}
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
{/* 设备屏二维码的落地页:自己换会话,不走 Guard(此时还没登录) */}
|
||||
<Route path="/qr" element={<QrLogin />} />
|
||||
<Route
|
||||
path="/bind"
|
||||
element={
|
||||
<Guard>
|
||||
<Bind />
|
||||
</Guard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
<Guard>
|
||||
<Home />
|
||||
</Guard>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<Guard>
|
||||
<Admin />
|
||||
</Guard>
|
||||
}
|
||||
/>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,397 @@
|
|||
// 后端契约的唯一出口:所有请求都走这里,方便统一处理 401 与错误文案。
|
||||
|
||||
const TOKEN_KEY = 'nx.token'
|
||||
const USER_KEY = 'nx.user'
|
||||
|
||||
export type SignInfo = { code: string; name: string; symbol: string; element: string; degree: number; date_range: string }
|
||||
|
||||
export type User = {
|
||||
id: string
|
||||
email?: string | null
|
||||
phone?: string | null
|
||||
nickname: string
|
||||
real_name?: string | null
|
||||
birthday?: string | null
|
||||
birth_time?: string | null
|
||||
birth_city?: string | null
|
||||
birth_region_code?: string | null
|
||||
birth_place?: string | null
|
||||
residence_region_code?: string | null
|
||||
residence_city?: string | null
|
||||
residence_place?: string | null
|
||||
timezone?: string | null
|
||||
sun_sign?: string | null
|
||||
sun_sign_name?: string | null
|
||||
sun_symbol?: string | null
|
||||
sun_degree?: number | null
|
||||
moon_sign?: string | null
|
||||
moon_sign_name?: string | null
|
||||
moon_symbol?: string | null
|
||||
moon_degree?: number | null
|
||||
role: 'user' | 'admin'
|
||||
status: string
|
||||
created_at?: string
|
||||
}
|
||||
|
||||
export type Device = {
|
||||
id: string
|
||||
chip_id: string
|
||||
model: string
|
||||
fw_version: string
|
||||
bound_at?: string | null
|
||||
last_active_at?: string | null
|
||||
}
|
||||
|
||||
export type RegionNode = { code: string; name: string; level: number; children?: RegionNode[] }
|
||||
|
||||
export type RegionRow = {
|
||||
code: string
|
||||
name: string
|
||||
level: number
|
||||
parent_code?: string | null
|
||||
timezone: string
|
||||
enabled: boolean
|
||||
sort_order: number
|
||||
}
|
||||
|
||||
export type Zodiac = {
|
||||
code: string
|
||||
name_cn: string
|
||||
name_en: string
|
||||
symbol: string
|
||||
element: string
|
||||
start_month: number
|
||||
start_day: number
|
||||
end_month: number
|
||||
end_day: number
|
||||
date_range?: string
|
||||
intro: string
|
||||
sort_order: number
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export type AstroPreview = {
|
||||
sun: SignInfo
|
||||
moon: SignInfo
|
||||
birth_place?: string | null
|
||||
timezone: string
|
||||
utc_time: string
|
||||
}
|
||||
|
||||
export type Fortune = {
|
||||
scope: 'month' | 'ym' | 'generic'
|
||||
period?: string
|
||||
title: string
|
||||
content: string
|
||||
updated_at?: string | null
|
||||
}
|
||||
|
||||
export type MyFortune = {
|
||||
period: string
|
||||
timezone: string
|
||||
sign?: string | null
|
||||
fortune?: Fortune | null
|
||||
}
|
||||
|
||||
export type FortuneRow = {
|
||||
id: number
|
||||
zodiac_code: string
|
||||
scope: 'month' | 'ym'
|
||||
period: string
|
||||
title: string
|
||||
title_en: string
|
||||
content: string
|
||||
content_en: string
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export type AdminUser = User & { devices: Device[] }
|
||||
|
||||
export type Firmware = {
|
||||
id: string
|
||||
model: string
|
||||
version: string
|
||||
channel: 'stable' | 'beta'
|
||||
size_bytes: number
|
||||
sha256: string
|
||||
notes: string
|
||||
notes_en: string
|
||||
min_version: string
|
||||
published: boolean
|
||||
download_count: number
|
||||
created_at?: string | null
|
||||
published_at?: string | null
|
||||
device_count: number
|
||||
}
|
||||
|
||||
export type DeviceUpgrade = {
|
||||
id: string
|
||||
chip_id: string
|
||||
model: string
|
||||
fw_version: string
|
||||
target_version: string
|
||||
upgrade_state: '' | 'pending' | 'downloading' | 'success' | 'failed' | 'canceled'
|
||||
upgrade_error: string
|
||||
upgrade_at?: string | null
|
||||
boot_slot: string
|
||||
fw_updated_at?: string | null
|
||||
bound_user_id?: string | null
|
||||
user_label: string
|
||||
last_active_at?: string | null
|
||||
}
|
||||
|
||||
// TF 卡媒体:网页上传 → 服务端处理 → 用户点「同步」后设备增量写入(music 原样透传;image 服务端已转 JPEG)
|
||||
export type MediaItem = {
|
||||
id: string
|
||||
kind: 'music' | 'image'
|
||||
name: string
|
||||
size: number
|
||||
crc32: number
|
||||
width: number
|
||||
height: number
|
||||
original_name: string
|
||||
created_at: string
|
||||
synced_devices: number
|
||||
// MP3 内嵌封面(上传时服务端已抽出);无封面时前端显示音符图标
|
||||
has_cover: boolean
|
||||
}
|
||||
|
||||
// 单台设备的待同步状态:pending 是待下载数量,rev 与 synced_rev 不同说明
|
||||
// 还有删除/改名这类不体现在数量上的变更。
|
||||
export type MediaPending = {
|
||||
device_id: string
|
||||
seq: number
|
||||
ack: number
|
||||
pending: number
|
||||
rev: string
|
||||
synced_rev: string
|
||||
items: { id: string; kind: 'music' | 'image'; name: string; size: number }[]
|
||||
}
|
||||
|
||||
export type UpgradesInfo = { total: number
|
||||
by_version: Record<string, number>
|
||||
latest: string
|
||||
pending: number
|
||||
items: DeviceUpgrade[]
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export const auth = {
|
||||
get token() {
|
||||
return localStorage.getItem(TOKEN_KEY)
|
||||
},
|
||||
get user(): User | null {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(USER_KEY) || 'null')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
},
|
||||
save(token: string, user: User) {
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
},
|
||||
saveUser(user: User) {
|
||||
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||
},
|
||||
clear() {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(USER_KEY)
|
||||
},
|
||||
}
|
||||
|
||||
async function req<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...((init.headers as Record<string, string>) || {}),
|
||||
}
|
||||
if (auth.token) headers.Authorization = `Bearer ${auth.token}`
|
||||
|
||||
const res = await fetch(path, { ...init, headers })
|
||||
const body = await res.json().catch(() => ({}))
|
||||
|
||||
// 只有「带着会话 token 打普通接口被打回」才是过期;登录/注册/扫码的 401
|
||||
// 是业务错误(密码错、票据失效),必须把后端 detail 透传给页面展示。
|
||||
if (res.status === 401 && auth.token && !path.startsWith('/api/auth/')) {
|
||||
auth.clear()
|
||||
throw new ApiError('登录已过期,请重新登录', 401)
|
||||
}
|
||||
if (!res.ok) {
|
||||
const detail = typeof body.detail === 'string' ? body.detail : `请求失败(${res.status})`
|
||||
throw new ApiError(detail, res.status)
|
||||
}
|
||||
return body as T
|
||||
}
|
||||
|
||||
/** multipart 专用:不能手动设 Content-Type,否则浏览器不会带 boundary。 */
|
||||
async function reqForm<T>(path: string, form: FormData): Promise<T> {
|
||||
const headers: Record<string, string> = {}
|
||||
if (auth.token) headers.Authorization = `Bearer ${auth.token}`
|
||||
const res = await fetch(path, { method: 'POST', body: form, headers })
|
||||
const body = await res.json().catch(() => ({}))
|
||||
if (res.status === 401 && auth.token) {
|
||||
auth.clear()
|
||||
throw new ApiError('登录已过期,请重新登录', 401)
|
||||
}
|
||||
if (!res.ok) {
|
||||
const detail = typeof body.detail === 'string' ? body.detail : `请求失败(${res.status})`
|
||||
throw new ApiError(detail, res.status)
|
||||
}
|
||||
return body as T
|
||||
}
|
||||
|
||||
const qs = (params: Record<string, unknown>) => {
|
||||
const sp = new URLSearchParams()
|
||||
Object.entries(params).forEach(([k, v]) => {
|
||||
if (v !== undefined && v !== null && v !== '') sp.set(k, String(v))
|
||||
})
|
||||
const s = sp.toString()
|
||||
return s ? `?${s}` : ''
|
||||
}
|
||||
|
||||
export const api = {
|
||||
register: (account: string, password: string, nickname = '') =>
|
||||
req<{ token: string; user: User }>('/api/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ account, password, nickname }),
|
||||
}),
|
||||
|
||||
login: (account: string, password: string) =>
|
||||
req<{ token: string; user: User }>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ account, password }),
|
||||
}),
|
||||
|
||||
/** 设备屏二维码里的一次性票据 → 会话(免密,一码一用) */
|
||||
qrLogin: (code: string) =>
|
||||
req<{ token: string; user: User }>('/api/auth/qr-login', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ code }),
|
||||
}),
|
||||
|
||||
logout: () => req<{ ok: boolean }>('/api/auth/logout', { method: 'POST' }),
|
||||
|
||||
profile: () => req<User>('/api/user/profile'),
|
||||
|
||||
updateProfile: (patch: Partial<User>) =>
|
||||
req<User>('/api/user/profile', { method: 'PUT', body: JSON.stringify(patch) }),
|
||||
|
||||
devices: () => req<Device[]>('/api/devices'),
|
||||
|
||||
pair: (code: string) =>
|
||||
req<Device>('/api/devices/pair', { method: 'POST', body: JSON.stringify({ code }) }),
|
||||
|
||||
unbind: (id: string) => req<{ ok: boolean; detail?: string }>(`/api/devices/${id}`, { method: 'DELETE' }),
|
||||
|
||||
health: () => req<{ ok: boolean; db: boolean; redis: boolean; weather_ready: boolean }>('/healthz'),
|
||||
|
||||
// 码表
|
||||
regionsTree: () => req<{ items: RegionNode[]; count: number }>('/api/meta/regions/tree'),
|
||||
zodiacs: () => req<{ items: Zodiac[]; count: number }>('/api/meta/zodiacs'),
|
||||
astroPreview: (payload: { birthday: string; birth_time?: string | null; birth_region_code?: string | null }) =>
|
||||
req<AstroPreview>('/api/meta/astro/preview', { method: 'POST', body: JSON.stringify(payload) }),
|
||||
myFortune: (lang: 'zh' | 'en') =>
|
||||
req<MyFortune>(`/api/meta/fortune?lang=${lang}`),
|
||||
|
||||
// TF 卡媒体库
|
||||
media: {
|
||||
list: () => req<MediaItem[]>('/api/media'),
|
||||
upload: (file: File) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
return reqForm<MediaItem>('/api/media', fd)
|
||||
},
|
||||
remove: (id: string) => req<unknown>(`/api/media/${id}`, { method: 'DELETE' }),
|
||||
// 设备侧:进模块时查一次待同步,用户点确认才下发
|
||||
pending: (deviceId: string) => req<MediaPending>(`/api/devices/${deviceId}/media/pending`),
|
||||
// <img>/<audio> 带不了 Authorization 头,token 走 query(后端只对这一条路径放宽)
|
||||
fileUrl: (id: string) => `/api/media/${id}/file${auth.token ? `?t=${encodeURIComponent(auth.token)}` : ''}`,
|
||||
coverUrl: (id: string) => `/api/media/${id}/cover${auth.token ? `?t=${encodeURIComponent(auth.token)}` : ''}`,
|
||||
},
|
||||
|
||||
// 管理端
|
||||
admin: {
|
||||
users: () => req<{ total: number; items: AdminUser[] }>('/api/admin/users'),
|
||||
setUserStatus: (userId: string, status: 'active' | 'disabled') =>
|
||||
req<{ ok: boolean }>(`/api/admin/users/${userId}/status?status=${status}`, { method: 'POST' }),
|
||||
unbindDevice: (deviceId: string) =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}`, { method: 'DELETE' }),
|
||||
revokeDevice: (deviceId: string) =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/revoke`, { method: 'POST' }),
|
||||
fortunes: (params?: { zodiac_code?: string; scope?: string; year?: number }) =>
|
||||
req<{ items: FortuneRow[] }>(`/api/admin/fortunes${qs(params || {})}`),
|
||||
createFortune: (body: Omit<FortuneRow, 'id'>) =>
|
||||
req<{ ok: boolean }>('/api/admin/fortunes', { method: 'POST', body: JSON.stringify(body) }),
|
||||
updateFortune: (id: number, body: Partial<FortuneRow>) =>
|
||||
req<{ ok: boolean }>(`/api/admin/fortunes/${id}`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
deleteFortune: (id: number) =>
|
||||
req<{ ok: boolean }>(`/api/admin/fortunes/${id}`, { method: 'DELETE' }),
|
||||
settings: () =>
|
||||
req<{ items: { key: string; value: unknown; updated_at?: string | null }[] }>('/api/admin/settings'),
|
||||
saveSetting: (key: string, value: string) =>
|
||||
req<{ ok: boolean }>('/api/admin/settings', { method: 'PUT', body: JSON.stringify({ key, value }) }),
|
||||
regions: (params: { q?: string; level?: number; page?: number; page_size?: number }) =>
|
||||
req<{ total: number; page: number; page_size: number; items: RegionRow[] }>(`/api/admin/regions${qs(params)}`),
|
||||
createRegion: (body: Omit<RegionRow, 'sort_order'> & { sort_order?: number }) =>
|
||||
req<{ ok: boolean; detail?: string }>('/api/admin/regions', { method: 'POST', body: JSON.stringify(body) }),
|
||||
updateRegion: (code: string, body: Partial<RegionRow>) =>
|
||||
req<{ ok: boolean }>(`/api/admin/regions/${code}`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
deleteRegion: (code: string) => req<{ ok: boolean }>(`/api/admin/regions/${code}`, { method: 'DELETE' }),
|
||||
importRegions: (mode: 'missing' | 'upsert' = 'missing') =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/regions/import?mode=${mode}`, { method: 'POST' }),
|
||||
zodiacs: () => req<{ items: Zodiac[] }>('/api/admin/zodiacs'),
|
||||
updateZodiac: (code: string, body: Partial<Zodiac>) =>
|
||||
req<{ ok: boolean }>(`/api/admin/zodiacs/${code}`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
createZodiac: (body: Zodiac) =>
|
||||
req<{ ok: boolean }>('/api/admin/zodiacs', { method: 'POST', body: JSON.stringify(body) }),
|
||||
deleteZodiac: (code: string) => req<{ ok: boolean }>(`/api/admin/zodiacs/${code}`, { method: 'DELETE' }),
|
||||
|
||||
// 固件
|
||||
firmwares: () =>
|
||||
req<{ items: Firmware[]; storage: string; max_size: number }>('/api/admin/firmwares'),
|
||||
uploadFirmware: (file: File, fields: Record<string, string>) => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
Object.entries(fields).forEach(([k, v]) => fd.append(k, v))
|
||||
return reqForm<{ ok: boolean; detail?: string }>('/api/admin/firmwares', fd)
|
||||
},
|
||||
updateFirmware: (id: string, patch: Partial<Firmware>) =>
|
||||
req<{ ok: boolean }>(`/api/admin/firmwares/${id}`, { method: 'PUT', body: JSON.stringify(patch) }),
|
||||
deleteFirmware: (id: string) => req<{ ok: boolean }>(`/api/admin/firmwares/${id}`, { method: 'DELETE' }),
|
||||
rolloutFirmware: (id: string, deviceIds?: string[]) =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/firmwares/${id}/rollout`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ firmware_id: id, device_ids: deviceIds ?? null }),
|
||||
}),
|
||||
// 下载要带 Bearer,直接 <a href> 不行,只能 fetch 成 blob 再点一下
|
||||
downloadFirmware: async (fw: Firmware) => {
|
||||
const res = await fetch(`/api/admin/firmwares/${fw.id}/download`, {
|
||||
headers: auth.token ? { Authorization: `Bearer ${auth.token}` } : {},
|
||||
})
|
||||
if (!res.ok) throw new ApiError(`下载失败(${res.status})`, res.status)
|
||||
const blob = await res.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `knob_os-${fw.version}.bin`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
},
|
||||
deviceUpgrades: (q?: string) =>
|
||||
req<UpgradesInfo>(`/api/admin/devices/upgrades${qs({ q })}`),
|
||||
pushUpgrade: (deviceId: string, firmwareId: string) =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/upgrade`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ firmware_id: firmwareId }),
|
||||
}),
|
||||
cancelUpgrade: (deviceId: string) =>
|
||||
req<{ ok: boolean; detail?: string }>(`/api/admin/devices/${deviceId}/upgrade`, { method: 'DELETE' }),
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import { Segmented } from 'antd'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { setLang, type Lang } from '../i18n'
|
||||
|
||||
/**
|
||||
* 顶栏语言切换:两个按钮直接点,比下拉少一步。
|
||||
* 窄屏只留「中 / EN」,全称藏在宽屏样式里(见 styles.css 的 .lang-full/.lang-short)。
|
||||
*/
|
||||
export default function LangSwitch() {
|
||||
const { i18n, t } = useTranslation()
|
||||
const lang: Lang = (i18n.language || 'zh').startsWith('en') ? 'en' : 'zh'
|
||||
return (
|
||||
<Segmented<Lang>
|
||||
className="lang-switch"
|
||||
value={lang}
|
||||
onChange={(v) => setLang(v)}
|
||||
aria-label={t('common.language')}
|
||||
options={[
|
||||
{
|
||||
value: 'zh',
|
||||
label: (
|
||||
<span title="中文">
|
||||
<span className="lang-full">中文</span>
|
||||
<span className="lang-short">中</span>
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ value: 'en', label: 'EN' },
|
||||
]}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,323 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
Empty,
|
||||
Image,
|
||||
List,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Tabs,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Typography,
|
||||
Upload,
|
||||
} from 'antd'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { api, type Device, type MediaItem, type MediaPending } from '../api'
|
||||
import { CardIcon, MusicIcon, PlayIcon, StopIcon, TrashIcon, UploadIcon } from '../components/icons'
|
||||
|
||||
const { Text } = Typography
|
||||
|
||||
function fmtSize(n: number) {
|
||||
if (n >= 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
|
||||
if (n >= 1024) return `${(n / 1024).toFixed(0)} KB`
|
||||
return `${n} B`
|
||||
}
|
||||
|
||||
// 每页条数:列表只是个管理页,一屏能看完就别滚(8 条要滚两屏)
|
||||
const PAGE_SIZE = 5
|
||||
|
||||
// TF 卡文件管理:拖拽上传(MP3/图片)→ 服务端入库。同步不在网页上点按钮——
|
||||
// 用户在设备上进「音乐」或「相册」时,设备自己检查并弹窗确认后同步;
|
||||
// 这里只负责管理文件(上传/删除)和展示每台设备的同步状态。
|
||||
// 音乐与图片分两个 Tab:用途不同(唱片机 vs 相册),目标目录也不同(/music、/pic)。
|
||||
export default function MediaCard({ devices }: { devices: Device[] }) {
|
||||
const { t } = useTranslation()
|
||||
const { message } = App.useApp()
|
||||
const [items, setItems] = useState<MediaItem[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [uploading, setUploading] = useState(0)
|
||||
|
||||
const [deviceId, setDeviceId] = useState<string>(devices[0]?.id ?? '')
|
||||
const [pending, setPending] = useState<MediaPending | null>(null)
|
||||
const [pendingErr, setPendingErr] = useState(false)
|
||||
|
||||
// 试听:一次只放一首,播放/停止就是同一个按钮
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const [playingId, setPlayingId] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (devices.length === 0) {
|
||||
setDeviceId('')
|
||||
setPending(null)
|
||||
return
|
||||
}
|
||||
if (!devices.some((d) => d.id === deviceId)) setDeviceId(devices[0].id)
|
||||
}, [devices, deviceId])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
setItems(await api.media.list())
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [message])
|
||||
|
||||
// 查一次设备同步状态(只展示,不触发任何动作)
|
||||
const refreshPending = useCallback(async () => {
|
||||
if (!deviceId) {
|
||||
setPending(null)
|
||||
setPendingErr(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
setPending(await api.media.pending(deviceId))
|
||||
setPendingErr(false)
|
||||
} catch {
|
||||
setPending(null)
|
||||
setPendingErr(true)
|
||||
}
|
||||
}, [deviceId])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
refreshPending()
|
||||
}, [refreshPending])
|
||||
|
||||
// 设备在用户进模块时才同步;这里 20 秒看一眼状态,同步完成后徽标/文案自动更新
|
||||
useEffect(() => {
|
||||
if (!deviceId) return
|
||||
const timer = window.setInterval(refreshPending, 20000)
|
||||
return () => window.clearInterval(timer)
|
||||
}, [deviceId, refreshPending])
|
||||
|
||||
// 离开页面/卡片销毁时把试听停掉
|
||||
useEffect(() => () => audioRef.current?.pause(), [])
|
||||
|
||||
async function upload(file: File) {
|
||||
setUploading((n) => n + 1)
|
||||
try {
|
||||
await api.media.upload(file)
|
||||
message.success(t('home.media.uploaded', { name: file.name }))
|
||||
} catch (e) {
|
||||
message.error(`${file.name}:${(e as Error).message}`)
|
||||
} finally {
|
||||
setUploading((n) => n - 1)
|
||||
load()
|
||||
refreshPending()
|
||||
}
|
||||
return false // 阻止 antd 自动上传,走我们自己的进度聚合
|
||||
}
|
||||
|
||||
async function remove(item: MediaItem) {
|
||||
try {
|
||||
if (playingId === item.id) togglePlay(item) // 删掉正在试听的文件先停声
|
||||
await api.media.remove(item.id)
|
||||
message.success(t('home.media.removed'))
|
||||
load()
|
||||
refreshPending()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
// 有待下载,或清单指纹变了(删除/改名),都算「需要同步」(仅用于状态文案)
|
||||
const pendingCount = pending?.pending ?? 0
|
||||
const revChanged = !!pending && pending.rev !== pending.synced_rev
|
||||
|
||||
function renderSyncBar() {
|
||||
if (devices.length === 0) {
|
||||
return <Text type="secondary" style={{ fontSize: 12 }}>{t('home.media.noDevice')}</Text>
|
||||
}
|
||||
return (
|
||||
<Space size={10} wrap>
|
||||
{devices.length > 1 && (
|
||||
<Select
|
||||
size="small"
|
||||
value={deviceId}
|
||||
onChange={setDeviceId}
|
||||
style={{ minWidth: 150 }}
|
||||
options={devices.map((d) => ({ value: d.id, label: d.chip_id.slice(-6) }))}
|
||||
/>
|
||||
)}
|
||||
{pendingCount > 0 ? (
|
||||
<Text style={{ fontSize: 12 }}>{t('home.media.pendingCount', { n: pendingCount })}</Text>
|
||||
) : revChanged ? (
|
||||
<Text style={{ fontSize: 12 }}>{t('home.media.pendingChange')}</Text>
|
||||
) : pending ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{t('home.media.upToDate')}</Text>
|
||||
) : pendingErr ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{t('home.media.checkFailed')}</Text>
|
||||
) : (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{t('home.media.checking')}</Text>
|
||||
)}
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{t('home.media.deviceSyncHint')}</Text>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
|
||||
function togglePlay(m: MediaItem) {
|
||||
if (playingId === m.id) {
|
||||
audioRef.current?.pause()
|
||||
audioRef.current = null
|
||||
setPlayingId(null)
|
||||
return
|
||||
}
|
||||
audioRef.current?.pause()
|
||||
const a = new Audio(api.media.fileUrl(m.id))
|
||||
audioRef.current = a
|
||||
setPlayingId(m.id)
|
||||
a.onended = () => {
|
||||
if (audioRef.current === a) {
|
||||
audioRef.current = null
|
||||
setPlayingId(null)
|
||||
}
|
||||
}
|
||||
a.play().catch(() => {
|
||||
if (audioRef.current === a) {
|
||||
audioRef.current = null
|
||||
setPlayingId(null)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function renderList(list: MediaItem[], kind: 'music' | 'image') {
|
||||
if (list.length === 0) {
|
||||
return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('home.media.sectionEmpty')} style={{ margin: '18px 0' }} />
|
||||
}
|
||||
return (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={list}
|
||||
pagination={{ pageSize: PAGE_SIZE, size: 'small', showSizeChanger: false }}
|
||||
renderItem={(m) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
kind === 'music' && (
|
||||
<Tooltip key="play" title={playingId === m.id ? t('home.media.stop') : t('home.media.play')}>
|
||||
<Button
|
||||
size="small"
|
||||
shape="circle"
|
||||
type={playingId === m.id ? 'primary' : 'default'}
|
||||
icon={playingId === m.id ? <StopIcon size={12} /> : <PlayIcon size={12} />}
|
||||
onClick={() => togglePlay(m)}
|
||||
/>
|
||||
</Tooltip>
|
||||
),
|
||||
<Popconfirm
|
||||
key="del"
|
||||
title={t('home.media.delConfirm')}
|
||||
description={t('home.media.delTip', { name: m.name })}
|
||||
okText={t('common.delete')}
|
||||
cancelText={t('common.cancel')}
|
||||
onConfirm={() => remove(m)}
|
||||
>
|
||||
<Tooltip title={t('common.delete')}>
|
||||
<Button size="small" shape="circle" danger icon={<TrashIcon size={12} />} />
|
||||
</Tooltip>
|
||||
</Popconfirm>,
|
||||
].filter(Boolean)}
|
||||
>
|
||||
<List.Item.Meta
|
||||
avatar={
|
||||
kind === 'image' ? (
|
||||
<Image
|
||||
src={api.media.fileUrl(m.id)}
|
||||
width={40}
|
||||
height={40}
|
||||
style={{ objectFit: 'cover', borderRadius: 6 }}
|
||||
preview={{ mask: false }}
|
||||
/>
|
||||
) : m.has_cover ? (
|
||||
<Image
|
||||
src={api.media.coverUrl(m.id)}
|
||||
width={40}
|
||||
height={40}
|
||||
style={{ objectFit: 'cover', borderRadius: 6 }}
|
||||
preview={{ mask: false }}
|
||||
/>
|
||||
) : (
|
||||
<span className="media-icon">
|
||||
<MusicIcon size={20} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
title={
|
||||
<Space size={6} wrap>
|
||||
<span style={{ fontSize: 13 }}>{m.name}</span>
|
||||
<Tag color={m.synced_devices > 0 ? 'green' : 'default'} style={{ marginRight: 0 }}>
|
||||
{m.synced_devices > 0 ? t('home.media.synced') : t('home.media.pending')}
|
||||
</Tag>
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{fmtSize(m.size)}
|
||||
{kind === 'image' && m.width > 0 && ` · ${m.width}×${m.height}`}
|
||||
</Text>
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const musicList = items.filter((x) => x.kind === 'music')
|
||||
const imageList = items.filter((x) => x.kind === 'image')
|
||||
|
||||
return (
|
||||
<Card
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<CardIcon size={15} />
|
||||
</span>
|
||||
{t('home.media.title')}
|
||||
</span>
|
||||
}
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
<Spin spinning={loading}>
|
||||
<Upload.Dragger
|
||||
multiple
|
||||
accept=".mp3,.jpg,.jpeg,.png,.webp,.bmp,.gif"
|
||||
showUploadList={false}
|
||||
beforeUpload={(file) => upload(file)}
|
||||
className="media-dragger"
|
||||
disabled={uploading > 0}
|
||||
>
|
||||
<span className="media-drop-row">
|
||||
<UploadIcon size={16} />
|
||||
{uploading > 0 ? t('home.media.uploading', { n: uploading }) : t('home.media.dropHere')}
|
||||
</span>
|
||||
</Upload.Dragger>
|
||||
|
||||
{items.length > 0 && <div className="media-sync-bar">{renderSyncBar()}</div>}
|
||||
|
||||
{items.length === 0 && !loading ? (
|
||||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('home.media.empty')} style={{ marginTop: 16 }} />
|
||||
) : (
|
||||
<Tabs
|
||||
size="small"
|
||||
items={[
|
||||
{ key: 'music', label: `${t('home.media.music')} (${musicList.length})`, children: renderList(musicList, 'music') },
|
||||
{ key: 'image', label: `${t('home.media.image')} (${imageList.length})`, children: renderList(imageList, 'image') },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</Spin>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
import { Button, Tooltip } from 'antd'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useTheme } from '../theme'
|
||||
import { MoonIcon, SunIcon } from './icons'
|
||||
|
||||
/** 亮/暗切换:图标显示"点下去会变成什么",比显示当前状态更少歧义 */
|
||||
export default function ThemeSwitch() {
|
||||
const { t } = useTranslation()
|
||||
const { isDark, toggle } = useTheme()
|
||||
const label = isDark ? t('common.toLight') : t('common.toDark')
|
||||
return (
|
||||
<Tooltip title={label} placement="bottom">
|
||||
<Button
|
||||
className="icon-btn"
|
||||
shape="circle"
|
||||
type="text"
|
||||
aria-label={label}
|
||||
onClick={toggle}
|
||||
icon={isDark ? <SunIcon size={17} /> : <MoonIcon size={17} />}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
import { Avatar, Button, Dropdown, Space, Typography } from 'antd'
|
||||
import type { MenuProps } from 'antd'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import LangSwitch from './LangSwitch'
|
||||
import ThemeSwitch from './ThemeSwitch'
|
||||
import { ChevronDownIcon, LogoutIcon, ShieldIcon, UserIcon } from './icons'
|
||||
|
||||
const { Title, Text } = Typography
|
||||
|
||||
export type TopBarUser = {
|
||||
nickname?: string | null
|
||||
email?: string | null
|
||||
phone?: string | null
|
||||
role?: string
|
||||
} | null
|
||||
|
||||
type Props = {
|
||||
title: string
|
||||
badge?: React.ReactNode
|
||||
user?: TopBarUser
|
||||
/** 管理后台入口,仅管理员可见 */
|
||||
onAdmin?: () => void
|
||||
/** 回到用户中心 */
|
||||
onHome?: () => void
|
||||
onLogout?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一顶栏:左侧品牌,右侧只留三个控件(语言 / 主题 / 账号菜单)。
|
||||
* 之前 Home 与 Admin 各写一套,把"管理后台 / 退出"平铺成按钮,窄屏必挤成两行;
|
||||
* 收进账号下拉后,无论几个入口都只占一个位置。
|
||||
*/
|
||||
export default function TopBar({ title, badge, user, onAdmin, onHome, onLogout }: Props) {
|
||||
const { t } = useTranslation()
|
||||
const name = user?.nickname || user?.email || ''
|
||||
const account = user?.email || user?.phone || name
|
||||
const initial = (name.trim()[0] || '?').toUpperCase()
|
||||
|
||||
const items: MenuProps['items'] = [
|
||||
{
|
||||
key: 'who',
|
||||
disabled: true,
|
||||
label: (
|
||||
<div className="account-meta">
|
||||
<div className="account-meta-name">{name || t('common.guest')}</div>
|
||||
{account && account !== name && <div className="account-meta-sub">{account}</div>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ type: 'divider' },
|
||||
...(onAdmin && user?.role === 'admin'
|
||||
? [{ key: 'admin', icon: <ShieldIcon size={15} />, label: t('common.adminCenter') }]
|
||||
: []),
|
||||
...(onHome ? [{ key: 'home', icon: <UserIcon size={15} />, label: t('common.myDevices') }] : []),
|
||||
...(onLogout
|
||||
? [
|
||||
{ type: 'divider' as const },
|
||||
{ key: 'logout', danger: true, icon: <LogoutIcon size={15} />, label: t('common.logout') },
|
||||
]
|
||||
: []),
|
||||
]
|
||||
|
||||
const onClick: MenuProps['onClick'] = ({ key }) => {
|
||||
if (key === 'admin') onAdmin?.()
|
||||
else if (key === 'home') onHome?.()
|
||||
else if (key === 'logout') onLogout?.()
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="topbar">
|
||||
<Space size={10} align="center" className="topbar-brand">
|
||||
<span className="brand-dot" />
|
||||
<Title level={5} className="topbar-title">
|
||||
{title}
|
||||
</Title>
|
||||
{badge}
|
||||
</Space>
|
||||
|
||||
<Space size={8} align="center" className="topbar-actions">
|
||||
<LangSwitch />
|
||||
<ThemeSwitch />
|
||||
<Dropdown menu={{ items, onClick }} trigger={['click']} placement="bottomRight" arrow>
|
||||
<Button type="text" className="account-btn">
|
||||
<Avatar size={26} className="account-avatar">
|
||||
{initial}
|
||||
</Avatar>
|
||||
<Text className="account-name hide-sm">{name}</Text>
|
||||
<ChevronDownIcon size={13} className="account-caret" />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
</Space>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,216 @@
|
|||
import type { SVGProps } from 'react'
|
||||
|
||||
/**
|
||||
* 内联 SVG 图标:项目没装 @ant-design/icons,为几十个图标引一整个图标库不划算。
|
||||
* 统一 24 格、stroke=currentColor,尺寸与描边由 props 覆盖。
|
||||
*/
|
||||
type IconProps = SVGProps<SVGSVGElement> & { size?: number }
|
||||
|
||||
function Icon({ size = 16, children, ...rest }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.8}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export const SunIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2v2M12 20v2M4.93 4.93l1.42 1.42M17.65 17.65l1.42 1.42M2 12h2M20 12h2M4.93 19.07l1.42-1.42M17.65 6.35l1.42-1.42" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const MoonIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const GlobeIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M3 12h18M12 3c2.5 2.6 3.9 5.7 3.9 9s-1.4 6.4-3.9 9c-2.5-2.6-3.9-5.7-3.9-9S9.5 5.6 12 3z" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const SaveIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
|
||||
<path d="M17 21v-8H7v8M7 3v5h8" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const LinkIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
|
||||
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const ShieldIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const LogoutIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
|
||||
<path d="M16 17l5-5-5-5M21 12H9" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const UserIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="8" r="4" />
|
||||
<path d="M4 21a8 8 0 0 1 16 0" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const SparkIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z" />
|
||||
<path d="M18.5 15.5l.8 2 2 .8-2 .8-.8 2-.8-2-2-.8 2-.8.8-2z" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const RefreshIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M21 12a9 9 0 1 1-2.64-6.36M21 3v6h-6" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const PlusIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 5v14M5 12h14" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const ChevronDownIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M6 9.5l6 6 6-6" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const DeviceIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<circle cx="12" cy="12" r="3.2" />
|
||||
<path d="M12 3v3.8M12 17.2V21" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const CloudIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M17.5 19a4.5 4.5 0 0 0 .5-8.97A6 6 0 0 0 6.2 9.5 4.25 4.25 0 0 0 6.5 19h11z" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const ServerIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<rect x="3" y="4" width="18" height="7" rx="2" />
|
||||
<rect x="3" y="13" width="18" height="7" rx="2" />
|
||||
<path d="M7 7.5h.01M7 16.5h.01" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const PinIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 21s7-5.2 7-11a7 7 0 1 0-14 0c0 5.8 7 11 7 11z" />
|
||||
<circle cx="12" cy="10" r="2.6" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
export const ClockIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 7v5.2l3.2 1.9" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 固件:芯片外形 + 引脚 */
|
||||
export const ChipIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<rect x="6" y="6" width="12" height="12" rx="2.5" />
|
||||
<rect x="9.5" y="9.5" width="5" height="5" rx="1" />
|
||||
<path d="M9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 上传:托盘 + 向上箭头 */
|
||||
export const UploadIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 16V4M8 8l4-4 4 4" />
|
||||
<path d="M4 16v2.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V16" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 下载:托盘 + 向下箭头 */
|
||||
export const DownloadIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M12 4v12M8 12l4 4 4-4" />
|
||||
<path d="M4 16v2.5A1.5 1.5 0 0 0 5.5 20h13a1.5 1.5 0 0 0 1.5-1.5V16" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 更多操作:三个点 */
|
||||
export const MoreIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<circle cx="12" cy="5" r="1.2" fill="currentColor" stroke="none" />
|
||||
<circle cx="12" cy="12" r="1.2" fill="currentColor" stroke="none" />
|
||||
<circle cx="12" cy="19" r="1.2" fill="currentColor" stroke="none" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 播放:实心三角 */
|
||||
export const PlayIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M8 5.5v13l11-6.5z" fill="currentColor" stroke="none" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 停止:实心方块 */
|
||||
export const StopIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<rect x="7" y="7" width="10" height="10" rx="1.5" fill="currentColor" stroke="none" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** TF 卡:SD 卡外形 + 触点 */
|
||||
export const CardIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M6 3h9l4 4v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z" />
|
||||
<path d="M8.5 7v2.5M11.5 6v3.5M14.5 6v3.5" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 音乐:音符 */
|
||||
export const MusicIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M9 18V6l10-2v11.5" />
|
||||
<circle cx="6.5" cy="18" r="2.5" />
|
||||
<circle cx="16.5" cy="15.5" r="2.5" />
|
||||
</Icon>
|
||||
)
|
||||
|
||||
/** 删除:垃圾桶 */
|
||||
export const TrashIcon = (p: IconProps) => (
|
||||
<Icon {...p}>
|
||||
<path d="M4 7h16M9 7V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2" />
|
||||
<path d="M6 7l1 13a1 1 0 0 0 1 .9h8a1 1 0 0 0 1-.9l1-13" />
|
||||
<path d="M10 11v6M14 11v6" />
|
||||
</Icon>
|
||||
)
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import i18n from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
import zh from './locales/zh'
|
||||
import en from './locales/en'
|
||||
|
||||
export type Lang = 'zh' | 'en'
|
||||
|
||||
const LANG_KEY = 'nx.lang'
|
||||
|
||||
export function currentLang(): Lang {
|
||||
const saved = localStorage.getItem(LANG_KEY)
|
||||
if (saved === 'zh' || saved === 'en') return saved
|
||||
return navigator.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
||||
}
|
||||
|
||||
export function setLang(lang: Lang) {
|
||||
localStorage.setItem(LANG_KEY, lang)
|
||||
return i18n.changeLanguage(lang)
|
||||
}
|
||||
|
||||
// 语言变化时同步 <html lang> 与标签页标题(浏览器翻译、无障碍朗读都依赖它)
|
||||
function syncDocument(lang: Lang) {
|
||||
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en'
|
||||
document.title = lang === 'zh' ? 'nex_buddy · 我的设备' : 'nex_buddy · My Devices'
|
||||
}
|
||||
|
||||
i18n.on('languageChanged', (l) => {
|
||||
syncDocument(l.startsWith('en') ? 'en' : 'zh')
|
||||
})
|
||||
|
||||
i18n.use(initReactI18next).init({
|
||||
resources: {
|
||||
zh: { translation: zh },
|
||||
en: { translation: en },
|
||||
},
|
||||
lng: currentLang(),
|
||||
fallbackLng: 'zh',
|
||||
interpolation: { escapeValue: false },
|
||||
})
|
||||
|
||||
syncDocument(currentLang())
|
||||
|
||||
export default i18n
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
export default {
|
||||
// QR sign-in from the device screen (/qr?t=...)
|
||||
qr: {
|
||||
subtitle: 'QR sign-in · no password needed',
|
||||
verifying: 'Signing you in…',
|
||||
ok: 'Signed in',
|
||||
redirect: 'Opening your profile',
|
||||
failed: 'This QR link is not usable',
|
||||
failedHint: 'It may have expired or already been used on another phone. Open the QR code on the device again.',
|
||||
toLogin: 'Sign in with password',
|
||||
missing: 'The QR link is missing its sign-in token',
|
||||
},
|
||||
common: {
|
||||
save: 'Save',
|
||||
ok: 'OK',
|
||||
cancel: 'Cancel',
|
||||
edit: 'Edit',
|
||||
delete: 'Delete',
|
||||
create: 'Create',
|
||||
refresh: 'Refresh',
|
||||
back: 'Home',
|
||||
logout: 'Sign out',
|
||||
adminCenter: 'Admin',
|
||||
admin: 'Admin',
|
||||
user: 'User',
|
||||
loading: 'Loading',
|
||||
total: '{{n}} items',
|
||||
required: 'Required',
|
||||
enabled: 'Enabled',
|
||||
saved: 'Saved',
|
||||
updated: 'Updated',
|
||||
deleted: 'Deleted',
|
||||
language: 'Language',
|
||||
toLight: 'Switch to light',
|
||||
toDark: 'Switch to dark',
|
||||
myDevices: 'My devices',
|
||||
guest: 'Not signed in',
|
||||
},
|
||||
login: {
|
||||
title: 'Sign in to nex_buddy',
|
||||
subtitle: 'Smart knob device platform',
|
||||
account: 'Email / Phone',
|
||||
accountPlaceholder: 'you@example.com',
|
||||
password: 'Password',
|
||||
submit: 'Sign in',
|
||||
toRegister: 'No account? Register',
|
||||
toLogin: 'Have an account? Sign in',
|
||||
registerTitle: 'Create account',
|
||||
nickname: 'Nickname',
|
||||
nicknamePlaceholder: 'Shown on the device',
|
||||
register: 'Register',
|
||||
registerSubmit: 'Register & sign in',
|
||||
welcomeBack: 'Welcome back',
|
||||
registered: 'Account created',
|
||||
accountRequired: 'Enter an email or phone number',
|
||||
passwordRequired: 'Enter a password',
|
||||
passwordMin: 'At least 6 characters',
|
||||
nicknameOptional: 'Nickname (optional)',
|
||||
langLabel: 'Language',
|
||||
badPassword: 'Incorrect account or password',
|
||||
accountDisabled: 'Account disabled. Contact the administrator',
|
||||
accountFormat: 'Account must be an email or phone number',
|
||||
accountTaken: 'This email/phone is already registered',
|
||||
qrExpired: 'QR code expired. Reopen it on the device',
|
||||
},
|
||||
bind: {
|
||||
title: 'Bind device',
|
||||
tip: 'Find the 6-digit pairing code on the device screen and enter it to bind the device to your account.',
|
||||
device: 'Device',
|
||||
confirm: 'Bind',
|
||||
later: 'Later',
|
||||
successTip: 'You can find it under "My Devices".',
|
||||
toDevices: 'Go to My Devices',
|
||||
expiry: 'Pairing codes are valid for 10 minutes and single-use.',
|
||||
bound: 'Bound',
|
||||
},
|
||||
home: {
|
||||
devices: 'My Devices',
|
||||
deviceCount: '{{n}} device(s)',
|
||||
pairPlaceholder: '6-digit pairing code on the device',
|
||||
pairCode: 'Pairing code is 6 digits',
|
||||
bind: 'Bind',
|
||||
bindOk: 'Bound',
|
||||
unbind: 'Unbind',
|
||||
unbindConfirm: 'Unbind this device?',
|
||||
unbindTip: 'The device loses access immediately and returns to the unbound state.',
|
||||
unbindOk: 'Unbound; the device is back to unbound state',
|
||||
noDevices: 'No device bound yet',
|
||||
noDevicesTip: 'Open the pairing screen on your knob, then enter the 6-digit code below to bind it.',
|
||||
account: 'Account',
|
||||
birthPlace: 'Birthplace',
|
||||
residencePlace: 'Residence',
|
||||
registeredAt: 'Joined',
|
||||
media: {
|
||||
title: 'TF Card Files',
|
||||
uploaded: 'Uploaded {{name}} — the device will offer to sync in Music/Gallery',
|
||||
removed: 'Deleted — it will also be wiped from the TF card on next sync',
|
||||
empty: 'No files yet — drop some MP3s or photos here',
|
||||
dropHere: 'Drop MP3 / images here, or click to browse',
|
||||
uploading: 'Uploading {{n}} file(s)…',
|
||||
music: 'Music',
|
||||
image: 'Photos',
|
||||
sectionEmpty: 'None',
|
||||
synced: 'Synced',
|
||||
pending: 'Pending',
|
||||
delConfirm: 'Delete this file?',
|
||||
play: 'Play',
|
||||
stop: 'Stop',
|
||||
delTip: 'Removes "{{name}}" from both the server and the device TF card.',
|
||||
noDevice: 'Bind a device to sync to its TF card',
|
||||
pendingCount: '{{n}} file(s) waiting to sync',
|
||||
pendingChange: 'Changes waiting to sync',
|
||||
upToDate: 'TF card is up to date',
|
||||
checking: 'Checking device state…',
|
||||
checkFailed: 'Cannot read device state right now',
|
||||
deviceSyncHint: 'Sync runs on the device: entering Music or Gallery will prompt',
|
||||
},
|
||||
notFilled: 'Not set',
|
||||
basicCard: 'Profile',
|
||||
nickname: 'Nickname',
|
||||
nicknamePlaceholder: 'Shown on the device',
|
||||
birthCard: 'Birth Info & Signs',
|
||||
birthday: 'Birthday',
|
||||
birthTime: 'Birth time',
|
||||
birthCity: 'Birthplace',
|
||||
birthCityTip: 'The birthplace fixes the time zone; the moon sign is time-sensitive, be precise',
|
||||
sunSign: 'Sun Sign',
|
||||
moonSign: 'Moon Sign',
|
||||
signEmpty: 'Not set',
|
||||
signHint: 'Fill birthday & birth time',
|
||||
savedWithSign: 'Saved: Sun {{sun}} · Moon {{moon}}',
|
||||
fortuneTitle: 'This Month',
|
||||
fortuneNone: 'Your monthly horoscope appears here once your birthday is set',
|
||||
residenceCity: 'City of residence',
|
||||
residenceCityTip: 'Used for device weather and the current-month horoscope',
|
||||
regionPlaceholder: 'Province / City / District',
|
||||
timezone: 'Time zone',
|
||||
timezoneTip: 'IANA name such as Asia/Shanghai; affects daily semantics only, not the natal chart',
|
||||
lang: 'Language',
|
||||
},
|
||||
admin: {
|
||||
title: 'Admin Console',
|
||||
tabs: {
|
||||
users: 'Users & Devices',
|
||||
regions: 'City Codes',
|
||||
zodiacs: 'Zodiac Codes',
|
||||
fortunes: 'Monthly Horoscope',
|
||||
firmware: 'Firmware',
|
||||
settings: 'Platform Settings',
|
||||
},
|
||||
forbidden: 'Admin required',
|
||||
forbiddenTip: 'This account is not an admin.',
|
||||
users: {
|
||||
email: 'Account',
|
||||
nickname: 'Nickname',
|
||||
role: 'Role',
|
||||
status: 'Status',
|
||||
statusActive: 'Active',
|
||||
statusDisabled: 'Disabled',
|
||||
sign: 'Signs',
|
||||
devices: 'Devices',
|
||||
createdAt: 'Joined',
|
||||
actions: 'Actions',
|
||||
disable: 'Disable',
|
||||
enable: 'Enable',
|
||||
disableConfirm: 'The account will no longer be able to sign in. Continue?',
|
||||
disableSelf: 'You cannot disable yourself',
|
||||
noDevices: 'None',
|
||||
model: 'Model',
|
||||
lastActive: 'Last active',
|
||||
unbindDevice: 'Unbind',
|
||||
unbindConfirm: 'The device will need pairing again. Continue?',
|
||||
revokeDevice: 'Revoke access',
|
||||
revokeConfirm: 'The device will lose access and must pair again. Continue?',
|
||||
unbindOk: 'Unbound',
|
||||
revokeOk: 'Revoked',
|
||||
enabled: 'Enabled',
|
||||
disabled: 'Disabled',
|
||||
search: 'Search account or nickname',
|
||||
},
|
||||
regions: {
|
||||
code: 'Code',
|
||||
name: 'Name',
|
||||
level: 'Level',
|
||||
level1: 'Province',
|
||||
level2: 'City',
|
||||
level3: 'District',
|
||||
parent: 'Parent',
|
||||
timezone: 'Time zone',
|
||||
actions: 'Actions',
|
||||
create: 'New region',
|
||||
createTitle: 'New region',
|
||||
editTitle: 'Edit {{name}}',
|
||||
codeLabel: 'Division code',
|
||||
codeExtra: '6-digit administrative code',
|
||||
codeFixed: 'The code is the primary key and cannot change',
|
||||
nameLabel: 'Name',
|
||||
parentLabel: 'Parent code',
|
||||
parentPlaceholder: 'Empty for province',
|
||||
sortLabel: 'Order',
|
||||
import: 'Import standard set',
|
||||
importConfirm: 'Add missing regions from the built-in table? Existing edits are kept.',
|
||||
importOk: 'Imported',
|
||||
search: 'Search name or code',
|
||||
isKey: 'The code is the primary key and cannot change',
|
||||
},
|
||||
zodiacs: {
|
||||
order: 'Ecliptic #',
|
||||
symbol: 'Symbol',
|
||||
nameCn: 'Name (CN)',
|
||||
nameEn: 'Name (EN)',
|
||||
element: 'Element',
|
||||
dateRange: 'Date range',
|
||||
intro: 'Intro',
|
||||
},
|
||||
settings: {
|
||||
title: 'Weather service',
|
||||
status: 'Weather service',
|
||||
ready: 'Configured',
|
||||
pending: 'Not configured',
|
||||
key: 'API Key / JWT',
|
||||
keyTip: 'The API Key under Project → Credentials; a JWT also works',
|
||||
host: 'API Host',
|
||||
hostTip: 'Your account-specific host, from Console → Settings',
|
||||
},
|
||||
fw: {
|
||||
statDevices: 'Devices',
|
||||
statLatest: 'Latest release',
|
||||
statPending: 'Assigned, waiting',
|
||||
statVersions: 'Versions in use',
|
||||
uploadTitle: 'Upload firmware',
|
||||
dropText: 'Drop a .bin here, or click to choose',
|
||||
dropHint: 'Max {{size}}',
|
||||
needFile: 'Choose a .bin file first',
|
||||
version: 'Version',
|
||||
versionRule: 'Like 0.1.2 or 0.2.0-rc1',
|
||||
channel: 'Channel',
|
||||
minVersion: 'Minimum version',
|
||||
minVersionPlaceholder: 'Leave empty = no limit',
|
||||
minVersionHint: 'Devices below this version upgrade to it first, then to this build',
|
||||
notes: 'Release notes (Chinese)',
|
||||
notesEn: 'Release notes (English)',
|
||||
notesPlaceholder: 'Shown in the device update prompt',
|
||||
uploaded: 'Uploaded',
|
||||
listTitle: 'Firmware builds',
|
||||
devicesTitle: 'Device upgrade status',
|
||||
devices: 'Devices',
|
||||
status: 'Status',
|
||||
published: 'Published',
|
||||
draft: 'Draft',
|
||||
publish: 'Publish',
|
||||
unpublish: 'Unpublish',
|
||||
createdAt: 'Uploaded',
|
||||
updatedAt: 'Last change',
|
||||
actions: 'Actions',
|
||||
size: 'Size',
|
||||
rollout: 'Upgrade all',
|
||||
rolloutConfirm: 'Set every older device’s target to {{version}}?',
|
||||
rolloutTip: 'Takes effect on each device’s next update check — nothing is pushed to it',
|
||||
rolledOut: 'Assigned',
|
||||
pushed: 'Assigned',
|
||||
canceled: 'Revoked',
|
||||
cancel: 'Revoke',
|
||||
deleteConfirm: 'Delete this build? The file is removed too.',
|
||||
deleted: 'Deleted',
|
||||
updated: 'Updated',
|
||||
empty: 'No firmware yet',
|
||||
noDevice: 'No devices',
|
||||
searchDevice: 'Chip id / account / version',
|
||||
device: 'Device',
|
||||
unbound: 'Unbound',
|
||||
current: 'Current',
|
||||
target: 'Target',
|
||||
stateLabel: 'Upgrade',
|
||||
pickVersion: 'Pick version',
|
||||
editTitle: 'Edit firmware info',
|
||||
download: 'Download firmware',
|
||||
more: 'More actions',
|
||||
state: {
|
||||
idle: 'Not assigned',
|
||||
pending: 'Waiting for device',
|
||||
downloading: 'Downloading',
|
||||
success: 'Upgraded',
|
||||
failed: 'Failed',
|
||||
canceled: 'Revoked',
|
||||
},
|
||||
},
|
||||
fortunes: {
|
||||
zodiac: 'Sign',
|
||||
scope: 'Scope',
|
||||
scopeMonth: 'Monthly template',
|
||||
scopeYm: 'Specific month',
|
||||
period: 'Period',
|
||||
title: 'Title (CN)',
|
||||
titleEn: 'Title (EN)',
|
||||
content: 'Body (CN)',
|
||||
contentEn: 'Body (EN)',
|
||||
create: 'New entry',
|
||||
periodMonth: 'Two digits, e.g. 11',
|
||||
periodYm: 'e.g. 2026-11',
|
||||
zodiacAll: 'All signs',
|
||||
yearFilter: 'Filter by year',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
export default {
|
||||
// 设备屏二维码扫码登录(/qr?t=...)
|
||||
qr: {
|
||||
subtitle: '扫码登录 · 无需输入密码',
|
||||
verifying: '正在登录…',
|
||||
ok: '登录成功',
|
||||
redirect: '正在进入你的个人页面',
|
||||
failed: '二维码不可用',
|
||||
failedHint: '链接可能已过期,或已经在另一台手机上用过。请在设备上重新打开二维码。',
|
||||
toLogin: '用密码登录',
|
||||
missing: '二维码里缺少登录凭证',
|
||||
},
|
||||
common: {
|
||||
save: '保存',
|
||||
ok: '确定',
|
||||
cancel: '取消',
|
||||
edit: '编辑',
|
||||
delete: '删除',
|
||||
create: '新增',
|
||||
refresh: '刷新',
|
||||
back: '返回首页',
|
||||
logout: '退出',
|
||||
adminCenter: '管理后台',
|
||||
admin: '管理员',
|
||||
user: '普通用户',
|
||||
loading: '加载中',
|
||||
total: '共 {{n}} 条',
|
||||
required: '必填',
|
||||
enabled: '启用',
|
||||
saved: '已保存',
|
||||
updated: '已更新',
|
||||
deleted: '已删除',
|
||||
language: '语言',
|
||||
toLight: '切换到亮色',
|
||||
toDark: '切换到暗色',
|
||||
myDevices: '我的设备',
|
||||
guest: '未登录',
|
||||
},
|
||||
login: {
|
||||
title: '登录 nex_buddy',
|
||||
subtitle: '旋钮设备服务平台',
|
||||
account: '邮箱 / 手机号',
|
||||
accountPlaceholder: 'you@example.com',
|
||||
password: '密码',
|
||||
submit: '登录',
|
||||
toRegister: '没有账号?注册',
|
||||
toLogin: '已有账号?去登录',
|
||||
registerTitle: '注册新账号',
|
||||
nickname: '昵称',
|
||||
nicknamePlaceholder: '设备上会显示',
|
||||
register: '注册',
|
||||
registerSubmit: '注册并登录',
|
||||
welcomeBack: '欢迎回来',
|
||||
registered: '注册成功',
|
||||
accountRequired: '请输入邮箱或手机号',
|
||||
passwordRequired: '请输入密码',
|
||||
passwordMin: '至少 6 位',
|
||||
nicknameOptional: '昵称(可选)',
|
||||
langLabel: '语言',
|
||||
badPassword: '账号或密码不正确',
|
||||
accountDisabled: '账号已被停用,请联系管理员',
|
||||
accountFormat: '账号需为邮箱或手机号',
|
||||
accountTaken: '该邮箱/手机号已注册',
|
||||
qrExpired: '二维码已失效,请在设备上重新打开',
|
||||
},
|
||||
bind: {
|
||||
title: '绑定设备',
|
||||
tip: '在设备屏幕上找到 6 位配对码,输入后即可把设备绑定到你的账号。',
|
||||
device: '设备',
|
||||
confirm: '确认绑定',
|
||||
later: '稍后再说',
|
||||
successTip: '可以在「我的设备」里查看它。',
|
||||
toDevices: '回到我的设备',
|
||||
expiry: '配对码 10 分钟内有效,用一次即作废。',
|
||||
bound: '已绑定',
|
||||
},
|
||||
home: {
|
||||
devices: '我的设备',
|
||||
deviceCount: '{{n}} 台',
|
||||
pairPlaceholder: '输入设备上的 6 位配对码',
|
||||
pairCode: '配对码是 6 位数字',
|
||||
bind: '绑定',
|
||||
bindOk: '绑定成功',
|
||||
unbind: '解绑',
|
||||
unbindConfirm: '解除绑定?',
|
||||
unbindTip: '设备会立即失去访问权限,回到未绑定态。',
|
||||
unbindOk: '已解绑,设备会回到未绑定态',
|
||||
noDevices: '还没有绑定设备',
|
||||
noDevicesTip: '在设备上打开「配对」页,把屏幕上的 6 位配对码填到下面即可绑定。',
|
||||
account: '账号',
|
||||
birthPlace: '出生地',
|
||||
residencePlace: '居住地',
|
||||
registeredAt: '注册',
|
||||
media: {
|
||||
title: 'TF 卡文件',
|
||||
uploaded: '已上传 {{name}},设备进入音乐/相册后会提示同步',
|
||||
removed: '已删除,设备同步时 TF 卡上的文件也会清掉',
|
||||
empty: '还没有文件,把 MP3 或图片拖进来试试',
|
||||
dropHere: '拖拽 MP3 / 图片到这里,或点击选择',
|
||||
uploading: '正在上传 {{n}} 个文件…',
|
||||
music: '音乐',
|
||||
image: '图片',
|
||||
sectionEmpty: '暂无',
|
||||
synced: '已同步',
|
||||
pending: '待同步',
|
||||
delConfirm: '删除这个文件?',
|
||||
play: '播放',
|
||||
stop: '停止',
|
||||
delTip: '会同时从服务端和设备 TF 卡删除「{{name}}」。',
|
||||
noDevice: '绑定设备后可同步到 TF 卡',
|
||||
pendingCount: '有 {{n}} 个文件待同步',
|
||||
pendingChange: '有文件变更待同步',
|
||||
upToDate: 'TF 卡已是最新',
|
||||
checking: '正在检查设备状态…',
|
||||
checkFailed: '暂时读不到设备状态',
|
||||
deviceSyncHint: '同步在设备端进行:进入「音乐」或「相册」时会提示',
|
||||
},
|
||||
notFilled: '未填写',
|
||||
basicCard: '个人资料',
|
||||
nickname: '昵称',
|
||||
nicknamePlaceholder: '设备上会显示',
|
||||
birthCard: '出生信息与星盘',
|
||||
birthday: '出生日期',
|
||||
birthTime: '出生时间',
|
||||
birthCity: '出生城市',
|
||||
birthCityTip: '出生地决定时区;月亮星座对时间敏感,尽量填准',
|
||||
sunSign: '太阳星座',
|
||||
moonSign: '月亮星座',
|
||||
signEmpty: '待填写',
|
||||
signHint: '填生日和出生时间',
|
||||
savedWithSign: '已保存:太阳{{sun}} · 月亮{{moon}}',
|
||||
fortuneTitle: '本月运势',
|
||||
fortuneNone: '填好生日后,这里会显示当月运势',
|
||||
residenceCity: '常住城市',
|
||||
residenceCityTip: '设备首页天气与运势的「当月」都用它',
|
||||
regionPlaceholder: '省 / 市 / 区县',
|
||||
timezone: '时区',
|
||||
timezoneTip: 'IANA 时区名,如 Asia/Shanghai;只影响日常语义,不影响星盘',
|
||||
lang: '语言',
|
||||
},
|
||||
admin: {
|
||||
title: '管理后台',
|
||||
tabs: {
|
||||
users: '用户与设备',
|
||||
regions: '城市码表',
|
||||
zodiacs: '星座码表',
|
||||
fortunes: '月度运势',
|
||||
firmware: '固件管理',
|
||||
settings: '平台设置',
|
||||
},
|
||||
forbidden: '需要管理员权限',
|
||||
forbiddenTip: '当前账号不是管理员,无法进入管理后台。',
|
||||
users: {
|
||||
email: '账号',
|
||||
nickname: '昵称',
|
||||
role: '角色',
|
||||
status: '状态',
|
||||
statusActive: '正常',
|
||||
statusDisabled: '已停用',
|
||||
sign: '星座',
|
||||
devices: '绑定设备',
|
||||
createdAt: '注册时间',
|
||||
actions: '操作',
|
||||
disable: '停用',
|
||||
enable: '恢复',
|
||||
disableConfirm: '停用后该账号将无法登录,确认?',
|
||||
disableSelf: '不能停用自己',
|
||||
noDevices: '未绑定',
|
||||
model: '型号',
|
||||
lastActive: '最近活跃',
|
||||
unbindDevice: '解绑',
|
||||
unbindConfirm: '解绑后设备需重新配对,确认?',
|
||||
revokeDevice: '吊销权限',
|
||||
revokeConfirm: '设备将失去访问权限,需要重新配对,确认?',
|
||||
unbindOk: '已解绑',
|
||||
revokeOk: '已吊销',
|
||||
enabled: '启用',
|
||||
disabled: '停用',
|
||||
search: '搜索账号或昵称',
|
||||
},
|
||||
regions: {
|
||||
code: '代码',
|
||||
name: '名称',
|
||||
level: '级别',
|
||||
level1: '省级',
|
||||
level2: '地级市',
|
||||
level3: '区县',
|
||||
parent: '上级代码',
|
||||
timezone: '时区',
|
||||
actions: '操作',
|
||||
create: '新增地区',
|
||||
createTitle: '新增地区',
|
||||
editTitle: '编辑 {{name}}',
|
||||
codeLabel: '行政区划代码',
|
||||
codeExtra: '6 位行政区划代码',
|
||||
codeFixed: '代码是主键,不可修改',
|
||||
nameLabel: '名称',
|
||||
parentLabel: '上级代码',
|
||||
parentPlaceholder: '省级留空',
|
||||
sortLabel: '排序',
|
||||
import: '补全标准码表',
|
||||
importConfirm: '从内置码表补全缺失记录?不会覆盖已修改的内容。',
|
||||
importOk: '已补全',
|
||||
search: '按名称或代码搜索',
|
||||
isKey: '代码是主键,不可修改',
|
||||
},
|
||||
zodiacs: {
|
||||
order: '黄经序号',
|
||||
symbol: '符号',
|
||||
nameCn: '中文名',
|
||||
nameEn: '英文名',
|
||||
element: '元素',
|
||||
dateRange: '日期区间',
|
||||
intro: '简介',
|
||||
},
|
||||
settings: {
|
||||
title: '天气服务',
|
||||
status: '天气服务',
|
||||
ready: '已配置',
|
||||
pending: '待配置',
|
||||
key: 'API Key / JWT',
|
||||
keyTip: '控制台「项目管理 → 凭据」里的 API Key;也可以直接贴 JWT',
|
||||
host: 'API Host',
|
||||
hostTip: '账号专属域名,控制台「设置」里复制',
|
||||
},
|
||||
fw: {
|
||||
statDevices: '设备总数',
|
||||
statLatest: '最新发布版本',
|
||||
statPending: '已指定待升级',
|
||||
statVersions: '在用的版本数',
|
||||
uploadTitle: '上传固件包',
|
||||
dropText: '把 .bin 拖到这里,或点击选择',
|
||||
dropHint: '最大 {{size}}',
|
||||
needFile: '请先选择要上传的 .bin 文件',
|
||||
version: '版本号',
|
||||
versionRule: '形如 0.1.2 或 0.2.0-rc1',
|
||||
channel: '通道',
|
||||
minVersion: '最低可升级版本',
|
||||
minVersionPlaceholder: '留空不限制',
|
||||
minVersionHint: '低于这一版的设备会先升到这个版本,再升到本包',
|
||||
notes: '更新说明(中文)',
|
||||
notesEn: '更新说明(英文)',
|
||||
notesPlaceholder: '会显示在设备升级提示里',
|
||||
uploaded: '已上传',
|
||||
listTitle: '固件包',
|
||||
devicesTitle: '设备升级状态',
|
||||
devices: '覆盖设备',
|
||||
status: '状态',
|
||||
published: '已发布',
|
||||
draft: '草稿',
|
||||
publish: '发布',
|
||||
unpublish: '下线',
|
||||
createdAt: '上传时间',
|
||||
updatedAt: '最近变更',
|
||||
actions: '操作',
|
||||
size: '大小',
|
||||
rollout: '批量升级',
|
||||
rolloutConfirm: '把所有低版本设备的目标版本设为 {{version}}?',
|
||||
rolloutTip: '设备下次检查更新时才生效,服务端不会主动唤醒它',
|
||||
rolledOut: '已指定',
|
||||
pushed: '已指定',
|
||||
canceled: '已撤销',
|
||||
cancel: '撤销',
|
||||
deleteConfirm: '删除这个固件包?文件会一起删掉',
|
||||
deleted: '已删除',
|
||||
updated: '已更新',
|
||||
empty: '还没有固件包',
|
||||
noDevice: '没有设备',
|
||||
searchDevice: '搜芯片号 / 账号 / 版本',
|
||||
device: '设备',
|
||||
unbound: '未绑定',
|
||||
current: '当前版本',
|
||||
target: '目标版本',
|
||||
stateLabel: '升级状态',
|
||||
pickVersion: '选择版本',
|
||||
editTitle: '编辑固件信息',
|
||||
download: '下载固件',
|
||||
more: '更多操作',
|
||||
state: {
|
||||
idle: '未指定',
|
||||
pending: '等待设备',
|
||||
downloading: '下载中',
|
||||
success: '已升级',
|
||||
failed: '升级失败',
|
||||
canceled: '已撤销',
|
||||
},
|
||||
},
|
||||
fortunes: {
|
||||
zodiac: '星座',
|
||||
scope: '范围',
|
||||
scopeMonth: '通用月度',
|
||||
scopeYm: '指定年月',
|
||||
period: '周期',
|
||||
title: '标题(中文)',
|
||||
titleEn: '标题(英文)',
|
||||
content: '正文(中文)',
|
||||
contentEn: '正文(英文)',
|
||||
create: '新增运势',
|
||||
periodMonth: '两位月份,如 11',
|
||||
periodYm: '如 2026-11',
|
||||
zodiacAll: '全部星座',
|
||||
yearFilter: '按年过滤',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import { StrictMode, useEffect, useState } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { App as AntApp, ConfigProvider } from 'antd'
|
||||
import zhCN from 'antd/locale/zh_CN'
|
||||
import enUS from 'antd/locale/en_US'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/zh-cn'
|
||||
import App from './App'
|
||||
import i18n, { currentLang } from './i18n'
|
||||
import { ThemeProvider, buildTheme, useTheme } from './theme'
|
||||
import './styles.css'
|
||||
|
||||
// antd 内置文案(分页/日期选择等)与 dayjs 跟随界面语言,主题跟随 ThemeProvider
|
||||
function Root() {
|
||||
const [lang, setLang] = useState(currentLang())
|
||||
const { mode } = useTheme()
|
||||
|
||||
// 监听要清理:原来写在渲染体里,每次重渲染都会多挂一个 handler
|
||||
useEffect(() => {
|
||||
const onChange = (l: string) => {
|
||||
const next = l.startsWith('en') ? 'en' : 'zh'
|
||||
setLang(next)
|
||||
dayjs.locale(next === 'zh' ? 'zh-cn' : 'en')
|
||||
}
|
||||
dayjs.locale(lang === 'zh' ? 'zh-cn' : 'en')
|
||||
i18n.on('languageChanged', onChange)
|
||||
return () => {
|
||||
i18n.off('languageChanged', onChange)
|
||||
}
|
||||
// 只在挂载时挂一次监听,lang 初值已由 useState 取好
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ConfigProvider locale={lang === 'zh' ? zhCN : enUS} theme={buildTheme(mode)}>
|
||||
<AntApp>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</AntApp>
|
||||
</ConfigProvider>
|
||||
)
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ThemeProvider>
|
||||
<Root />
|
||||
</ThemeProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,567 @@
|
|||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
Col,
|
||||
Dropdown,
|
||||
Form,
|
||||
Grid,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Statistic,
|
||||
Table,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Upload,
|
||||
} from 'antd'
|
||||
import type { ColumnsType } from 'antd/es/table'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import dayjs from 'dayjs'
|
||||
import { api, type DeviceUpgrade, type Firmware, type UpgradesInfo } from '../api'
|
||||
import { ChipIcon, DownloadIcon, MoreIcon, RefreshIcon, UploadIcon } from '../components/icons'
|
||||
|
||||
const { Dragger } = Upload
|
||||
const { TextArea } = Input
|
||||
|
||||
function fmtSize(n: number): string {
|
||||
if (!n) return '—'
|
||||
if (n < 1024) return `${n} B`
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`
|
||||
return `${(n / 1048576).toFixed(2)} MB`
|
||||
}
|
||||
|
||||
function fmtTime(v?: string | null): string {
|
||||
return v ? dayjs(v).format('MM-DD HH:mm') : '—'
|
||||
}
|
||||
|
||||
/** 升级状态 → 颜色 + 词条。空字符串是「从没推过」,不是错误,别用红色。 */
|
||||
const STATE_STYLE: Record<string, { color: string; key: string }> = {
|
||||
'': { color: 'default', key: 'idle' },
|
||||
pending: { color: 'orange', key: 'pending' },
|
||||
downloading: { color: 'blue', key: 'downloading' },
|
||||
success: { color: 'green', key: 'success' },
|
||||
failed: { color: 'red', key: 'failed' },
|
||||
canceled: { color: 'default', key: 'canceled' },
|
||||
}
|
||||
|
||||
export default function FirmwarePanel() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { message, modal } = App.useApp()
|
||||
const screens = Grid.useBreakpoint()
|
||||
const narrow = !screens.sm
|
||||
const zh = i18n.language !== 'en'
|
||||
|
||||
const [fws, setFws] = useState<Firmware[]>([])
|
||||
const [maxSize, setMaxSize] = useState(0)
|
||||
const [ups, setUps] = useState<UpgradesInfo | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [editing, setEditing] = useState<Firmware | null>(null)
|
||||
const [q, setQ] = useState('')
|
||||
const [form] = Form.useForm()
|
||||
const [editForm] = Form.useForm()
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [f, u] = await Promise.all([api.admin.firmwares(), api.admin.deviceUpgrades(q)])
|
||||
setFws(f.items)
|
||||
setMaxSize(f.max_size)
|
||||
setUps(u)
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [message, q])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
async function submitUpload() {
|
||||
const v = await form.validateFields()
|
||||
if (!file) {
|
||||
message.warning(t('admin.fw.needFile'))
|
||||
return
|
||||
}
|
||||
setUploading(true)
|
||||
try {
|
||||
const res = await api.admin.uploadFirmware(file, {
|
||||
version: v.version,
|
||||
channel: v.channel,
|
||||
notes: v.notes || '',
|
||||
notes_en: v.notes_en || '',
|
||||
min_version: v.min_version || '',
|
||||
publish: v.publish ? 'true' : 'false',
|
||||
})
|
||||
message.success(res.detail || t('admin.fw.uploaded'))
|
||||
form.resetFields()
|
||||
form.setFieldsValue({ channel: 'stable', publish: false })
|
||||
setFile(null)
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function togglePublish(fw: Firmware) {
|
||||
try {
|
||||
await api.admin.updateFirmware(fw.id, { published: !fw.published })
|
||||
message.success(t('admin.fw.updated'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(fw: Firmware) {
|
||||
try {
|
||||
await api.admin.deleteFirmware(fw.id)
|
||||
message.success(t('admin.fw.deleted'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function rollout(fw: Firmware) {
|
||||
try {
|
||||
const res = await api.admin.rolloutFirmware(fw.id)
|
||||
message.success(res.detail || t('admin.fw.rolledOut'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function pushOne(d: DeviceUpgrade, firmwareId: string) {
|
||||
try {
|
||||
const res = await api.admin.pushUpgrade(d.id, firmwareId)
|
||||
message.success(res.detail || t('admin.fw.pushed'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelOne(d: DeviceUpgrade) {
|
||||
try {
|
||||
await api.admin.cancelUpgrade(d.id)
|
||||
message.success(t('admin.fw.canceled'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function openEdit(fw: Firmware) {
|
||||
setEditing(fw)
|
||||
editForm.setFieldsValue({
|
||||
notes: fw.notes,
|
||||
notes_en: fw.notes_en,
|
||||
min_version: fw.min_version,
|
||||
channel: fw.channel,
|
||||
})
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
if (!editing) return
|
||||
const v = await editForm.validateFields()
|
||||
try {
|
||||
await api.admin.updateFirmware(editing.id, v)
|
||||
message.success(t('admin.fw.updated'))
|
||||
setEditing(null)
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
const fwColumns: ColumnsType<Firmware> = [
|
||||
{
|
||||
title: t('admin.fw.version'),
|
||||
dataIndex: 'version',
|
||||
width: 150,
|
||||
render: (v: string, r) => (
|
||||
<Space size={6}>
|
||||
<span className="fw-version">{v}</span>
|
||||
<Tag color={r.channel === 'beta' ? 'purple' : 'blue'}>{r.channel}</Tag>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{ title: t('admin.fw.size'), dataIndex: 'size_bytes', width: 100, align: 'right', responsive: ['md'], render: (n: number) => <span className="table-num muted">{fmtSize(n)}</span> },
|
||||
{
|
||||
title: t('admin.fw.notes'),
|
||||
dataIndex: 'notes',
|
||||
responsive: ['lg'],
|
||||
render: (_: string, r) => (
|
||||
<Tooltip title={r.sha256}>
|
||||
<span className="fw-notes">{zh ? r.notes || '—' : r.notes_en || r.notes || '—'}</span>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('admin.fw.devices'),
|
||||
dataIndex: 'device_count',
|
||||
width: 90,
|
||||
align: 'center',
|
||||
responsive: ['md'],
|
||||
render: (n: number) => (n ? <Tag color="geekblue">{n}</Tag> : <span className="muted">0</span>),
|
||||
},
|
||||
{
|
||||
title: t('admin.fw.status'),
|
||||
dataIndex: 'published',
|
||||
width: 100,
|
||||
responsive: ['sm'],
|
||||
render: (p: boolean) =>
|
||||
p ? <Tag color="green">{t('admin.fw.published')}</Tag> : <Tag>{t('admin.fw.draft')}</Tag>,
|
||||
},
|
||||
{ title: t('admin.fw.createdAt'), dataIndex: 'created_at', width: 120, responsive: ['md'], render: fmtTime },
|
||||
{
|
||||
title: t('admin.fw.actions'),
|
||||
key: 'op',
|
||||
width: 200,
|
||||
align: 'right',
|
||||
render: (_, r) => (
|
||||
<div className="row-actions">
|
||||
<Button size="small" type="text" onClick={() => togglePublish(r)}>
|
||||
{r.published ? t('admin.fw.unpublish') : t('admin.fw.publish')}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={t('admin.fw.rolloutConfirm', { version: r.version })}
|
||||
description={t('admin.fw.rolloutTip')}
|
||||
okText={t('common.ok')}
|
||||
cancelText={t('common.cancel')}
|
||||
onConfirm={() => rollout(r)}
|
||||
>
|
||||
<Button size="small" type="link">
|
||||
{t('admin.fw.rollout')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
menu={{
|
||||
items: [
|
||||
{ key: 'download', label: t('admin.fw.download'), icon: <DownloadIcon size={14} /> },
|
||||
{ key: 'edit', label: t('common.edit') },
|
||||
{ type: 'divider' as const },
|
||||
{ key: 'delete', label: t('common.delete'), danger: true },
|
||||
],
|
||||
onClick: ({ key }) => {
|
||||
if (key === 'download') {
|
||||
api.admin.downloadFirmware(r).catch((e) => message.error(e.message))
|
||||
} else if (key === 'edit') {
|
||||
openEdit(r)
|
||||
} else if (key === 'delete') {
|
||||
modal.confirm({
|
||||
title: t('admin.fw.deleteConfirm'),
|
||||
okText: t('common.ok'),
|
||||
cancelText: t('common.cancel'),
|
||||
okButtonProps: { danger: true },
|
||||
onOk: () => remove(r),
|
||||
})
|
||||
}
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Button size="small" type="text" icon={<MoreIcon size={14} />} aria-label={t('admin.fw.more')} />
|
||||
</Dropdown>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
const devColumns: ColumnsType<DeviceUpgrade> = [
|
||||
{
|
||||
title: t('admin.fw.device'),
|
||||
key: 'dev',
|
||||
width: 160,
|
||||
render: (_, d) => {
|
||||
const st = STATE_STYLE[d.upgrade_state] || STATE_STYLE['']
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<span className="mono fw-chip">{d.chip_id}</span>
|
||||
<span className="muted">{d.user_label || t('admin.fw.unbound')}</span>
|
||||
{/* 窄屏把升级状态藏进这一格,否则五列挤不下、芯片号会被拆成竖排 */}
|
||||
{narrow && <Tag color={st.color}>{t(`admin.fw.state.${st.key}`)}</Tag>}
|
||||
</Space>
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('admin.fw.current'),
|
||||
dataIndex: 'fw_version',
|
||||
width: 120,
|
||||
responsive: ['md'],
|
||||
render: (v: string, d) => (
|
||||
<Space size={6}>
|
||||
<span className="mono">{v || '—'}</span>
|
||||
{d.boot_slot && <Tag>{d.boot_slot}</Tag>}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('admin.fw.target'),
|
||||
dataIndex: 'target_version',
|
||||
width: 110,
|
||||
responsive: ['sm'],
|
||||
render: (v: string) => (v ? <span className="mono">{v}</span> : <span className="muted">—</span>),
|
||||
},
|
||||
{
|
||||
title: t('admin.fw.stateLabel'),
|
||||
dataIndex: 'upgrade_state',
|
||||
width: 140,
|
||||
responsive: ['sm'],
|
||||
render: (s: string, d) => {
|
||||
const st = STATE_STYLE[s] || STATE_STYLE['']
|
||||
return (
|
||||
<Space direction="vertical" size={0}>
|
||||
<Tag color={st.color}>{t(`admin.fw.state.${st.key}`)}</Tag>
|
||||
{d.upgrade_error && <span className="muted">{d.upgrade_error}</span>}
|
||||
</Space>
|
||||
)
|
||||
},
|
||||
},
|
||||
{ title: t('admin.fw.updatedAt'), dataIndex: 'upgrade_at', width: 120, responsive: ['md'], render: fmtTime },
|
||||
{
|
||||
title: t('admin.fw.actions'),
|
||||
key: 'op',
|
||||
width: 230,
|
||||
align: 'right',
|
||||
render: (_, d) => (
|
||||
<Space size={6}>
|
||||
<Select
|
||||
size="small"
|
||||
style={{ width: 130 }}
|
||||
placeholder={t('admin.fw.pickVersion')}
|
||||
options={fws.map((f) => ({
|
||||
value: f.id,
|
||||
label: `${f.version}${f.published ? '' : ` (${t('admin.fw.draft')})`}`,
|
||||
}))}
|
||||
onSelect={(v: string) => pushOne(d, v)}
|
||||
/>
|
||||
{d.target_version && (
|
||||
<Button size="small" type="text" onClick={() => cancelOne(d)}>
|
||||
{t('admin.fw.cancel')}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<Spin spinning={loading}>
|
||||
<Row gutter={[12, 12]}>
|
||||
<Col xs={12} md={6}>
|
||||
<Card className="panel stat-card">
|
||||
<Statistic title={t('admin.fw.statDevices')} value={ups?.total ?? 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card className="panel stat-card">
|
||||
<Statistic title={t('admin.fw.statLatest')} value={ups?.latest || '—'} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card className="panel stat-card">
|
||||
<Statistic title={t('admin.fw.statPending')} value={ups?.pending ?? 0} />
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={12} md={6}>
|
||||
<Card className="panel stat-card">
|
||||
<Statistic title={t('admin.fw.statVersions')} value={Object.keys(ups?.by_version || {}).length} />
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Card
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<UploadIcon size={15} />
|
||||
</span>
|
||||
{t('admin.fw.uploadTitle')}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<Form form={form} layout="vertical" initialValues={{ channel: 'stable', publish: false }}>
|
||||
<Dragger
|
||||
className="fw-dragger"
|
||||
accept=".bin"
|
||||
maxCount={1}
|
||||
// 选中的文件名与大小直接显示在拖拽区内(见 fw-drop-hint),不再重复一条文件列表
|
||||
showUploadList={false}
|
||||
beforeUpload={(f) => {
|
||||
setFile(f)
|
||||
return false
|
||||
}}
|
||||
>
|
||||
<span className="fw-drop">
|
||||
<UploadIcon size={20} />
|
||||
<span>
|
||||
<span className="fw-drop-title">{t('admin.fw.dropText')}</span>
|
||||
<span className="fw-drop-hint">
|
||||
{file ? (
|
||||
<span className="fw-drop-file">{`${file.name} · ${fmtSize(file.size)}`}</span>
|
||||
) : (
|
||||
t('admin.fw.dropHint', { size: fmtSize(maxSize) })
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</Dragger>
|
||||
|
||||
<Row gutter={[16, 0]} className="fw-fields">
|
||||
<Col xs={24} sm={8}>
|
||||
<Form.Item
|
||||
name="version"
|
||||
label={t('admin.fw.version')}
|
||||
rules={[
|
||||
{ required: true, message: t('common.required') },
|
||||
{ pattern: /^\d{1,3}\.\d{1,3}\.\d{1,3}(-[0-9A-Za-z.-]{1,16})?$/, message: t('admin.fw.versionRule') },
|
||||
]}
|
||||
>
|
||||
<Input placeholder="0.1.2" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Form.Item name="channel" label={t('admin.fw.channel')}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'stable', label: 'stable' },
|
||||
{ value: 'beta', label: 'beta' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} sm={8}>
|
||||
<Form.Item name="min_version" label={t('admin.fw.minVersion')} tooltip={t('admin.fw.minVersionHint')}>
|
||||
<Input placeholder={t('admin.fw.minVersionPlaceholder')} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 0]}>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="notes" label={t('admin.fw.notes')}>
|
||||
<TextArea rows={2} placeholder={t('admin.fw.notesPlaceholder')} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="notes_en" label={t('admin.fw.notesEn')}>
|
||||
<TextArea rows={2} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<div className="fw-actions">
|
||||
<Button type="primary" loading={uploading} onClick={submitUpload}>
|
||||
{t('common.ok')}
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<ChipIcon size={15} />
|
||||
</span>
|
||||
{t('admin.fw.listTitle')}
|
||||
</span>
|
||||
}
|
||||
extra={
|
||||
<Button icon={<RefreshIcon size={15} />} onClick={load}>
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="middle"
|
||||
columns={fwColumns}
|
||||
dataSource={fws}
|
||||
pagination={false}
|
||||
locale={{ emptyText: t('admin.fw.empty') }}
|
||||
scroll={{ x: 1000 }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<ChipIcon size={15} />
|
||||
</span>
|
||||
{t('admin.fw.devicesTitle')}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="toolbar">
|
||||
<Input.Search allowClear placeholder={t('admin.fw.searchDevice')} style={{ width: 260 }} onSearch={setQ} />
|
||||
<div className="toolbar-right">
|
||||
<Button icon={<RefreshIcon size={15} />} onClick={load}>
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="middle"
|
||||
columns={devColumns}
|
||||
dataSource={ups?.items || []}
|
||||
pagination={{ pageSize: 10, hideOnSinglePage: true }}
|
||||
locale={{ emptyText: t('admin.fw.noDevice') }}
|
||||
scroll={{ x: 920 }}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Modal
|
||||
open={!!editing}
|
||||
title={`${t('admin.fw.editTitle')} · ${editing?.version ?? ''}`}
|
||||
onCancel={() => setEditing(null)}
|
||||
onOk={saveEdit}
|
||||
okText={t('common.save')}
|
||||
cancelText={t('common.cancel')}
|
||||
>
|
||||
<Form form={editForm} layout="vertical">
|
||||
<Form.Item name="channel" label={t('admin.fw.channel')}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: 'stable', label: 'stable' },
|
||||
{ value: 'beta', label: 'beta' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="min_version" label={t('admin.fw.minVersion')}>
|
||||
<Input placeholder="0.1.0" />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes" label={t('admin.fw.notes')}>
|
||||
<TextArea rows={3} />
|
||||
</Form.Item>
|
||||
<Form.Item name="notes_en" label={t('admin.fw.notesEn')}>
|
||||
<TextArea rows={3} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
</Spin>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { App, Button, Card, Input, Result, Space, Typography } from 'antd'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { api } from '../api'
|
||||
import LangSwitch from '../components/LangSwitch'
|
||||
import ThemeSwitch from '../components/ThemeSwitch'
|
||||
|
||||
const { Title, Paragraph, Text } = Typography
|
||||
|
||||
// 扫码进来形如 /bind?code=123456&did=44BD8D6EA0A0 —— 预填配对码、只读展示设备末四位
|
||||
export default function Bind() {
|
||||
const { t } = useTranslation()
|
||||
const { message } = App.useApp()
|
||||
const nav = useNavigate()
|
||||
const [params] = useSearchParams()
|
||||
const [code, setCode] = useState(params.get('code') || '')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [done, setDone] = useState(false)
|
||||
const did = params.get('did') || ''
|
||||
|
||||
useEffect(() => {
|
||||
if (params.get('code')) setCode(params.get('code')!.slice(0, 6))
|
||||
}, [params])
|
||||
|
||||
async function pair() {
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
message.warning(t('home.pairCode'))
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
const d = await api.pair(code)
|
||||
message.success(`${t('bind.bound')} ${d.model}`)
|
||||
setDone(true)
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<Card bordered={false} className="auth-card">
|
||||
<Result
|
||||
status="success"
|
||||
title={t('home.bindOk')}
|
||||
subTitle={t('bind.successTip')}
|
||||
extra={[
|
||||
<Button type="primary" key="home" onClick={() => nav('/', { replace: true })}>
|
||||
{t('bind.toDevices')}
|
||||
</Button>,
|
||||
]}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<Card bordered={false} className="auth-card">
|
||||
<div className="auth-head">
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
{t('bind.title')}
|
||||
</Title>
|
||||
<div className="auth-controls">
|
||||
<LangSwitch />
|
||||
<ThemeSwitch />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Paragraph type="secondary" style={{ marginTop: 12, marginBottom: 20 }}>
|
||||
{t('bind.tip')}
|
||||
{did && (
|
||||
<>
|
||||
<br />
|
||||
<Text code>
|
||||
{t('bind.device')} …{did.slice(-4)}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Paragraph>
|
||||
|
||||
<Space direction="vertical" size={12} style={{ width: '100%' }}>
|
||||
<Input
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
placeholder="000000"
|
||||
maxLength={6}
|
||||
className="code-input"
|
||||
size="large"
|
||||
/>
|
||||
<Button type="primary" size="large" block loading={busy} onClick={pair}>
|
||||
{t('bind.confirm')}
|
||||
</Button>
|
||||
<Button block onClick={() => nav('/')}>
|
||||
{t('bind.later')}
|
||||
</Button>
|
||||
</Space>
|
||||
|
||||
<Paragraph type="secondary" style={{ marginTop: 16, marginBottom: 0, fontSize: 12 }}>
|
||||
{t('bind.expiry')}
|
||||
</Paragraph>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,519 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
Cascader,
|
||||
Col,
|
||||
DatePicker,
|
||||
Form,
|
||||
Input,
|
||||
List,
|
||||
Popconfirm,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Spin,
|
||||
Tag,
|
||||
TimePicker,
|
||||
Typography,
|
||||
} from 'antd'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import dayjs from 'dayjs'
|
||||
import {
|
||||
api,
|
||||
auth,
|
||||
type AstroPreview,
|
||||
type Device,
|
||||
type MyFortune,
|
||||
type RegionNode,
|
||||
type User,
|
||||
type Zodiac,
|
||||
} from '../api'
|
||||
import TopBar from '../components/TopBar'
|
||||
import MediaCard from '../components/MediaCard'
|
||||
import {
|
||||
DeviceIcon,
|
||||
LinkIcon,
|
||||
PinIcon,
|
||||
SaveIcon,
|
||||
SparkIcon,
|
||||
UserIcon,
|
||||
} from '../components/icons'
|
||||
|
||||
const { Text, Paragraph } = Typography
|
||||
|
||||
function fmt(ts?: string | null) {
|
||||
return ts ? dayjs(ts).format('MM-DD HH:mm') : '—'
|
||||
}
|
||||
|
||||
// 码表是三级树,资料的 code 可能落在任意一级:找出从根到它的路径
|
||||
function findPath(nodes: RegionNode[], code: string, trail: string[] = []): string[] | null {
|
||||
for (const n of nodes) {
|
||||
const next = [...trail, n.code]
|
||||
if (n.code === code) return next
|
||||
if (n.children) {
|
||||
const hit = findPath(n.children, code, next)
|
||||
if (hit) return hit
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 常用时区快捷列表,其余场景(跨国)很少见,管理端码表里还有各城市的时区兜底
|
||||
const TIMEZONES = [
|
||||
'Asia/Shanghai',
|
||||
'Asia/Hong_Kong',
|
||||
'Asia/Macau',
|
||||
'Asia/Taipei',
|
||||
'Asia/Tokyo',
|
||||
'Asia/Seoul',
|
||||
'Asia/Singapore',
|
||||
'Asia/Bangkok',
|
||||
'Asia/Kolkata',
|
||||
'Asia/Dubai',
|
||||
'Europe/London',
|
||||
'Europe/Paris',
|
||||
'Europe/Berlin',
|
||||
'Europe/Moscow',
|
||||
'America/New_York',
|
||||
'America/Chicago',
|
||||
'America/Los_Angeles',
|
||||
'America/Sao_Paulo',
|
||||
'Australia/Sydney',
|
||||
'UTC',
|
||||
]
|
||||
|
||||
type Sign = { name?: string | null; symbol?: string | null; degree?: number | null; element?: string }
|
||||
|
||||
function SignTile({ label, sign, dateRange }: { label: string; sign: Sign; dateRange?: string }) {
|
||||
const { t } = useTranslation()
|
||||
const empty = !sign.name
|
||||
return (
|
||||
<div className={`sign-tile${empty ? ' is-empty' : ''}`}>
|
||||
<div className="sign-label">{label}</div>
|
||||
<div className="sign-symbol">{sign.symbol || '—'}</div>
|
||||
<div className="sign-name">{sign.name || t('home.signEmpty')}</div>
|
||||
<div className="sign-meta">
|
||||
{empty ? (
|
||||
<span>{t('home.signHint')}</span>
|
||||
) : (
|
||||
<>
|
||||
{sign.element && <span>{sign.element}</span>}
|
||||
{typeof sign.degree === 'number' && <span>{sign.degree.toFixed(2)}°</span>}
|
||||
{dateRange && <span>{dateRange}</span>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { message } = App.useApp()
|
||||
const nav = useNavigate()
|
||||
const [user, setUser] = useState<User | null>(auth.user)
|
||||
const [devices, setDevices] = useState<Device[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [code, setCode] = useState('')
|
||||
const [tree, setTree] = useState<RegionNode[]>([])
|
||||
const [signs, setSigns] = useState<Record<string, Zodiac>>({})
|
||||
const [preview, setPreview] = useState<AstroPreview | null>(null)
|
||||
const [myFortune, setMyFortune] = useState<MyFortune | null>(null)
|
||||
const [formBasic] = Form.useForm()
|
||||
const [formBirth] = Form.useForm()
|
||||
|
||||
// 树与星座码表都只取一次,回填路径时要用树的引用
|
||||
const treeRef = useRef<RegionNode[]>([])
|
||||
|
||||
const loadFortune = useCallback((lang: string) => {
|
||||
api
|
||||
.myFortune(lang.startsWith('en') ? 'en' : 'zh')
|
||||
.then(setMyFortune)
|
||||
.catch(() => setMyFortune(null))
|
||||
}, [])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const [me, list] = await Promise.all([api.profile(), api.devices()])
|
||||
setUser(me)
|
||||
auth.saveUser(me)
|
||||
setDevices(list)
|
||||
const birthPath = me.birth_region_code ? findPath(treeRef.current, me.birth_region_code) : null
|
||||
const resPath = me.residence_region_code ? findPath(treeRef.current, me.residence_region_code) : null
|
||||
formBasic.setFieldsValue({
|
||||
nickname: me.nickname,
|
||||
residence_path: resPath,
|
||||
timezone: me.timezone || null,
|
||||
})
|
||||
formBirth.setFieldsValue({
|
||||
birthday: me.birthday ? dayjs(me.birthday) : null,
|
||||
birth_time: me.birth_time ? dayjs(me.birth_time, 'HH:mm:ss') : null,
|
||||
birth_path: birthPath,
|
||||
})
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number }
|
||||
if (err.status === 401) nav('/login', { replace: true })
|
||||
else message.error(err.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [formBasic, formBirth, message, nav])
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
;(async () => {
|
||||
// 先拿码表再拿资料,这样出生地能被回填成 Cascader 的路径
|
||||
try {
|
||||
const [treeRes, signRes] = await Promise.all([api.regionsTree(), api.zodiacs()])
|
||||
if (!alive) return
|
||||
treeRef.current = treeRes.items
|
||||
setTree(treeRes.items)
|
||||
setSigns(Object.fromEntries(signRes.items.map((s) => [s.code, s])))
|
||||
} catch {
|
||||
/* 码表拉不到也不挡登录,只是选择器为空 */
|
||||
}
|
||||
if (alive) await load()
|
||||
})()
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [load])
|
||||
|
||||
// 语言切换时运势文案跟着切
|
||||
useEffect(() => {
|
||||
loadFortune(i18n.language)
|
||||
}, [i18n.language, loadFortune])
|
||||
|
||||
// 选日期/时间/城市时即时试算,免得保存完才发现出生地选错
|
||||
const watchedBirthday = Form.useWatch('birthday', formBirth)
|
||||
const watchedTime = Form.useWatch('birth_time', formBirth)
|
||||
const watchedBirthPath = Form.useWatch('birth_path', formBirth)
|
||||
|
||||
useEffect(() => {
|
||||
if (!watchedBirthday) {
|
||||
setPreview(null)
|
||||
return
|
||||
}
|
||||
const leaf = (watchedBirthPath as string[] | undefined)?.slice(-1)[0]
|
||||
const timer = setTimeout(() => {
|
||||
api
|
||||
.astroPreview({
|
||||
birthday: (watchedBirthday as dayjs.Dayjs).format('YYYY-MM-DD'),
|
||||
birth_time: watchedTime ? (watchedTime as dayjs.Dayjs).format('HH:mm:ss') : null,
|
||||
birth_region_code: leaf || null,
|
||||
})
|
||||
.then(setPreview)
|
||||
.catch(() => undefined)
|
||||
}, 400)
|
||||
return () => clearTimeout(timer)
|
||||
}, [watchedBirthday, watchedTime, watchedBirthPath])
|
||||
|
||||
async function bind() {
|
||||
if (!/^\d{6}$/.test(code)) {
|
||||
message.warning(t('home.pairCode'))
|
||||
return
|
||||
}
|
||||
try {
|
||||
await api.pair(code)
|
||||
message.success(t('home.bindOk'))
|
||||
setCode('')
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function unbind(d: Device) {
|
||||
try {
|
||||
await api.unbind(d.id)
|
||||
message.success(t('home.unbindOk'))
|
||||
load()
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveBasic(v: { nickname: string; residence_path?: string[]; timezone?: string | null }) {
|
||||
setSaving(true)
|
||||
try {
|
||||
const me = await api.updateProfile({
|
||||
nickname: v.nickname,
|
||||
residence_region_code: (v.residence_path || []).slice(-1)[0] || null,
|
||||
timezone: v.timezone || null,
|
||||
})
|
||||
setUser(me)
|
||||
auth.saveUser(me)
|
||||
message.success(t('common.saved'))
|
||||
loadFortune(i18n.language)
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function saveBirth(v: Record<string, unknown>) {
|
||||
setSaving(true)
|
||||
try {
|
||||
const birthday = v.birthday as dayjs.Dayjs | null
|
||||
const birthTime = v.birth_time as dayjs.Dayjs | null
|
||||
const me = await api.updateProfile({
|
||||
birthday: birthday ? birthday.format('YYYY-MM-DD') : null,
|
||||
birth_time: birthTime ? birthTime.format('HH:mm:ss') : null,
|
||||
birth_region_code: ((v.birth_path as string[]) || []).slice(-1)[0] || null,
|
||||
})
|
||||
setUser(me)
|
||||
auth.saveUser(me)
|
||||
setPreview(null)
|
||||
message.success(
|
||||
me.sun_sign_name ? t('home.savedWithSign', { sun: me.sun_sign_name, moon: me.moon_sign_name }) : t('common.saved'),
|
||||
)
|
||||
loadFortune(i18n.language)
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
function logout() {
|
||||
api.logout().catch(() => undefined)
|
||||
auth.clear()
|
||||
nav('/login', { replace: true })
|
||||
}
|
||||
|
||||
const pick = (code?: string | null, name?: string | null, symbol?: string | null, degree?: number | null) => ({
|
||||
name,
|
||||
symbol,
|
||||
degree,
|
||||
element: code ? signs[code]?.element : undefined,
|
||||
})
|
||||
const shown = preview
|
||||
? { sun: { ...preview.sun }, moon: { ...preview.moon } }
|
||||
: {
|
||||
sun: pick(user?.sun_sign, user?.sun_sign_name, user?.sun_symbol, user?.sun_degree),
|
||||
moon: pick(user?.moon_sign, user?.moon_sign_name, user?.moon_symbol, user?.moon_degree),
|
||||
}
|
||||
|
||||
const cascaderProps = {
|
||||
options: tree,
|
||||
fieldNames: { label: 'name' as const, value: 'code' as const, children: 'children' as const },
|
||||
changeOnSelect: true as const,
|
||||
showSearch: {
|
||||
filter: (input: string, path: unknown[]) =>
|
||||
path.some((o) => String((o as { name: string; code: string }).name).includes(input) || String((o as { code: string }).code).includes(input)),
|
||||
},
|
||||
placeholder: t('home.regionPlaceholder'),
|
||||
allowClear: true as const,
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<TopBar title="nex_buddy" user={user} onAdmin={() => nav('/admin')} onLogout={logout} />
|
||||
|
||||
<main className="content">
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col xs={24} lg={13}>
|
||||
<Card
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<UserIcon size={15} />
|
||||
</span>
|
||||
{t('home.account')}
|
||||
</span>
|
||||
}
|
||||
className="panel"
|
||||
>
|
||||
<div className="status-row">
|
||||
<span className="status-label">{t('login.account')}</span>
|
||||
<span className="status-value">{user?.email || user?.phone || '—'}</span>
|
||||
</div>
|
||||
<div className="status-row">
|
||||
<span className="status-label">
|
||||
<PinIcon size={14} />
|
||||
{t('home.birthPlace')}
|
||||
</span>
|
||||
<span className="status-value">{user?.birth_place || t('home.notFilled')}</span>
|
||||
</div>
|
||||
<div className="status-row">
|
||||
<span className="status-label">{t('home.registeredAt')}</span>
|
||||
<span className="status-value">
|
||||
{user?.created_at ? dayjs(user.created_at).format('YYYY-MM-DD') : '—'}
|
||||
</span>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<DeviceIcon size={15} />
|
||||
</span>
|
||||
{t('home.devices')}
|
||||
</span>
|
||||
}
|
||||
extra={<Text type="secondary">{t('home.deviceCount', { n: devices.length })}</Text>}
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
<Spin spinning={loading}>
|
||||
{devices.length === 0 ? (
|
||||
<div className="empty-box">
|
||||
<span className="empty-icon">
|
||||
<DeviceIcon size={22} />
|
||||
</span>
|
||||
<span className="empty-title">{t('home.noDevices')}</span>
|
||||
<span className="empty-tip">{t('home.noDevicesTip')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
dataSource={devices}
|
||||
renderItem={(d) => (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Popconfirm
|
||||
key="unbind"
|
||||
title={t('home.unbindConfirm')}
|
||||
description={t('home.unbindTip')}
|
||||
okText={t('home.unbind')}
|
||||
cancelText={t('common.cancel')}
|
||||
onConfirm={() => unbind(d)}
|
||||
>
|
||||
<Button size="small" danger type="text">
|
||||
{t('home.unbind')}
|
||||
</Button>
|
||||
</Popconfirm>,
|
||||
]}
|
||||
>
|
||||
<List.Item.Meta
|
||||
title={
|
||||
<Space size={8}>
|
||||
<span>{d.model || 'Knob'}</span>
|
||||
<Tag color="blue">v{d.fw_version || '—'}</Tag>
|
||||
</Space>
|
||||
}
|
||||
description={
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
{d.chip_id} · {fmt(d.bound_at)} · {fmt(d.last_active_at)}
|
||||
</Text>
|
||||
}
|
||||
/>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Spin>
|
||||
|
||||
<div className="bind-row">
|
||||
<Input
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
|
||||
placeholder={t('home.pairPlaceholder')}
|
||||
maxLength={6}
|
||||
onPressEnter={bind}
|
||||
/>
|
||||
<Button type="primary" icon={<LinkIcon size={15} />} onClick={bind}>
|
||||
{t('home.bind')}
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<MediaCard devices={devices} />
|
||||
</Col>
|
||||
|
||||
<Col xs={24} lg={11}>
|
||||
<Card
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<UserIcon size={15} />
|
||||
</span>
|
||||
{t('home.basicCard')}
|
||||
</span>
|
||||
}
|
||||
className="panel"
|
||||
>
|
||||
<Form form={formBasic} layout="vertical" onFinish={saveBasic} requiredMark={false}>
|
||||
<Form.Item name="nickname" label={t('home.nickname')} rules={[{ required: true, message: t('common.required') }]}>
|
||||
<Input maxLength={20} placeholder={t('home.nicknamePlaceholder')} />
|
||||
</Form.Item>
|
||||
<Form.Item name="residence_path" label={t('home.residenceCity')} tooltip={t('home.residenceCityTip')}>
|
||||
<Cascader {...cascaderProps} />
|
||||
</Form.Item>
|
||||
<Form.Item name="timezone" label={t('home.timezone')} tooltip={t('home.timezoneTip')}>
|
||||
<Select
|
||||
allowClear
|
||||
showSearch
|
||||
placeholder="Asia/Shanghai"
|
||||
options={TIMEZONES.map((z) => ({ value: z, label: z }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" block loading={saving} icon={<SaveIcon size={15} />}>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title={
|
||||
<span className="card-title-row">
|
||||
<span className="card-icon">
|
||||
<SparkIcon size={15} />
|
||||
</span>
|
||||
{t('home.birthCard')}
|
||||
</span>
|
||||
}
|
||||
className="panel"
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
<Spin spinning={loading}>
|
||||
<Form form={formBirth} layout="vertical" onFinish={saveBirth} requiredMark={false}>
|
||||
<Row gutter={12}>
|
||||
<Col span={14}>
|
||||
<Form.Item name="birthday" label={t('home.birthday')}>
|
||||
<DatePicker style={{ width: '100%' }} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col span={10}>
|
||||
<Form.Item name="birth_time" label={t('home.birthTime')}>
|
||||
<TimePicker style={{ width: '100%' }} format="HH:mm" minuteStep={5} />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Form.Item name="birth_path" label={t('home.birthCity')} tooltip={t('home.birthCityTip')}>
|
||||
<Cascader {...cascaderProps} />
|
||||
</Form.Item>
|
||||
|
||||
<Button type="primary" htmlType="submit" block loading={saving} icon={<SaveIcon size={15} />}>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
</Form>
|
||||
|
||||
<div className="astro-grid">
|
||||
<SignTile label={t('home.sunSign')} sign={shown.sun} dateRange={preview?.sun.date_range} />
|
||||
<SignTile label={t('home.moonSign')} sign={shown.moon} dateRange={preview?.moon.date_range} />
|
||||
</div>
|
||||
|
||||
<div className="fortune-note">
|
||||
<div className="fortune-label">{t('home.fortuneTitle')}</div>
|
||||
{myFortune?.fortune?.title && <div className="fortune-head">{myFortune.fortune.title}</div>}
|
||||
<Paragraph style={{ marginBottom: 0, fontSize: 13 }}>
|
||||
{myFortune?.fortune?.content || t('home.fortuneNone')}
|
||||
</Paragraph>
|
||||
</div>
|
||||
</Spin>
|
||||
</Card>
|
||||
|
||||
</Col>
|
||||
</Row>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
import { useState } from 'react'
|
||||
import { App, Button, Card, Form, Input, Segmented, Typography } from 'antd'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { api, auth } from '../api'
|
||||
import LangSwitch from '../components/LangSwitch'
|
||||
import ThemeSwitch from '../components/ThemeSwitch'
|
||||
|
||||
const { Title, Text } = Typography
|
||||
|
||||
// 后端 auth 接口返回的英文 detail → 界面词条(key 对不上就原样显示)
|
||||
const AUTH_ERROR_KEYS: Record<string, string> = {
|
||||
'account or password incorrect': 'login.badPassword',
|
||||
'account disabled': 'login.accountDisabled',
|
||||
'account must be an email or a phone number': 'login.accountFormat',
|
||||
'account already registered': 'login.accountTaken',
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const { t } = useTranslation()
|
||||
const { message } = App.useApp()
|
||||
const nav = useNavigate()
|
||||
const [params] = useSearchParams()
|
||||
const next = params.get('next') || '/'
|
||||
const [mode, setMode] = useState<'login' | 'register'>('login')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
async function submit(v: { account: string; password: string; nickname?: string }) {
|
||||
setBusy(true)
|
||||
try {
|
||||
const r =
|
||||
mode === 'login'
|
||||
? await api.login(v.account.trim(), v.password)
|
||||
: await api.register(v.account.trim(), v.password, v.nickname?.trim() || '')
|
||||
auth.save(r.token, r.user)
|
||||
message.success(mode === 'login' ? t('login.welcomeBack') : t('login.registered'))
|
||||
nav(next, { replace: true })
|
||||
} catch (e) {
|
||||
const raw = (e as Error).message
|
||||
message.error(AUTH_ERROR_KEYS[raw] ? t(AUTH_ERROR_KEYS[raw]) : raw)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<Card className="auth-card" bordered={false}>
|
||||
<div className="auth-head">
|
||||
<div className="brand">
|
||||
<div className="brand-dot" />
|
||||
<div>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
nex_buddy
|
||||
</Title>
|
||||
<Text type="secondary">{t('login.subtitle')}</Text>
|
||||
</div>
|
||||
</div>
|
||||
<div className="auth-controls">
|
||||
<LangSwitch />
|
||||
<ThemeSwitch />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Segmented
|
||||
block
|
||||
value={mode}
|
||||
onChange={(v) => setMode(v as 'login' | 'register')}
|
||||
options={[
|
||||
{ label: t('login.submit'), value: 'login' },
|
||||
{ label: t('login.register'), value: 'register' },
|
||||
]}
|
||||
style={{ margin: '22px 0 18px' }}
|
||||
/>
|
||||
|
||||
<Form layout="vertical" onFinish={submit} requiredMark={false} size="large">
|
||||
<Form.Item
|
||||
name="account"
|
||||
label={t('login.account')}
|
||||
rules={[{ required: true, message: t('login.accountRequired') }]}
|
||||
>
|
||||
<Input autoComplete="username" placeholder={t('login.accountPlaceholder')} />
|
||||
</Form.Item>
|
||||
|
||||
{mode === 'register' && (
|
||||
<Form.Item name="nickname" label={t('login.nicknameOptional')}>
|
||||
<Input placeholder={t('login.nicknamePlaceholder')} maxLength={20} />
|
||||
</Form.Item>
|
||||
)}
|
||||
|
||||
<Form.Item
|
||||
name="password"
|
||||
label={t('login.password')}
|
||||
rules={[
|
||||
{ required: true, message: t('login.passwordRequired') },
|
||||
...(mode === 'register' ? [{ min: 6, message: t('login.passwordMin') }] : []),
|
||||
]}
|
||||
>
|
||||
<Input.Password autoComplete={mode === 'login' ? 'current-password' : 'new-password'} />
|
||||
</Form.Item>
|
||||
|
||||
<Button type="primary" htmlType="submit" block loading={busy} style={{ marginTop: 4 }}>
|
||||
{mode === 'login' ? t('login.submit') : t('login.registerSubmit')}
|
||||
</Button>
|
||||
</Form>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Button, Card, Result, Spin, Typography } from 'antd'
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { api, auth } from '../api'
|
||||
|
||||
const { Title, Text } = Typography
|
||||
|
||||
// 后端 qr-login 的 401 detail(中文原文)→ 界面词条
|
||||
const QR_ERROR_KEYS: Record<string, string> = {
|
||||
'二维码已失效,请在设备上重新打开': 'login.qrExpired',
|
||||
}
|
||||
|
||||
/**
|
||||
* 设备屏上那个二维码的落地页。
|
||||
*
|
||||
* 扫码 → 打开 /qr?t=<票据> → 自动换会话 → 落到个人页。
|
||||
* 设计上刻意不做任何输入:手机扫完就该是"已经登录好了",多一步都是摩擦。
|
||||
*/
|
||||
export default function QrLogin() {
|
||||
const { t } = useTranslation()
|
||||
const nav = useNavigate()
|
||||
const [params] = useSearchParams()
|
||||
const code = (params.get('t') || '').trim()
|
||||
|
||||
const [state, setState] = useState<'busy' | 'ok' | 'fail'>('busy')
|
||||
const [err, setErr] = useState('')
|
||||
// 票据一码一用:StrictMode 下 effect 会跑两遍,第二遍会拿到 401,
|
||||
// 把已经成功的状态覆盖成"已失效"。用 ref 保证只换一次。
|
||||
const started = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (started.current) return
|
||||
started.current = true
|
||||
|
||||
if (!code) {
|
||||
setState('fail')
|
||||
setErr(t('qr.missing'))
|
||||
return
|
||||
}
|
||||
api
|
||||
.qrLogin(code)
|
||||
.then((r) => {
|
||||
auth.save(r.token, r.user)
|
||||
setState('ok')
|
||||
setTimeout(() => nav('/', { replace: true }), 600)
|
||||
})
|
||||
.catch((e) => {
|
||||
setState('fail')
|
||||
const raw = (e as Error).message
|
||||
setErr(QR_ERROR_KEYS[raw] ? t(QR_ERROR_KEYS[raw]) : raw)
|
||||
})
|
||||
}, [code, nav, t])
|
||||
|
||||
return (
|
||||
<div className="auth-wrap">
|
||||
<Card className="auth-card" bordered={false}>
|
||||
<div className="brand">
|
||||
<div className="brand-dot" />
|
||||
<div>
|
||||
<Title level={4} style={{ margin: 0 }}>
|
||||
nex_buddy
|
||||
</Title>
|
||||
<Text type="secondary">{t('qr.subtitle')}</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{state === 'busy' && (
|
||||
<div style={{ padding: '28px 0 12px', textAlign: 'center' }}>
|
||||
<Spin size="large" />
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Text type="secondary">{t('qr.verifying')}</Text>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state === 'ok' && (
|
||||
<Result status="success" title={t('qr.ok')} subTitle={t('qr.redirect')} />
|
||||
)}
|
||||
|
||||
{state === 'fail' && (
|
||||
<Result
|
||||
status="warning"
|
||||
title={t('qr.failed')}
|
||||
subTitle={err || t('qr.failedHint')}
|
||||
extra={
|
||||
<Button type="primary" onClick={() => nav('/login', { replace: true })}>
|
||||
{t('qr.toLogin')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,920 @@
|
|||
/* ------------------------------------------------------------------ 色板
|
||||
亮/暗两套只在这里定义,其他规则一律引用变量。
|
||||
新增颜色先加变量,不要在规则里写死 #hex——否则暗色下必然漏改。 */
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
--brand: #2f7cf6;
|
||||
--brand-ink: #2f5bbf;
|
||||
--ink: #101828;
|
||||
--ink-2: #344054;
|
||||
--muted: #667085;
|
||||
--line: #eaecf0;
|
||||
--line-soft: #f2f4f7;
|
||||
--bg: #f6f7fb;
|
||||
--panel: #ffffff;
|
||||
--panel-2: #fafbfd;
|
||||
--topbar-bg: rgba(255, 255, 255, 0.82);
|
||||
|
||||
--shadow-card: 0 1px 2px rgba(16, 24, 40, 0.04), 0 12px 32px rgba(16, 24, 40, 0.06);
|
||||
--shadow-pop: 0 18px 50px rgba(16, 24, 40, 0.08);
|
||||
|
||||
--tile-bg: linear-gradient(160deg, #f7f9ff 0%, #eef4ff 100%);
|
||||
--tile-line: #e6ecf8;
|
||||
--tile-glow: rgba(47, 124, 246, 0.16);
|
||||
--fortune-bg: #f5f8ff;
|
||||
--fortune-ink: #2f5bbf;
|
||||
--glow-a: #e9f0ff;
|
||||
--glow-b: #e8f7f1;
|
||||
--ring: rgba(47, 124, 246, 0.18);
|
||||
--hover-bg: rgba(16, 24, 40, 0.04);
|
||||
}
|
||||
|
||||
[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
|
||||
--brand: #5b9bff;
|
||||
--brand-ink: #a9c8ff;
|
||||
--ink: #e8ecf5;
|
||||
--ink-2: #c5cddd;
|
||||
--muted: #9aa5ba;
|
||||
--line: #232a3a;
|
||||
--line-soft: #1c2331;
|
||||
--bg: #0b0f19;
|
||||
--panel: #141a28;
|
||||
--panel-2: #171e2d;
|
||||
--topbar-bg: rgba(13, 18, 30, 0.78);
|
||||
|
||||
--shadow-card: 0 1px 2px rgba(0, 0, 0, 0.3), 0 12px 30px rgba(0, 0, 0, 0.28);
|
||||
--shadow-pop: 0 20px 48px rgba(0, 0, 0, 0.5);
|
||||
|
||||
--tile-bg: linear-gradient(160deg, #182034 0%, #131a29 100%);
|
||||
--tile-line: #263048;
|
||||
--tile-glow: rgba(91, 155, 255, 0.22);
|
||||
--fortune-bg: #16203a;
|
||||
--fortune-ink: #a9c8ff;
|
||||
--glow-a: #16203a;
|
||||
--glow-b: #0f241f;
|
||||
--ring: rgba(91, 155, 255, 0.28);
|
||||
--hover-bg: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
|
||||
'Microsoft YaHei', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
transition: background-color 0.24s ease, color 0.24s ease;
|
||||
}
|
||||
|
||||
/* 滚动条跟随主题,暗色下不出现一条刺眼的亮槽 */
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--line) transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--line);
|
||||
border-radius: 99px;
|
||||
border: 3px solid transparent;
|
||||
background-clip: content-box;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--muted);
|
||||
background-clip: content-box;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ 登录 / 绑定
|
||||
antd 的 <App> 会再包一层 div,高度链会断,这里必须用视口单位 */
|
||||
.auth-wrap {
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px 16px;
|
||||
background: radial-gradient(1200px 600px at 20% -10%, var(--glow-a) 0%, transparent 60%),
|
||||
radial-gradient(900px 500px at 110% 10%, var(--glow-b) 0%, transparent 55%), var(--bg);
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
border-radius: 18px;
|
||||
box-shadow: var(--shadow-pop);
|
||||
}
|
||||
|
||||
/* 登录/绑定页的角落控件(语言 + 主题):跟标题同一行,右侧靠齐。
|
||||
旧版用绝对定位,窄屏会和品牌副标题叠在一起,这里改回普通流布局。 */
|
||||
.auth-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.auth-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.brand-dot {
|
||||
display: inline-block; /* Space 的 item 不是 flex 容器,inline 元素宽高会被忽略 */
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 10px;
|
||||
background: conic-gradient(from 140deg, #2f7cf6, #59d3b2, #ffb25e, #2f7cf6);
|
||||
box-shadow: 0 4px 12px rgba(47, 124, 246, 0.35);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.code-input input,
|
||||
.code-input {
|
||||
text-align: center;
|
||||
letter-spacing: 0.5em;
|
||||
font-size: 24px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 布局 */
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
height: 56px;
|
||||
padding: 0 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
background: var(--topbar-bg);
|
||||
backdrop-filter: saturate(180%) blur(12px);
|
||||
border-bottom: 1px solid var(--line);
|
||||
transition: background-color 0.24s ease, border-color 0.24s ease;
|
||||
}
|
||||
|
||||
.topbar-brand,
|
||||
.topbar-actions {
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.topbar-title.ant-typography {
|
||||
margin: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.content {
|
||||
max-width: 1080px;
|
||||
margin: 0 auto;
|
||||
padding: 20px 16px 48px;
|
||||
}
|
||||
|
||||
.panel {
|
||||
border-radius: 16px;
|
||||
box-shadow: var(--shadow-card);
|
||||
}
|
||||
|
||||
/* ============================================================ 统一规范
|
||||
管理后台有 5 个页面,每个页面都自己写 Space + marginBottom 的话,
|
||||
搜索框宽度、按钮间距、计数位置必然各不相同。这里定一套:
|
||||
.toolbar 一行工具条,筛选在左、动作在右、计数靠最右
|
||||
.table-num 数字列右对齐(等宽数字,列看起来才齐)
|
||||
.row-actions 表格行内文字按钮,压缩内边距,避免挤成一片
|
||||
============================================================ */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.toolbar-count {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 卡片头部与内边距统一:标题字号一致,工具条不会顶着卡片边缘 */
|
||||
.panel.ant-card > .ant-card-head {
|
||||
min-height: 56px;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.panel.ant-card > .ant-card-head .ant-card-head-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.panel.ant-card > .ant-card-body {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
/* 表格:表头压成次级文字、行分隔线更淡,整体比 antd 默认干净一档 */
|
||||
.panel .ant-table-wrapper {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.panel .ant-table-wrapper .ant-table-thead > tr > th {
|
||||
background: var(--panel-2);
|
||||
color: var(--muted);
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
padding-top: 10px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.panel .ant-table-wrapper .ant-table-tbody > tr > td {
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
}
|
||||
|
||||
.panel .ant-table-wrapper .ant-table-tbody > tr:last-child > td {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
/* 展开行(用户的设备列表)用底色区分,否则和主表粘在一起 */
|
||||
.panel .ant-table-wrapper .ant-table-tbody > tr.ant-table-expanded-row > td {
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.panel .ant-table-wrapper .ant-table-pagination.ant-pagination {
|
||||
margin: 16px 0 0;
|
||||
}
|
||||
|
||||
/* 分页去掉外框,激活页只用主色文字标识 */
|
||||
.panel .ant-pagination .ant-pagination-item,
|
||||
.panel .ant-pagination .ant-pagination-item-link {
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel .ant-pagination .ant-pagination-item-active {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.table-num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.row-actions .ant-btn {
|
||||
padding-inline: 6px;
|
||||
height: 28px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 危险操作在行内只保留文字色,不额外加底色 */
|
||||
.row-actions .ant-btn-dangerous.ant-btn-text:hover {
|
||||
background: rgba(240, 68, 56, 0.08) !important;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- 顶栏控件:语言/主题/账号 */
|
||||
.icon-btn.ant-btn {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
min-width: 32px;
|
||||
padding: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--muted);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.icon-btn.ant-btn:hover {
|
||||
color: var(--ink);
|
||||
background: var(--hover-bg) !important;
|
||||
}
|
||||
|
||||
.lang-switch.ant-segmented {
|
||||
padding: 2px;
|
||||
border-radius: 10px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.lang-switch .ant-segmented-item-label {
|
||||
min-height: 26px;
|
||||
line-height: 26px;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
.lang-short {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.account-btn.ant-btn {
|
||||
height: 32px;
|
||||
padding: 0 8px 0 4px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-radius: 999px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.account-btn.ant-btn:hover {
|
||||
background: var(--hover-bg) !important;
|
||||
}
|
||||
|
||||
.account-avatar.ant-avatar {
|
||||
background: linear-gradient(140deg, var(--brand), #59d3b2);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.account-name.ant-typography {
|
||||
max-width: 128px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.account-caret {
|
||||
color: var(--muted);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.account-meta {
|
||||
min-width: 168px;
|
||||
padding: 2px 4px 6px;
|
||||
}
|
||||
|
||||
.account-meta-name {
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.account-meta-sub {
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* 下拉里分组项不要灰得像不可点,用普通文字色 */
|
||||
.ant-dropdown-menu-item-disabled .account-meta {
|
||||
opacity: 1;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.ant-dropdown-menu-item-disabled .account-meta-name {
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- 设备绑定 */
|
||||
.bind-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.bind-row .ant-input {
|
||||
letter-spacing: 0.28em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 空态:图标 + 一句引导 + 一条操作提示,比单行 Empty 更有指向性 */
|
||||
.empty-box {
|
||||
padding: 18px 0 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.empty-box .empty-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--brand);
|
||||
background: var(--tile-bg);
|
||||
border: 1px solid var(--tile-line);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.empty-box .empty-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.empty-box .empty-tip {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
max-width: 320px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- 状态列表 */
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px dashed var(--line);
|
||||
}
|
||||
|
||||
.status-row:last-child {
|
||||
border-bottom: none;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.status-row:first-child {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.status-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.status-value {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.status-dot.is-ok {
|
||||
background: #12b76a;
|
||||
box-shadow: 0 0 0 3px rgba(18, 183, 106, 0.16);
|
||||
}
|
||||
|
||||
.status-dot.is-warn {
|
||||
background: #f79009;
|
||||
box-shadow: 0 0 0 3px rgba(247, 144, 9, 0.16);
|
||||
}
|
||||
|
||||
.status-dot.is-bad {
|
||||
background: #f04438;
|
||||
box-shadow: 0 0 0 3px rgba(240, 68, 56, 0.16);
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- 星盘展示 */
|
||||
.astro-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 12px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.sign-tile {
|
||||
position: relative;
|
||||
padding: 14px 14px 12px;
|
||||
border-radius: 14px;
|
||||
border: 1px solid var(--tile-line);
|
||||
background: var(--tile-bg);
|
||||
overflow: hidden;
|
||||
transition: border-color 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.sign-tile::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -28px;
|
||||
top: -28px;
|
||||
width: 92px;
|
||||
height: 92px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle at 30% 30%, var(--tile-glow), transparent 70%);
|
||||
}
|
||||
|
||||
.sign-tile.is-empty {
|
||||
border-style: dashed;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.sign-label {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.sign-symbol {
|
||||
margin-top: 6px;
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
color: var(--brand);
|
||||
/* 星座符号优先走符号字体,否则会被彩色 emoji 字体接管,看着像贴纸 */
|
||||
font-family: 'Apple Symbols', 'Segoe UI Symbol', 'Noto Sans Symbols 2', serif;
|
||||
}
|
||||
|
||||
.sign-name {
|
||||
margin-top: 8px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.sign-meta {
|
||||
margin-top: 6px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.zodiac-glyph {
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
color: var(--brand);
|
||||
font-family: 'Apple Symbols', 'Segoe UI Symbol', 'Noto Sans Symbols 2', serif;
|
||||
}
|
||||
|
||||
/* 本月运势:嵌在星盘卡里,用一条淡分隔线接在太阳/月亮星座下方 */
|
||||
.fortune-note {
|
||||
margin-top: 16px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.fortune-label {
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.fortune-head {
|
||||
margin-bottom: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--fortune-ink);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 卡片标题图标 */
|
||||
.card-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
margin-right: 8px;
|
||||
border-radius: 8px;
|
||||
color: var(--brand);
|
||||
background: var(--tile-bg);
|
||||
border: 1px solid var(--tile-line);
|
||||
vertical-align: -6px;
|
||||
}
|
||||
|
||||
.card-title-row {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
/* 管理端 Tab 文案 + 图标 */
|
||||
.tab-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* TF 卡媒体列表:音乐条目的音符图标占位(图片条目用缩略图) */
|
||||
.media-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 6px;
|
||||
background: var(--panel-2);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* 拖拽上传区:单行(图标 + 文案),压到最矮 */
|
||||
.media-dragger .ant-upload {
|
||||
padding: 9px 12px !important;
|
||||
border-radius: 12px;
|
||||
background: var(--panel-2);
|
||||
}
|
||||
.media-drop-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
line-height: 1.2;
|
||||
}
|
||||
.media-drop-row svg {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* 同步状态条:只展示状态,同步动作在设备端进行 */
|
||||
.media-sync-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
margin-top: 10px;
|
||||
padding: 7px 10px;
|
||||
border-radius: 9px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--line-soft);
|
||||
}
|
||||
.media-empty-line {
|
||||
padding: 6px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 固件管理 */
|
||||
.stat-card.ant-card .ant-card-body {
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.stat-card .ant-statistic-title {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.stat-card .ant-statistic-content {
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
/* 上传拖拽区:横向一行(图标 + 主文案 + 大小提示),不占半屏高度 */
|
||||
.fw-dragger.ant-upload-wrapper .ant-upload-drag {
|
||||
background: var(--panel-2);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.fw-dragger .ant-upload-btn {
|
||||
padding: 18px 16px !important;
|
||||
}
|
||||
|
||||
.fw-drop {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.fw-drop svg {
|
||||
color: var(--brand);
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.fw-drop-title {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.fw-drop-hint {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* 选中文件后文件名比「最大 8 MB」更重要,提一档字色 */
|
||||
.fw-drop-file {
|
||||
color: var(--ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 上传表单:拖拽区 → 三列字段 → 两列说明 → 右对齐操作,统一 16px 栅格 */
|
||||
.fw-fields {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.fw-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.fw-actions .ant-btn {
|
||||
min-width: 96px;
|
||||
}
|
||||
|
||||
.fw-version {
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 芯片号一行显示:窄屏列被压窄时不能按字符竖排 */
|
||||
.fw-chip {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.fw-notes {
|
||||
display: block;
|
||||
max-width: 360px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--ink-2);
|
||||
}
|
||||
|
||||
.mono {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12.5px;
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* 拖拽区在暗色下要跟着主题走,antd 默认用的是浅灰 */
|
||||
.ant-upload-drag {
|
||||
border-radius: 14px;
|
||||
}
|
||||
|
||||
.ant-upload-drag .ant-upload-drag-icon {
|
||||
margin-bottom: 4px;
|
||||
color: var(--brand);
|
||||
}
|
||||
|
||||
.ant-upload-drag .ant-upload-text {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ 响应式 */
|
||||
@media (max-width: 575px) {
|
||||
.hide-sm {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 14px 12px 40px;
|
||||
}
|
||||
|
||||
/* 卡片与工具条在窄屏收紧,给表格留出更多横向空间 */
|
||||
.panel.ant-card > .ant-card-head {
|
||||
padding: 0 14px;
|
||||
min-height: 50px;
|
||||
}
|
||||
|
||||
.panel.ant-card > .ant-card-body {
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.fortune-note {
|
||||
margin-top: 14px;
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
/* 固件上传:窄屏字段竖排后按钮铺满,避免右侧只剩一个孤立小按钮 */
|
||||
.fw-actions .ant-btn {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
gap: 6px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.toolbar .ant-input-search {
|
||||
width: auto !important;
|
||||
flex: 1 1 160px;
|
||||
}
|
||||
|
||||
.toolbar-right {
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.row-actions .ant-btn {
|
||||
padding-inline: 4px;
|
||||
}
|
||||
|
||||
/* 窄屏不横向滚动:列已被 responsive 砍到关键几列,让表格撑满卡片宽度 */
|
||||
.panel .ant-table-content {
|
||||
overflow-x: hidden !important;
|
||||
}
|
||||
|
||||
.panel .ant-table-content > table {
|
||||
width: 100% !important;
|
||||
min-width: 0 !important;
|
||||
table-layout: auto !important;
|
||||
}
|
||||
|
||||
/* 窄屏单元格收紧内边距并允许换行,否则邮箱这类长字段会把后面的列顶出卡片 */
|
||||
.panel .ant-table-thead > tr > th,
|
||||
.panel .ant-table-tbody > tr > td {
|
||||
padding-left: 8px !important;
|
||||
padding-right: 8px !important;
|
||||
}
|
||||
|
||||
.panel .ant-table-cell {
|
||||
white-space: normal !important;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
padding: 0 12px;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.topbar .brand-dot {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
/* 顶栏宽度吃紧:语言只留「中 / EN」,账号只留头像 */
|
||||
.lang-full {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.lang-short {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.lang-switch .ant-segmented-item-label {
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.account-btn.ant-btn {
|
||||
padding: 0 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
|
||||
import { theme as antdTheme, type ThemeConfig } from 'antd'
|
||||
|
||||
export type ThemeMode = 'light' | 'dark'
|
||||
|
||||
const STORAGE_KEY = 'nx.theme'
|
||||
|
||||
// 系统偏好:用户没主动选过时跟随,避免"深色系统 + 白屏"的刺眼首屏
|
||||
function systemTheme(): ThemeMode {
|
||||
if (typeof window === 'undefined' || !window.matchMedia) return 'light'
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
export function currentTheme(): ThemeMode {
|
||||
const saved = localStorage.getItem(STORAGE_KEY)
|
||||
return saved === 'light' || saved === 'dark' ? saved : systemTheme()
|
||||
}
|
||||
|
||||
/** 写到 <html> 上:data-theme 给 CSS 变量用,color-scheme 管原生滚动条与输入光标 */
|
||||
function applyTheme(mode: ThemeMode) {
|
||||
const root = document.documentElement
|
||||
root.dataset.theme = mode
|
||||
root.style.colorScheme = mode
|
||||
}
|
||||
|
||||
type ThemeCtx = {
|
||||
mode: ThemeMode
|
||||
isDark: boolean
|
||||
setMode: (m: ThemeMode) => void
|
||||
toggle: () => void
|
||||
}
|
||||
|
||||
const Ctx = createContext<ThemeCtx>({
|
||||
mode: 'light',
|
||||
isDark: false,
|
||||
setMode: () => undefined,
|
||||
toggle: () => undefined,
|
||||
})
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [mode, setModeState] = useState<ThemeMode>(currentTheme)
|
||||
|
||||
const setMode = useCallback((m: ThemeMode) => {
|
||||
localStorage.setItem(STORAGE_KEY, m)
|
||||
applyTheme(m)
|
||||
setModeState(m)
|
||||
}, [])
|
||||
|
||||
const toggle = useCallback(() => {
|
||||
setModeState((prev) => {
|
||||
const next: ThemeMode = prev === 'dark' ? 'light' : 'dark'
|
||||
localStorage.setItem(STORAGE_KEY, next)
|
||||
applyTheme(next)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
applyTheme(currentTheme())
|
||||
}, [])
|
||||
|
||||
// 只在用户没显式选过时跟随系统切换
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia?.('(prefers-color-scheme: dark)')
|
||||
if (!mq) return
|
||||
const onChange = () => {
|
||||
if (!localStorage.getItem(STORAGE_KEY)) {
|
||||
const next = mq.matches ? 'dark' : 'light'
|
||||
applyTheme(next)
|
||||
setModeState(next)
|
||||
}
|
||||
}
|
||||
mq.addEventListener('change', onChange)
|
||||
return () => mq.removeEventListener('change', onChange)
|
||||
}, [])
|
||||
|
||||
const value = useMemo<ThemeCtx>(
|
||||
() => ({ mode, isDark: mode === 'dark', setMode, toggle }),
|
||||
[mode, setMode, toggle],
|
||||
)
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
return useContext(Ctx)
|
||||
}
|
||||
|
||||
/** antd 的 token:与 styles.css 里的 CSS 变量保持同一套色板,避免两处打架 */
|
||||
export function buildTheme(mode: ThemeMode): ThemeConfig {
|
||||
const dark = mode === 'dark'
|
||||
return {
|
||||
algorithm: dark ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
|
||||
token: {
|
||||
colorPrimary: '#2f7cf6',
|
||||
colorInfo: '#2f7cf6',
|
||||
colorSuccess: '#12b76a',
|
||||
colorWarning: '#f79009',
|
||||
colorError: '#f04438',
|
||||
borderRadius: 10,
|
||||
fontSize: 14,
|
||||
controlHeight: 34,
|
||||
fontFamily:
|
||||
"-apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif",
|
||||
colorBgLayout: dark ? '#0b0f19' : '#f6f7fb',
|
||||
colorBgContainer: dark ? '#141a28' : '#ffffff',
|
||||
colorBgElevated: dark ? '#19202e' : '#ffffff',
|
||||
colorBorderSecondary: dark ? '#242c3e' : '#eaecf0',
|
||||
colorTextBase: dark ? '#e8ecf5' : '#101828',
|
||||
// 暗色下默认的 secondary 偏暗,12px 小字(表单说明、卡片提示)会糊,提亮一档
|
||||
colorTextSecondary: dark ? '#a3aec2' : '#667085',
|
||||
colorTextTertiary: dark ? '#8b96aa' : '#98a2b3',
|
||||
},
|
||||
components: {
|
||||
Card: {
|
||||
headerFontSize: 15,
|
||||
headerHeight: 50,
|
||||
borderRadiusLG: 16,
|
||||
},
|
||||
Button: {
|
||||
fontWeight: 500,
|
||||
primaryShadow: 'none',
|
||||
defaultShadow: 'none',
|
||||
dangerShadow: 'none',
|
||||
},
|
||||
Table: {
|
||||
headerBg: dark ? '#1a2130' : '#fafbfd',
|
||||
headerSplitColor: 'transparent',
|
||||
},
|
||||
Tabs: {
|
||||
titleFontSize: 14,
|
||||
horizontalItemPadding: '10px 0',
|
||||
},
|
||||
Segmented: {
|
||||
itemSelectedBg: dark ? '#262f42' : '#ffffff',
|
||||
},
|
||||
Modal: {
|
||||
borderRadiusLG: 16,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// 端口唯一来源是项目根的 .env:BACKEND_PORT / FRONTEND_PORT。
|
||||
// scripts/dev.sh(后端)和这里(前端)都读同一份,改端口只改 .env 一处。
|
||||
function readRootEnv(): Record<string, string> {
|
||||
const out: Record<string, string> = {}
|
||||
try {
|
||||
const txt = readFileSync(fileURLToPath(new URL('../.env', import.meta.url)), 'utf-8')
|
||||
for (const raw of txt.split('\n')) {
|
||||
const line = raw.trim()
|
||||
if (!line || line.startsWith('#')) continue
|
||||
const eq = line.indexOf('=')
|
||||
if (eq <= 0) continue
|
||||
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim().replace(/^["']|["']$/g, '')
|
||||
}
|
||||
} catch {
|
||||
// 根目录没有 .env 时用默认端口
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const env = readRootEnv()
|
||||
const BACKEND_PORT = Number(env.BACKEND_PORT) || 8100
|
||||
const FRONTEND_PORT = Number(env.FRONTEND_PORT) || 5174
|
||||
|
||||
const proxy = {
|
||||
'/api': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
|
||||
'/device': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
|
||||
'/healthz': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: FRONTEND_PORT,
|
||||
// 默认只监听 [::1],127.0.0.1 会连不上;顺便让手机在同一局域网也能打开调试
|
||||
host: '0.0.0.0',
|
||||
proxy,
|
||||
},
|
||||
// 本地用打包产物验证「手机扫设备屏二维码」这条链路:dev 的按需编译
|
||||
// 在局域网 IP 下会被浏览器的跨网络限制挡住,而线上是静态文件。
|
||||
// 端口同用 FRONTEND_PORT;若 dev server 正在跑被占用,vite 会自动顺延
|
||||
preview: {
|
||||
port: FRONTEND_PORT,
|
||||
host: '0.0.0.0',
|
||||
proxy,
|
||||
},
|
||||
})
|
||||
Loading…
Reference in New Issue