Compare commits

...

22 Commits

Author SHA1 Message Date
xiaoxia f1597749f1 fix(ci): staging-e2e/api-tests容器启动前强制清理,避免DooD模式下命名冲突
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 36s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 48s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 1m27s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 1m32s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 38s
CI/CD Pipeline / Validate - Code Quality (pull_request) Successful in 4m29s
Preview Deploy / Deploy Preview Environment (pull_request) Failing after 23s
AI Code Review / AI Code Review (pull_request) Successful in 3m44s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 4m43s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 3m52s
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 8m41s
CI/CD Pipeline / Unit Tests (pull_request) Successful in 4m46s
CI/CD Pipeline / Integration Tests (pull_request) Successful in 2m10s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 50m8s
Preview Cleanup / Cleanup Preview Environment (pull_request) Successful in 11s
CI/CD Pipeline / Production Browser E2E (pull_request) Failing after 1310h30m19s
CI/CD Pipeline / ACR Image Cleanup (pull_request) Failing after 1310h52m19s
CI/CD Pipeline / Staging API Integration Tests (pull_request) Failing after 1310h52m21s
CI/CD Pipeline / Staging E2E Tests (pull_request) Failing after 1310h52m23s
CI/CD Pipeline / Deploy Production (pull_request) Failing after 1310h52m25s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Failing after 1311h6m9s
CI/CD Pipeline / Build Production Worker Image (pull_request) Failing after 1311h6m11s
CI/CD Pipeline / Build Production Web Image (pull_request) Failing after 1311h6m13s
CI/CD Pipeline / Build Production API Image (pull_request) Failing after 1311h6m15s
CI/CD Pipeline / Frontend Unit Tests (pull_request) Failing after 1311h6m17s
CI/CD Pipeline / Build Staging Worker Image (pull_request) Failing after 1311h13m43s
CI/CD Pipeline / Build Staging Web Image (pull_request) Failing after 1311h13m45s
CI/CD Pipeline / Build Staging API Image (pull_request) Failing after 1311h13m47s
2026-07-24 00:06:51 +08:00
CI Bot f21d981585 style: auto-format with black + isort + prettier
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m34s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 47s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m5s
CI/CD Pipeline / Unit Tests (push) Successful in 4m57s
CI/CD Pipeline / Integration Tests (push) Successful in 2m13s
CI/CD Pipeline / Frontend Lint (push) Successful in 28s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 54s
CI/CD Pipeline / Build Staging API Image (push) Successful in 12m48s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m10s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 3m19s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m26s
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Failing after 1310h52m27s
CI/CD Pipeline / Deploy Production (push) Failing after 1311h6m46s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1311h15m57s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1311h15m59s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1311h16m31s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1311h16m33s
CI/CD Pipeline / PR Build API Image (push) Failing after 1311h16m35s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1311h18m13s
CI/CD Pipeline / Build Production API Image (push) Failing after 1311h48m25s
2026-07-23 15:57:09 +00:00
xiaoxia ed21ee11d2 refactor(#776): 统一配置入口,建立packages/config消除重复定义 (#791)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 23:55:01 +08:00
xiaoxia c6941a738c docs(#780): 补齐.env.example缺失的30+配置项 (#790)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 23:54:59 +08:00
xiaoxia d92909321c refactor(#777): 修复Domain层依赖Adapters的DDD违规(4处) (#789)
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m14s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 2m12s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m28s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m24s
CI/CD Pipeline / Unit Tests (push) Successful in 6m25s
CI/CD Pipeline / Integration Tests (push) Successful in 5m4s
CI/CD Pipeline / Frontend Lint (push) Successful in 45s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 1m23s
CI/CD Pipeline / Build Staging API Image (push) Successful in 11m44s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m17s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 2m36s
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Failing after 1311h30m48s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1311h31m38s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1311h31m40s
CI/CD Pipeline / Build Production API Image (push) Failing after 1311h31m42s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1311h33m45s
CI/CD Pipeline / PR Build API Image (push) Failing after 1311h33m49s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1311h33m56s
CI/CD Pipeline / Deploy Production (push) Failing after 1312h3m14s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1312h6m11s
2026-07-23 23:54:56 +08:00
CI Bot a2bddf726e style: auto-format with black + isort + prettier
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m35s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m47s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m44s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 2m50s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 1m23s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 2m59s
CI/CD Pipeline / Frontend Lint (push) Successful in 4m44s
CI/CD Pipeline / Unit Tests (push) Successful in 6m16s
CI/CD Pipeline / Build Staging API Image (push) Successful in 11m44s
CI/CD Pipeline / Integration Tests (push) Successful in 2m50s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 53s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 7s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 26s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 4m23s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1311h54m1s
CI/CD Pipeline / Deploy Production (push) Failing after 1312h1m2s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1312h11m48s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1312h11m50s
CI/CD Pipeline / PR Build API Image (push) Failing after 1312h13m28s
CI/CD Pipeline / Build Production API Image (push) Failing after 1312h11m52s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1312h13m29s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1312h13m26s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1312h45m50s
2026-07-23 15:05:23 +00:00
xiaoxia c052e857ff style: black格式化3个BGM相关测试文件(修复develop push CI Code Quality)(#787)
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m1s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 2m15s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m34s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m30s
CI/CD Pipeline / Unit Tests (push) Successful in 5m57s
CI/CD Pipeline / Integration Tests (push) Successful in 3m16s
CI/CD Pipeline / Frontend Lint (push) Successful in 40s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 50s
CI/CD Pipeline / Build Staging API Image (push) Successful in 12m4s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m29s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 4m25s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 56s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 5m39s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 5m37s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1312h24m1s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1312h24m7s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1312h24m8s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1312h25m37s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1312h25m39s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1312h25m43s
CI/CD Pipeline / Deploy Production (push) Failing after 1312h56m28s
CI/CD Pipeline / Build Production API Image (push) Failing after 1312h56m33s
CI/CD Pipeline / PR Build API Image (push) Failing after 1312h58m4s
2026-07-23 23:01:01 +08:00
xiaoxia 3862996045 refactor(#783): 统一API文件命名风格为kebab-case (#788)
CI/CD Pipeline / Production Browser E2E (push) Failing after 1312h43m40s
CI/CD Pipeline / Deploy Production (push) Failing after 1312h43m42s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1312h48m16s
CI/CD Pipeline / Build Production API Image (push) Failing after 1312h48m20s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1312h49m4s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1312h51m34s
CI/CD Pipeline / PR Build API Image (push) Failing after 1312h49m8s
CI/CD Pipeline / Build Staging API Image (push) Successful in 13m4s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 2m5s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 4m56s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 58s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 2m0s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m5s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m12s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 21s
CI/CD Pipeline / Unit Tests (push) Successful in 6m21s
CI/CD Pipeline / Integration Tests (push) Successful in 2m38s
CI/CD Pipeline / Frontend Lint (push) Successful in 46s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 2m39s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1313h21m29s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 4m40s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1313h20m41s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 35s
2026-07-23 22:34:56 +08:00
xiaoxia 69845eedc6 chore(#782): 清理废弃文件 init-tables.sql / routers.py / api_docs.html (#785)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 22:34:54 +08:00
xiaoxia 389d1e4401 refactor(#775): 禁止API直接调用Worker任务函数,必须走Celery队列或shared层 (#786)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 22:34:51 +08:00
xiaoxia a009cd382a fix(ci): 修复integration-tests needs依赖 + push事件auto-fix支持
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
fix(ci): 修复integration-tests needs依赖 + push事件auto-fix支持
2026-07-23 22:33:23 +08:00
xiaoxia 956d90c5c2 refactor(#774): 统一配置管理,消除重复定义和默认值不一致
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 57s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m7s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 56s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 50s
CI/CD Pipeline / Unit Tests (push) Successful in 5m52s
CI/CD Pipeline / Integration Tests (push) Successful in 2m55s
CI/CD Pipeline / Frontend Lint (push) Successful in 27s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 1m31s
CI/CD Pipeline / Build Staging API Image (push) Successful in 11m4s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m45s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 3m41s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 25s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m11s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 6m53s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1313h0m28s
CI/CD Pipeline / Deploy Production (push) Failing after 1313h0m30s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1313h0m36s
CI/CD Pipeline / Build Production API Image (push) Failing after 1313h0m40s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1313h4m30s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1313h6m39s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1313h4m32s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1313h33m1s
CI/CD Pipeline / PR Build API Image (push) Failing after 1313h36m56s
2026-07-23 22:17:50 +08:00
xiaoxia 678d3503a7 fix(test): 修复JWT篡改签名测试flaky - 改签名中间字符而非最后一位 (#770)
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m5s
CI/CD Pipeline / Frontend Lint (push) Successful in 30s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 57s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m3s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 2m7s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 1m23s
CI/CD Pipeline / Integration Tests (push) Successful in 4m1s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 5m51s
CI/CD Pipeline / Unit Tests (push) Successful in 6m43s
CI/CD Pipeline / Build Staging API Image (push) Successful in 15m42s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Failing after 1313h13m39s
CI/CD Pipeline / Deploy Production (push) Failing after 1313h21m27s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1313h31m19s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1313h31m21s
CI/CD Pipeline / Build Production API Image (push) Failing after 1313h31m23s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1313h35m3s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1313h35m5s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1313h36m45s
CI/CD Pipeline / PR Build API Image (push) Failing after 1314h7m29s
fix(test): 修复JWT篡改签名测试flaky - 改签名中间字符而非最后一位
2026-07-23 21:52:01 +08:00
xiaoxia 90dd5c6d80 test(p3-1): wave31 素材库+素材UseCase单测20个 (#772)
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m43s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m51s
CI/CD Pipeline / Frontend Lint (push) Successful in 1m53s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m59s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 2m6s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 1m1s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 2m50s
CI/CD Pipeline / Integration Tests (push) Successful in 4m53s
CI/CD Pipeline / Unit Tests (push) Successful in 8m32s
CI/CD Pipeline / Build Staging API Image (push) Successful in 11m55s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 47s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 10s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 30s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 4m2s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1314h26m42s
CI/CD Pipeline / Deploy Production (push) Failing after 1314h26m44s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1314h28m55s
CI/CD Pipeline / Build Production API Image (push) Failing after 1314h28m57s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1314h30m43s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1314h30m42s
CI/CD Pipeline / PR Build API Image (push) Failing after 1314h30m44s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1314h30m45s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1315h1m16s
2026-07-23 20:46:04 +08:00
xiaoxia e81c7444b0 test(p3-1): wave30 Project领域模型+UseCase单测39个 (#771)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 20:45:46 +08:00
xiaoxia 081e58e5a0 fix: 修复2个ruff F401未使用import错误(BGM PR引入) (#773)
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m14s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m31s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m26s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m20s
CI/CD Pipeline / Unit Tests (push) Successful in 7m17s
CI/CD Pipeline / Integration Tests (push) Successful in 4m26s
CI/CD Pipeline / Frontend Lint (push) Successful in 37s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 43s
CI/CD Pipeline / Build Staging API Image (push) Successful in 12m38s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 1m37s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 4m37s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 1m6s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 3m9s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 6m37s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1314h40m8s
CI/CD Pipeline / Deploy Production (push) Failing after 1314h40m10s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1314h40m32s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1314h40m34s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1314h43m27s
CI/CD Pipeline / Build Production API Image (push) Failing after 1314h40m36s
CI/CD Pipeline / PR Build API Image (push) Failing after 1314h43m31s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1314h44m20s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1315h15m51s
fix: 修复2个ruff F401未使用import错误(BGM PR引入)
2026-07-23 20:44:36 +08:00
xiaoxia 486f1a092e style: black格式化3个AI相关文件(修复develop Validate Code Quality失败) (#768)
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m23s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m15s
CI/CD Pipeline / Frontend Lint (push) Successful in 40s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m12s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 2m4s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 4m8s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 44s
CI/CD Pipeline / Integration Tests (push) Successful in 3m33s
CI/CD Pipeline / Unit Tests (push) Successful in 7m9s
CI/CD Pipeline / Build Staging API Image (push) Successful in 13m15s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 52s
CI/CD Pipeline / ACR Image Cleanup (push) Successful in 25s
CI/CD Pipeline / Staging API Integration Tests (push) Successful in 3m59s
CI/CD Pipeline / Staging E2E Tests (push) Failing after 4m50s
CI/CD Pipeline / Production Browser E2E (push) Failing after 1315h0m45s
CI/CD Pipeline / Deploy Production (push) Failing after 1315h0m47s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1315h1m0s
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1315h0m58s
CI/CD Pipeline / Build Production API Image (push) Failing after 1315h1m2s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1315h8m33s
CI/CD Pipeline / PR Build API Image (push) Failing after 1315h8m37s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1315h10m5s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1315h40m57s
2026-07-23 20:10:42 +08:00
xiaoxia 021001073b fix(ci): 修复Staging E2E/API Tests DooD挂载路径问题 - 改用docker cp (#769)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 20:04:20 +08:00
xiaoxia 7d92f82900 Merge pull request 'feat(#642): 一键生成支持自定义BGM' (#763) from feat/custom-bgm-generation into develop
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 19:45:08 +08:00
xiaoxia 3e621bee2c fix(ci): P0系统性修复 - concurrency/UnitTests/门禁同步(4项全改) (#765)
CI/CD Pipeline / Check if frontend-only change (push) Has been cancelled
CI/CD Pipeline / Validate - Code Quality (push) Has been cancelled
CI/CD Pipeline / Validate - Type Check (mypy) (push) Has been cancelled
CI/CD Pipeline / Validate - Migration (alembic) (push) Has been cancelled
CI/CD Pipeline / Unit Tests (push) Has been cancelled
CI/CD Pipeline / Integration Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Has been cancelled
CI/CD Pipeline / Frontend Unit Tests (push) Has been cancelled
CI/CD Pipeline / PR Build API Image (push) Has been cancelled
CI/CD Pipeline / PR Build Web Image (push) Has been cancelled
CI/CD Pipeline / PR Build Worker Image (push) Has been cancelled
CI/CD Pipeline / Build Staging API Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Web Image (push) Has been cancelled
CI/CD Pipeline / Build Staging Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Build Production API Image (push) Has been cancelled
CI/CD Pipeline / Build Production Web Image (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
2026-07-23 19:38:03 +08:00
xiaoxia 5629cf63ec fix(web): 修复微信回调页token时序bug - 先存token再取用户信息 (#764)
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Build Production Worker Image (push) Failing after 1315h47m45s
CI/CD Pipeline / Build Production API Image (push) Failing after 1315h47m49s
CI/CD Pipeline / PR Build Worker Image (push) Failing after 1315h52m20s
CI/CD Pipeline / PR Build API Image (push) Failing after 1315h52m24s
CI/CD Pipeline / Check if frontend-only change (push) Failing after 1315h53m9s
CI/CD Pipeline / Validate - Code Quality (push) Failing after 1m23s
CI/CD Pipeline / Validate - Type Check (mypy) (push) Successful in 1m22s
CI/CD Pipeline / Validate - Migration (alembic) (push) Successful in 1m17s
CI/CD Pipeline / Unit Tests (push) Successful in 7m50s
CI/CD Pipeline / Integration Tests (push) Successful in 3m43s
CI/CD Pipeline / Frontend Lint (push) Successful in 34s
CI/CD Pipeline / Frontend Unit Tests (push) Successful in 53s
CI/CD Pipeline / PR Build Web Image (push) Failing after 1316h24m44s
CI/CD Pipeline / Build Staging API Image (push) Successful in 6m55s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 3m7s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 3m4s
CI/CD Pipeline / Build Production Web Image (push) Failing after 1316h20m9s
2026-07-23 19:35:46 +08:00
CI Bot a9896e1507 feat(#642): 一键生成支持自定义BGM
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 21s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 37s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 25s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 1m21s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 1m23s
CI/CD Pipeline / Validate - Code Quality (pull_request) Failing after 1m55s
Preview Deploy / Deploy Preview Environment (pull_request) Failing after 23s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 59s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 53s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 4m34s
CI/CD Pipeline / Integration Tests (pull_request) Successful in 2m40s
AI Code Review / AI Code Review (pull_request) Successful in 4m4s
CI/CD Pipeline / Unit Tests (pull_request) Successful in 5m49s
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 10m3s
Preview Cleanup / Cleanup Preview Environment (pull_request) Successful in 19s
CI/CD Pipeline / Production Browser E2E (pull_request) Failing after 1317h0m15s
CI/CD Pipeline / Staging API Integration Tests (pull_request) Failing after 1317h0m19s
CI/CD Pipeline / Staging E2E Tests (pull_request) Failing after 1317h0m21s
CI/CD Pipeline / Build Production Worker Image (pull_request) Failing after 1317h0m27s
CI/CD Pipeline / Deploy Production (pull_request) Failing after 1317h0m23s
CI/CD Pipeline / Build Production Web Image (pull_request) Failing after 1317h0m29s
CI/CD Pipeline / Build Production API Image (pull_request) Failing after 1317h0m31s
CI/CD Pipeline / Build Staging Worker Image (pull_request) Failing after 1317h1m57s
CI/CD Pipeline / Build Staging Web Image (pull_request) Failing after 1317h1m57s
CI/CD Pipeline / Build Staging API Image (pull_request) Failing after 1317h1m59s
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Failing after 1317h32m46s
CI/CD Pipeline / ACR Image Cleanup (pull_request) Failing after 1317h32m38s
CI/CD Pipeline / Frontend Unit Tests (pull_request) Failing after 1317h32m54s
- 领域模型 GenerationTask 新增 bgm_config 字段
- ORM/Repository/UseCase/API 全链路透传 bgm_config
- Worker 端新增 BGM 配置合并逻辑(用户配置 > 模板配置)
- enabled 字段特殊处理:用户显式传才覆盖模板状态
- 合并逻辑抽至 packages/domain/bgm_utils.py 纯函数
- 14个BGM合并单测 + 2个领域单测,全量4246通过
2026-07-23 18:25:06 +08:00
123 changed files with 2986 additions and 1011 deletions
+180 -42
View File
@@ -1,60 +1,198 @@
# 小虾 SaaS 环境变量配置
# ============================================================
# 小虾 SaaS 环境变量完整配置
# ============================================================
# 本文件列出所有可配置的环境变量及默认值。
# 复制为 .env 后按需修改;生产环境务必覆盖所有密钥类配置。
#
# 配置读取规则(pydantic-settings,大小写不敏感):
# 1. 系统环境变量(最高优先级)
# 2. .env.{APP_ENV} 文件(如 .env.staging)
# 3. .env 文件
# 4. 代码中的默认值(最低优先级)
# ============================================================
# ==================== 应用配置 ====================
APP_NAME=小虾 SaaS
APP_BASE_URL=http://localhost:3000
# ==================== 应用基本配置 ====================
# 应用名称
APP_NAME=xiaoxia-saas
# 应用版本号(展示用,代码中已内置默认)
APP_VERSION=0.1.61
# 环境标识:development / staging / production
# 决定读取 .env.{APP_ENV} 还是 .env,也影响部分配置的严格校验
APP_ENV=development
# ==================== 数据库配置 ====================
DATABASE_URL=postgresql://xiaoxia_user:your_password@localhost:5432/xiaoxia_saas
# 开发环境:使用内存数据库(不需要 PostgreSQL)
USE_IN_MEMORY_DB=true
# 生产环境:使用 PostgreSQL
# USE_IN_MEMORY_DB=false
# ==================== Redis 配置 ====================
REDIS_URL=redis://localhost:6379/0
# ==================== JWT 配置 ====================
JWT_SECRET_KEY=your-super-secret-key-change-this-in-production-min-32-chars
JWT_ALGORITHM=HS256
JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30
JWT_REFRESH_TOKEN_EXPIRE_DAYS=30
# ==================== 邮件配置 ====================
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-specific-password
SMTP_FROM_EMAIL=noreply@xiaoxia-saas.com
SMTP_FROM_NAME=小虾 SaaS
# ==================== 环境配置 ====================
ENVIRONMENT=development
# 是否开启 Debug 模式(开发环境 true,生产环境 false)
DEBUG=true
# ==================== CORS 配置 ====================
# 逗号分隔的域名列表(Settings 读取 CORS_ORIGINS_RAW)
CORS_ORIGINS_RAW=http://localhost:3000,http://localhost:5173
# 应用基础 URL,用于生成认证邮件、回调链接等
APP_BASE_URL=http://localhost:3000
# API 服务监听地址(容器内绑定,外部暴露由 Docker/Nginx 控制)
API_HOST=0.0.0.0
# API 服务监听端口
API_PORT=8000
# 是否自动创建数据库表结构(开发环境可开启,生产环境用 alembic migration)
AUTO_CREATE_SCHEMA=false
# ==================== 数据库配置 ====================
# 数据库连接串(格式:postgresql+psycopg://user:password@host:port/dbname)
DATABASE_URL=postgresql+psycopg://postgres:postgres@localhost:5432/xiaoxia_saas
# 连接池大小(常驻连接数)
DATABASE_POOL_SIZE=20
# 连接池最大溢出连接数(pool_size + max_overflow = 最大并发连接数)
DATABASE_MAX_OVERFLOW=10
# 获取连接超时时间(秒)
DATABASE_POOL_TIMEOUT=30
# 连接回收时间(秒),防止数据库端主动断开导致的死连接
DATABASE_POOL_RECYCLE=3600
# 是否使用内存数据库(SQLite,仅开发/测试可用;生产务必 false)
USE_IN_MEMORY_DB=false
# ==================== Redis 配置 ====================
# Redis 连接 URL(格式:redis://[:password@]host:port/db)
REDIS_URL=redis://localhost:6379/0
# 是否使用 Redis 存储 Session(多实例部署时必须开启;开发可用内存存储)
ENABLE_REDIS_SESSIONS=false
# ==================== Celery 任务队列 ====================
# Celery Broker(任务分发),默认用 Redis db0
CELERY_BROKER_URL=redis://localhost:6379/0
# Celery Result Backend(任务结果存储),默认用 Redis db1
CELERY_RESULT_BACKEND=redis://localhost:6379/1
# ==================== Worker 配置 ====================
# Worker 进程名称
WORKER_NAME=xiaoxia-saas-worker
# Worker 并发数(同时执行的任务数)
WORKER_CONCURRENCY=4
# 每个子进程最多处理多少任务后重启(防止内存泄漏)
WORKER_MAX_TASKS_PER_CHILD=1000
# ==================== JWT 认证配置 ====================
# JWT 签名密钥 — 生产环境必须设置为强随机字符串(至少32字符)
# 内置不安全值会被拒绝:secret / changeme / password / your-secret-key 等
JWT_SECRET_KEY=your-super-secret-key-change-this-in-production-min-32-chars
# JWT 签名算法
JWT_ALGORITHM=HS256
# Access Token 过期时间(分钟)
JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30
# Refresh Token 过期时间(天)
JWT_REFRESH_TOKEN_EXPIRE_DAYS=30
# ==================== 邮件配置 ====================
# 是否启用邮件投递(关闭时邮件内容打印到日志,开发调试用)
ENABLE_EMAIL_DELIVERY=false
# SMTP 服务器地址
SMTP_HOST=smtp.gmail.com
# SMTP 端口
SMTP_PORT=587
# SMTP 用户名
SMTP_USER=your-email@gmail.com
# SMTP 密码 / 应用专用密码
SMTP_PASSWORD=your-app-specific-password
# 发件人邮箱
SMTP_FROM_EMAIL=noreply@xiaoxia-saas.com
# 发件人显示名称
SMTP_FROM_NAME=小虾 SaaS
# 是否启用 TLS
SMTP_USE_TLS=true
# ==================== 阿里云 OSS 配置 ====================
# OSS 区域 endpoint
OSS_ENDPOINT=oss-cn-hangzhou.aliyuncs.com
# OSS Access Key ID — 非开发环境必须设置
OSS_ACCESS_KEY_ID=your-access-key-id
# OSS Access Key Secret — 非开发环境必须设置
OSS_ACCESS_KEY_SECRET=your-access-key-secret
# OSS Bucket 名称
OSS_BUCKET_NAME=xiaoxia-autocut
# ==================== CosyVoice 语音合成配置 ====================
# 注意:base_url 只需写到 /api/v1,具体路径由代码拼接
# 模型: cosyvoice-v3-flash (推荐,支持系统音色,性价比高)
# cosyvoice-v3-plus (高质量,系统音色少)
# cosyvoice-v3.5-flash / cosyvoice-v3.5-plus (仅支持克隆/设计音色,无系统音色)
# 音色: v3系列系统音色带 _v3 后缀,如 longxiaochun_v3, longxiaoxia_v3, longanyang (无后缀)
# 注意:COSYVOICE_* 变量由 packages/shared/config.py 的 SharedSettings 读取
# 直传最大文件大小(MB)
OSS_DIRECT_UPLOAD_MAX_MB=2000
# 直传签名有效期(秒)
OSS_DIRECT_UPLOAD_EXPIRE_SECONDS=900
# ==================== CORS 配置 ====================
# 允许跨域的前端域名列表,逗号分隔
CORS_ORIGINS_RAW=http://localhost:3000,http://localhost:5173,http://localhost:8000
# ==================== 渲染引擎配置 ====================
# 渲染引擎选择:
# legacy — 旧 VideoComposeService(稳定,功能完整)
# unified — 新 UnifiedRenderService(新架构,部分场景仍在验证)
RENDER_ENGINE=legacy
# ==================== CosyVoice 语音合成 ====================
# 阿里云百灵语音合成服务
# 模型选择:
# cosyvoice-v3-flash — 推荐,系统音色多,性价比高
# cosyvoice-v3-plus — 高质量,系统音色少
# cosyvoice-v3.5-flash / cosyvoice-v3.5-plus — 仅支持克隆/设计音色,无系统音色
# 音色:v3 系列系统音色带 _v3 后缀,如 longxiaochun_v3 / longxiaoxia_v3 / longanyang
COSYVOICE_API_KEY=your-cosyvoice-api-key
COSYVOICE_BASE_URL=https://dashscope.aliyuncs.com/api/v1
COSYVOICE_MODEL=cosyvoice-v3-flash
COSYVOICE_VOICE=longxiaochun_v3
COSYVOICE_SAMPLE_RATE=22050
COSYVOICE_FORMAT=mp3
# 音色克隆模型名(固定为 voice-enrollment,通常不需修改)
COSYVOICE_CLONE_MODEL=voice-enrollment
# ==================== 豆包大模型(火山引擎方舟) ====================
# 用于 AI 文案生成、智能剪辑等需要大模型能力的场景
DOUBAO_API_KEY=your-doubao-api-key
DOUBAO_MODEL=doubao-seed-1-6-250615
DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
DOUBAO_TIMEOUT=30
DOUBAO_MAX_RETRIES=2
+27 -6
View File
@@ -22,7 +22,8 @@ permissions:
contents: read
concurrency:
group: ci-pipeline-${{ gitea.event_name }}-${{ gitea.ref }}
cancel-in-progress: true
# PR事件取消进行中的旧run,push事件不取消(确保完整CI跑完)
cancel-in-progress: ${{ gitea.event_name == 'pull_request' }}
jobs:
check-frontend-only:
name: Check if frontend-only change
@@ -394,7 +395,9 @@ jobs:
if: always() && needs.check-frontend-only.outputs.skip_backend != 'true'
needs:
- check-frontend-only
- validate
- validate-code-quality
- validate-type-check
- validate-migration
env:
DATABASE_URL: postgresql+psycopg://postgres:postgres@host.docker.internal:5432/xiaoxia_saas
USE_IN_MEMORY_DB: 'false'
@@ -1083,15 +1086,24 @@ jobs:
shell: sh
run: |
set -eu
docker run --rm --ipc=host \
# DooD模式下不能用-v挂载(宿主机路径与CI容器路径不一致)
# 改用 docker create + docker cp 方式把代码拷进容器
CONTAINER_NAME="staging-e2e-$$"
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
docker create --name "$CONTAINER_NAME" --ipc=host \
-e E2E_BASE_URL=https://staging.xiaoxiajianji.com \
-e E2E_API_BASE=https://staging-api.xiaoxiajianji.com/api/v1 \
-e E2E_BROWSER_CHANNEL=chromium \
-e PLAYWRIGHT_HEADLESS=1 \
-v "$PWD:/workspace" \
-w /workspace/apps/web \
git.xiaoxiajianji.com/xiaoxia/base/playwright:v1.45.0-jammy \
sh -lc "npm ci && npx playwright test --reporter=line --project=chromium e2e/auth.spec.ts e2e/auth-guard.spec.ts e2e/core-upload.spec.ts e2e/core-generation.spec.ts"
docker cp apps "$CONTAINER_NAME:/workspace/"
docker cp package-lock.json "$CONTAINER_NAME:/workspace/" 2>/dev/null || true
docker start -a "$CONTAINER_NAME"
EXIT_CODE=$(docker wait "$CONTAINER_NAME")
docker rm "$CONTAINER_NAME" 2>/dev/null || true
exit $EXIT_CODE
- name: Job duration summary
if: always()
@@ -1139,13 +1151,22 @@ jobs:
shell: sh
run: |
set -eu
docker run --rm \
# DooD模式下不能用-v挂载(宿主机路径与CI容器路径不一致)
# 改用 docker create + docker cp 方式把代码拷进容器
CONTAINER_NAME="staging-api-tests-$$"
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
docker create --name "$CONTAINER_NAME" \
-e E2E_BASE_URL=https://staging.xiaoxiajianji.com \
-e E2E_API_BASE=https://staging-api.xiaoxiajianji.com/api/v1 \
-v "$PWD:/workspace" \
-w /workspace/apps/web \
git.xiaoxiajianji.com/xiaoxia/base/playwright:v1.45.0-jammy \
sh -lc 'npm ci && npx playwright test --reporter=line e2e/test_auth.spec.ts e2e/test_asset.spec.ts e2e/test_project.spec.ts'
docker cp apps "$CONTAINER_NAME:/workspace/"
docker cp package-lock.json "$CONTAINER_NAME:/workspace/" 2>/dev/null || true
docker start -a "$CONTAINER_NAME"
EXIT_CODE=$(docker wait "$CONTAINER_NAME")
docker rm "$CONTAINER_NAME" 2>/dev/null || true
exit $EXIT_CODE
- name: Job duration summary
if: always()
Regular → Executable
+7 -4
View File
@@ -1,4 +1,3 @@
import os
from logging.config import fileConfig
from sqlalchemy import engine_from_config, pool
@@ -8,13 +7,17 @@ from alembic import context
# Import your models' Base here
from packages.adapters.sqlalchemy_impl.models import Base
# 使用统一配置入口获取 database_url,而非直接读环境变量
from packages.config import get_shared_settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
database_url = os.getenv("DATABASE_URL")
if database_url:
config.set_main_option("sqlalchemy.url", database_url)
# 从统一配置系统获取 database_url,确保与应用使用同一配置源
settings = get_shared_settings()
if settings.database_url:
config.set_main_option("sqlalchemy.url", settings.database_url)
# Interpret the config file for Python logging.
# This line sets up loggers basically.
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -1,3 +1,4 @@
from app.api.routes.ai import router as ai_router
from app.api.routes.asset_diagnosis import router as asset_diagnosis_router
from app.api.routes.asset_libraries import router as asset_libraries_router
from app.api.routes.assets import router as assets_router
@@ -9,7 +10,6 @@ from app.api.routes.feature_flags import router as feature_flags_router
from app.api.routes.generation_tasks import router as generation_tasks_router
from app.api.routes.health import router as health_check_router
from app.api.routes.ingest_jobs import router as ingest_jobs_router
from app.api.routes.ai import router as ai_router
from app.api.routes.internal_render import router as internal_render_router
from app.api.routes.projects import router as projects_router
from app.api.routes.share import router as share_router
+1 -1
View File
@@ -5,7 +5,7 @@
from __future__ import annotations
from typing import List, Literal, Optional
from typing import List, Literal
from app.services.ai_service import TITLE_STYLES, generate_smart_titles, semantic_match_assets
from fastapi import APIRouter
+2 -1
View File
@@ -30,7 +30,6 @@ from app.schemas.generation_task import (
GenerationTaskResponse,
ListGenerationTasksResponse,
)
from app.services.smart_asset_selector import SmartAssetSelector
from fastapi import APIRouter, Depends, HTTPException
from packages.application import (
@@ -61,6 +60,7 @@ def _to_generation_task_response(task) -> GenerationTaskResponse:
batch_id=getattr(task, "batch_id", ""),
video_title=getattr(task, "video_title", ""),
resolution=getattr(task, "resolution", ""),
bgm_config=getattr(task, "bgm_config", {}) or {},
logs=getattr(task, "logs", "[]"),
status=task.status,
progress=task.progress,
@@ -289,6 +289,7 @@ def create_generation_task(
batch_id=batch_id,
video_title=request.video_title,
resolution=request.resolution,
bgm_config=request.bgm_config,
auto_retry_enabled=request.auto_retry_enabled,
auto_retry_max=request.auto_retry_max,
)
+2 -2
View File
@@ -1907,7 +1907,7 @@ def editor_ai_recommend(
detail="当前草稿状态不支持AI推荐,请先编辑后再试",
)
from apps.worker.worker_app.tasks.ai_tasks import run_ai_recommend
from packages.shared.ai_service import run_ai_recommend
result = run_ai_recommend(
plan_id=plan_id,
@@ -1992,7 +1992,7 @@ def editor_generate_cover(
_, plan_svc = services
plan = plan_svc.get_plan_or_raise(plan_id)
from apps.worker.worker_app.tasks.ai_tasks import run_generate_cover
from packages.shared.ai_service import run_generate_cover
cover_data = run_generate_cover(
plan_id=plan_id,
+3 -6
View File
@@ -6,6 +6,7 @@ import logging
from typing import Optional
from app.auth import AuthenticatedUser, get_current_user
from app.core.celery_app import celery_app
from app.dependencies import (
get_audio_url_signer,
get_cosyvoice_service,
@@ -181,13 +182,9 @@ def synthesize(
try:
if is_segment:
from worker_app.tasks import process_tts_segment_synthesis
process_tts_segment_synthesis.delay(job.id)
celery_app.send_task("worker.process_tts_segment_synthesis", args=[job.id])
else:
from worker_app.tasks import process_tts_synthesis
process_tts_synthesis.delay(job.id)
celery_app.send_task("worker.process_tts_synthesis", args=[job.id])
except Exception as e:
# Celery 调度失败,标记 job 为 failed
try:
+3 -6
View File
@@ -6,6 +6,7 @@ import logging
from typing import Optional
from app.auth import AuthenticatedUser, get_current_user
from app.core.celery_app import celery_app
from app.dependencies import get_cosyvoice_service, get_voice_clone_profile_repository
from app.schemas.voice_clone import (
CreateVoiceCloneRequest,
@@ -97,9 +98,7 @@ def create_voice_clone(
task_id = (profile.metadata or {}).get("cosyvoice_task_id", "")
if profile.status == "processing" and task_id:
try:
from worker_app.tasks import process_voice_clone
process_voice_clone.delay(profile.id)
celery_app.send_task("worker.process_voice_clone", args=[profile.id])
logger.info(f"Celery task dispatched for voice clone {profile.id}")
except Exception as e:
logger.error(f"Failed to dispatch Celery task: {e}")
@@ -213,9 +212,7 @@ def retry_voice_clone(
task_id = (profile.metadata or {}).get("cosyvoice_task_id", "")
if profile.status == "processing" and task_id:
try:
from worker_app.tasks import process_voice_clone
process_voice_clone.delay(profile.id)
celery_app.send_task("worker.process_voice_clone", args=[profile.id])
logger.info(f"Celery task dispatched for voice clone retry {profile.id}")
except Exception as e:
logger.error(f"Failed to dispatch Celery task: {e}")
+23 -166
View File
@@ -1,171 +1,28 @@
import os
from typing import Optional
"""API 服务配置(向后兼容层)。
from pydantic import AliasChoices, Field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
统一配置已迁移到 packages.config.api_settings。
新代码请使用:
from packages.config import APISettings, get_api_settings
本文件保留 Settings 类名、get_settings() 函数、settings 模块级单例,
确保所有旧的 import 路径仍然有效。
"""
class Settings(BaseSettings):
APP_NAME: str = "xiaoxia-saas"
APP_VERSION: str = "0.1.61"
ENVIRONMENT: str = "development"
DEBUG: bool = True
# 应用基础 URL,用于生成认证邮件中的链接
# 开发环境默认 http://localhost:3000
# 生产环境应通过环境变量 APP_BASE_URL 设置
APP_BASE_URL: str = "http://localhost:3000"
# Container bind address; external expose is controlled by Docker/Nginx.
API_HOST: str = "0.0.0.0" # nosec: B104
API_PORT: int = 8000
DATABASE_URL: str = "postgresql+psycopg://postgres:postgres@localhost:5432/xiaoxia_saas"
DATABASE_POOL_SIZE: int = 20
DATABASE_MAX_OVERFLOW: int = 10 # 调整为合理值:pool_size(20) + max_overflow(10) = 最大30连接
DATABASE_POOL_TIMEOUT: int = 30
DATABASE_POOL_RECYCLE: int = 3600
USE_IN_MEMORY_DB: bool = False
AUTO_CREATE_SCHEMA: bool = False
REDIS_URL: str = "redis://localhost:6379/0"
ENABLE_REDIS_SESSIONS: bool = False
# JWT secret key - MUST be set via environment variable, no default allowed
JWT_SECRET_KEY: Optional[str] = None
# JWT 算法与过期时间(与 .env.example 对齐)
JWT_ALGORITHM: str = "HS256"
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 30
@field_validator("JWT_SECRET_KEY", mode="before")
@classmethod
def validate_jwt_secret_key(cls, v):
if v is None or v == "":
raise ValueError(
"JWT_SECRET_KEY must be set via environment variable. " "Do not use default value in production!"
)
# Block known insecure default values
insecure_defaults = [
"your-secret-key-change-in-production",
"your-secret-key",
"secret",
"changeme",
"password",
]
if v.lower() in [d.lower() for d in insecure_defaults]:
raise ValueError(
f"JWT_SECRET_KEY '{v}' is insecure. " "Please set a strong random secret via environment variable."
)
return v
ENABLE_EMAIL_DELIVERY: bool = False
SMTP_HOST: str = "smtp.gmail.com"
SMTP_PORT: int = 587
SMTP_USER: str = ""
SMTP_PASSWORD: str = ""
SMTP_FROM_EMAIL: str = ""
SMTP_FROM_NAME: str = "小虾 SaaS"
SMTP_USE_TLS: bool = True
CELERY_BROKER_URL: str = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND: str = "redis://localhost:6379/1"
# OSS 七牛云相关
OSS_ENDPOINT: str = "oss-cn-hangzhou.aliyuncs.com"
OSS_ACCESS_KEY_ID: str = ""
OSS_ACCESS_KEY_SECRET: str = ""
OSS_BUCKET_NAME: str = "xiaoxia-autocut"
@field_validator("OSS_ACCESS_KEY_ID", mode="before")
@classmethod
def validate_oss_access_key_id(cls, v):
if (v is None or v == "") and os.getenv("APP_ENV", "development") != "development":
raise ValueError(
"OSS_ACCESS_KEY_ID must be set via environment variable in non-development environments. "
"Check the server .env file (e.g. /var/lib/xiaoxia-saas-staging/.env)."
)
return v or ""
@field_validator("OSS_ACCESS_KEY_SECRET", mode="before")
@classmethod
def validate_oss_access_key_secret(cls, v):
if (v is None or v == "") and os.getenv("APP_ENV", "development") != "development":
raise ValueError(
"OSS_ACCESS_KEY_SECRET must be set via environment variable in non-development environments. "
"Check the server .env file (e.g. /var/lib/xiaoxia-saas-staging/.env)."
)
return v or ""
OSS_DIRECT_UPLOAD_MAX_MB: int = Field(
default=2000,
validation_alias=AliasChoices("OSS_DIRECT_UPLOAD_MAX_MB", "MAX_UPLOAD_SIZE_MB"),
)
OSS_DIRECT_UPLOAD_EXPIRE_SECONDS: int = 900
CORS_ORIGINS_RAW: str = "http://localhost:3000,http://localhost:5173,http://localhost:8000"
# 渲染引擎选择:legacy=旧VideoComposeService,unified=新UnifiedRenderService
RENDER_ENGINE: str = "legacy"
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
@property
def CORS_ORIGINS(self) -> list[str]:
return [origin.strip() for origin in self.CORS_ORIGINS_RAW.split(",") if origin.strip()]
@property
def database_url(self) -> str:
return self.DATABASE_URL
@property
def redis_url(self) -> str:
return self.REDIS_URL
@property
def celery_broker_url(self) -> str:
return self.CELERY_BROKER_URL
@property
def celery_result_backend(self) -> str:
return self.CELERY_RESULT_BACKEND
@property
def oss_endpoint(self) -> str:
return self.OSS_ENDPOINT
@property
def oss_access_key_id(self) -> str:
return self.OSS_ACCESS_KEY_ID
@property
def oss_access_key_secret(self) -> str:
return self.OSS_ACCESS_KEY_SECRET
@property
def oss_bucket_name(self) -> str:
return self.OSS_BUCKET_NAME
_settings: Optional[Settings] = None
def get_settings() -> Settings:
global _settings
if _settings is None:
env = os.getenv("APP_ENV", "development")
env_file = f".env.{env}" if env != "development" else ".env"
if os.path.exists(env_file):
_settings = Settings(_env_file=env_file)
else:
_settings = Settings()
return _settings
from packages.config import APISettings as Settings
from packages.config import get_api_settings as get_settings
from packages.config import reload_settings_cache
# 模块级单例(向后兼容)
settings = get_settings()
# 暴露旧的 reload_settings 函数名
def reload_settings():
"""重新加载配置(测试用)。"""
reload_settings_cache()
global settings
settings = get_settings()
return settings
__all__ = ["Settings", "get_settings", "settings", "reload_settings"]
Regular → Executable
+10 -9
View File
@@ -1,19 +1,20 @@
"""Compatibility layer for the canonical API settings module.
"""向后兼容层 — 配置已统一到 packages.config。
Use `app.config` as the single source of truth for API configuration.
This module remains only for older imports during migration.
新代码请使用:
from packages.config import get_api_settings, APISettings
"""
from app.config import Settings as AppSettings
from app.config import get_settings, settings
from packages.config import APISettings as AppSettings
from packages.config import get_api_settings as get_settings
from packages.config import reload_settings_cache
def reload_settings() -> AppSettings:
"""Reload settings for tests and legacy callers."""
import app.config as canonical_config
"""重新加载配置(测试用)。"""
reload_settings_cache()
return get_settings()
canonical_config.settings = canonical_config.get_settings()
return canonical_config.settings
settings = get_settings()
__all__ = ["AppSettings", "get_settings", "reload_settings", "settings"]
+6
View File
@@ -51,6 +51,11 @@ class CreateGenerationTaskRequest(BaseModel):
default="",
description="输出分辨率,格式为 WIDTHxHEIGHT,如 1280x720、1080x1920。为空使用默认 1280x720",
)
# ── 自定义 BGM ──
bgm_config: dict = Field(
default_factory=dict,
description="自定义BGM配置,覆盖模板BGM设置。支持 enabled/source/asset_id/preset_id/audio_url/volume 等字段",
)
@model_validator(mode="after")
def _check_at_least_one_mode(self) -> "CreateGenerationTaskRequest":
@@ -80,6 +85,7 @@ class GenerationTaskResponse(BaseModel):
batch_id: str = ""
video_title: str = ""
resolution: str = ""
bgm_config: dict = Field(default_factory=dict)
status: str
progress: float
result_count: int
+16 -15
View File
@@ -298,11 +298,13 @@ def _semantic_match_fallback(
score = min(1.0, base_score * 0.8 + name_bonus)
score = round(score, 3)
results.append({
**asset,
"match_score": score,
"match_reason": "fallback_keyword",
})
results.append(
{
**asset,
"match_score": score,
"match_reason": "fallback_keyword",
}
)
# 按匹配度降序
results.sort(key=lambda x: x["match_score"], reverse=True)
@@ -414,9 +416,7 @@ def semantic_match_assets(
tags = asset.get("tags", [])
tags_str = ",".join(str(t) for t in tags[:5])
desc = str(asset.get("description", ""))[:80]
asset_summaries.append(
f"ID:{aid} | 名称:{name} | 标签:[{tags_str}] | 描述:{desc}"
)
asset_summaries.append(f"ID:{aid} | 名称:{name} | 标签:[{tags_str}] | 描述:{desc}")
asset_ids = [str(a.get("id", "")) for a in assets[:50]]
@@ -434,8 +434,7 @@ def semantic_match_assets(
user_prompt = (
f"目标视频描述:{description}\n\n"
f"素材列表:\n" + "\n".join(asset_summaries) +
f"\n\n请返回每个素材的匹配分数JSON:"
f"素材列表:\n" + "\n".join(asset_summaries) + "\n\n请返回每个素材的匹配分数JSON:"
)
messages = [
@@ -457,11 +456,13 @@ def semantic_match_assets(
for asset in assets:
aid = str(asset.get("id", ""))
score = scores.get(aid, 0.3) # 没评分的给默认偏低分
matched.append({
**asset,
"match_score": round(score, 3),
"match_reason": "doubao_semantic",
})
matched.append(
{
**asset,
"match_score": round(score, 3),
"match_reason": "doubao_semantic",
}
)
matched.sort(key=lambda x: x["match_score"], reverse=True)
logger.info(
-8
View File
@@ -1,8 +0,0 @@
from fastapi import APIRouter
router = APIRouter()
@router.get("/health")
def health():
return {"ok": True, "service": "api"}
Executable → Regular
View File
Executable → Regular
View File
+2 -2
View File
@@ -8,8 +8,8 @@
* - POST /api/v1/templates/{id}/toggle-favorite — 收藏/取消收藏
*/
import apiClient from "./client"
import type { TitleConfig, SubtitleConfig, BgmConfig } from "./editingPlanner"
import type { EditPlanConfig } from "./templateEditor"
import type { TitleConfig, SubtitleConfig, BgmConfig } from "./editing-planner"
import type { EditPlanConfig } from "./template-editor"
/* ──────────── 类型定义 ──────────── */
@@ -12,8 +12,8 @@
import React, { useState, useMemo, useCallback, useRef, useEffect } from "react"
import "./AssetSelector.css"
import { Input, Select, Button } from "@/components/ui"
import type { MediaAsset } from "@/api/templateEditor"
import { MATERIAL_TYPE_LABELS, MATERIAL_TYPE_ICONS, QUALITY_OPTIONS } from "@/api/templateEditor"
import type { MediaAsset } from "@/api/template-editor"
import { MATERIAL_TYPE_LABELS, MATERIAL_TYPE_ICONS, QUALITY_OPTIONS } from "@/api/template-editor"
/* ──────────── 类型 ──────────── */
View File
View File
+2 -2
View File
@@ -12,8 +12,8 @@
*/
import React, { useState, useCallback, useRef, useEffect } from "react"
import { Modal, Button } from "@/components/ui"
import { createVoiceClone, toVoiceClone } from "@/api/voiceClone"
import type { VoiceClone } from "@/api/voiceClone"
import { createVoiceClone, toVoiceClone } from "@/api/voice-clone"
import type { VoiceClone } from "@/api/voice-clone"
import { uploadAsset } from "@/api/assets"
import "./clone-modal.css"
View File
Executable → Regular
View File
+2 -2
View File
@@ -5,8 +5,8 @@
* 全部完成(ready / failed)后停止轮询。
*/
import { useState, useEffect, useCallback, useRef } from "react"
import { getVoiceClones } from "@/api/voiceClone"
import type { VoiceClone } from "@/api/voiceClone"
import { getVoiceClones } from "@/api/voice-clone"
import type { VoiceClone } from "@/api/voice-clone"
const POLL_INTERVAL = 3000 // 3 秒
View File
View File
View File
+7 -1
View File
@@ -39,7 +39,13 @@ const WechatCallback: React.FC = () => {
const result = await wechatCallback(code, state)
// 获取用户信息
// 先把 token 存到 localStorage,让请求拦截器能拿到(getCurrentUser 需要带 token)
localStorage.setItem("access_token", result.access_token)
if (result.refresh_token) {
localStorage.setItem("refresh_token", result.refresh_token)
}
// 获取用户信息(这时候请求拦截器能拿到 token 了)
const userData = await getCurrentUser()
const user: User = normalizeUser(userData)
setAuth(user, result.access_token, result.refresh_token)
View File
@@ -11,7 +11,7 @@ import type {
TemplateCategory,
TemplateMode,
SaveTemplatePayload,
} from "@/api/editingPlanner"
} from "@/api/editing-planner"
import {
getEditingTemplates,
getEditingTemplate,
@@ -19,9 +19,9 @@ import {
updateEditingTemplate,
getTemplateCategories,
MODE_LABELS,
} from "@/api/editingPlanner"
import type { MediaAsset, TransitionEffect, TitleConfig } from "@/api/templateEditor"
import { getMediaAssets, getEditPlan, getEditPlanClips } from "@/api/templateEditor"
} from "@/api/editing-planner"
import type { MediaAsset, TransitionEffect, TitleConfig } from "@/api/template-editor"
import { getMediaAssets, getEditPlan, getEditPlanClips } from "@/api/template-editor"
import { useUndoRedo } from "./hooks/useUndoRedo"
import type {
ClipData,
@@ -4,9 +4,9 @@
*/
import React, { useRef, useState, useCallback } from "react"
import { useNavigate } from "react-router-dom"
import type { TemplateMode } from "@/api/editingPlanner"
import type { TemplateMode } from "@/api/editing-planner"
import type { ClipData, ClipType } from "../types"
import { TRANSITION_OPTIONS } from "@/api/templateEditor"
import { TRANSITION_OPTIONS } from "@/api/template-editor"
import type { AssetItem } from "@/api/assets"
interface SubtitleSettings {
View File
@@ -4,8 +4,8 @@
*/
import React from "react"
import { CloseOutlined, InboxOutlined } from "@ant-design/icons"
import type { EditPlanGeneration } from "@/api/templateEditor"
import { PLAN_STATUS_LABELS } from "@/api/templateEditor"
import type { EditPlanGeneration } from "@/api/template-editor"
import { PLAN_STATUS_LABELS } from "@/api/template-editor"
interface GenerationHistoryModalProps {
open: boolean
@@ -7,7 +7,7 @@ import React, { useCallback } from "react"
import { Drawer } from "antd"
import type { IntroOutroConfig, IntroOutroItem, IntroOutroKind, TransitionType } from "../types"
import { DEFAULT_INTRO_OUTRO } from "../types"
import { TRANSITION_OPTIONS } from "@/api/templateEditor"
import { TRANSITION_OPTIONS } from "@/api/template-editor"
/* ──────────── 常量 ──────────── */
@@ -3,10 +3,10 @@
* Tab 切换:模板列表 + 素材库
*/
import React, { useState } from "react"
import type { EditingTemplate } from "@/api/editingPlanner"
import { MODE_LABELS } from "@/api/editingPlanner"
import type { MediaAsset } from "@/api/templateEditor"
import AssetSelector from "@/components/AssetSelector/AssetSelector"
import type { EditingTemplate } from "@/api/editing-planner"
import { MODE_LABELS } from "@/api/editing-planner"
import type { MediaAsset } from "@/api/template-editor"
import AssetSelector from "@/components/asset-selector/AssetSelector"
interface MediaPanelProps {
templates: EditingTemplate[]
View File
@@ -5,7 +5,7 @@
*/
import React from "react"
import type { ClipData, ClipType } from "../types"
import type { TitleConfig } from "@/api/templateEditor"
import type { TitleConfig } from "@/api/template-editor"
import type { CoverConfig } from "../types"
interface SubtitleSettings {
@@ -4,7 +4,7 @@
*/
import React from "react"
import { Modal, Input, Select } from "@/components/ui"
import type { TemplateCategory } from "@/api/editingPlanner"
import type { TemplateCategory } from "@/api/editing-planner"
interface SaveModalProps {
open: boolean
View File
@@ -10,7 +10,7 @@
*/
import React, { useState, useRef, useCallback, useEffect, useLayoutEffect, useMemo } from "react"
import type { ClipData, ClipType, TrimConfig } from "../types"
import { TRANSITION_OPTIONS } from "@/api/templateEditor"
import { TRANSITION_OPTIONS } from "@/api/template-editor"
interface TimelinePanelProps {
clips: ClipData[]
@@ -5,7 +5,7 @@
*/
import React, { useCallback } from "react"
import { Drawer, Slider } from "antd"
import { TRANSITION_OPTIONS } from "@/api/templateEditor"
import { TRANSITION_OPTIONS } from "@/api/template-editor"
import type { TransitionConfig, TransitionType } from "../types"
import { DEFAULT_TRANSITION } from "../types"
@@ -18,7 +18,7 @@ import type {
CreateEditPlanClipRequest,
UpdateEditPlanClipRequest,
ClipReorderItem,
} from "@/api/templateEditor"
} from "@/api/template-editor"
import {
getEditPlanClips,
createEditPlanClip,
@@ -27,7 +27,7 @@ import {
reorderEditPlanClips,
batchDeleteEditPlanClips,
createClipsFromAssets,
} from "@/api/templateEditor"
} from "@/api/template-editor"
import { useUndoRedo } from "./useUndoRedo"
const QUERY_KEY = "editPlanClips"
View File
View File
+5 -5
View File
@@ -30,15 +30,15 @@ import {
getGenerationTaskResults,
getGenerationStatus,
getEditPlan,
} from "@/api/templateEditor"
import type { GeneratedVideo, EditPlanConfig, TitleConfig } from "@/api/templateEditor"
} from "@/api/template-editor"
import type { GeneratedVideo, EditPlanConfig, TitleConfig } from "@/api/template-editor"
import type { CoverConfig } from "../editing-planner/types"
import { getEditingTemplates } from "@/api/editingPlanner"
import { getEditingTemplates } from "@/api/editing-planner"
import { getTitles } from "@/api/titles"
import { fetchPresetVoices } from "@/api/voices"
import type { PresetVoiceItem } from "@/api/voices"
import { formatDuration } from "@/api/voiceClone"
import type { VoiceClone } from "@/api/voiceClone"
import { formatDuration } from "@/api/voice-clone"
import type { VoiceClone } from "@/api/voice-clone"
import CloneModal from "@/components/voice/CloneModal"
import { synthesizeSpeech, getTTSJobStatus, saveTtsToLibrary } from "@/api/tts"
import { getTags, createTag } from "@/api/tags"
View File
View File
View File
@@ -40,7 +40,7 @@ import {
MODE_COLORS,
type EditingTemplate,
type TemplateMode,
} from "@/api/editingPlanner"
} from "@/api/editing-planner"
import "./MyTemplates.css"
const { Title, Text } = Typography
+2 -2
View File
@@ -19,8 +19,8 @@ import { Button, Modal, Input, Tooltip } from "@/components/ui"
import type { ButtonProps } from "antd"
import PageHead from "@/components/layout/PageHead"
import { useCloneProgress } from "@/hooks/useCloneProgress"
import { deleteVoiceClone, updateVoiceClone, formatDuration } from "@/api/voiceClone"
import type { VoiceClone, VoiceCloneStatus } from "@/api/voiceClone"
import { deleteVoiceClone, updateVoiceClone, formatDuration } from "@/api/voice-clone"
import type { VoiceClone, VoiceCloneStatus } from "@/api/voice-clone"
import "./my-voices.css"
/* ============================================================
View File
View File
View File
View File
@@ -25,7 +25,7 @@ import {
updateVoiceClone,
formatDuration,
type VoiceClone as VoiceCloneType,
} from "@/api/voiceClone"
} from "@/api/voice-clone"
import "./voice-clone.css"
/* ── 状态配置 ─────────────────────────────────────────── */
+1 -1
View File
@@ -34,7 +34,7 @@ import {
retryVoiceClone,
toVoiceClone,
type VoiceClone,
} from "@/api/voiceClone"
} from "@/api/voice-clone"
import { synthesizeSpeech, getTTSJobStatus, saveTtsToLibrary } from "@/api/tts"
import {
getAssetsByKind,
View File
@@ -23,7 +23,7 @@ import {
copyEditPlan,
getMediaAssets,
getMediaAsset,
} from "@/api/templateEditor"
} from "@/api/template-editor"
const mockGet = vi.fn()
const mockPost = vi.fn()
@@ -7,7 +7,7 @@ import {
deleteEditingTemplate,
getTemplateCategories,
generateFromTemplate,
} from "@/api/editingPlanner"
} from "@/api/editing-planner"
const mockGet = vi.fn()
const mockPost = vi.fn()
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"
import { toVoiceClone, formatDuration } from "@/api/voiceClone"
import type { VoiceCloneProfile } from "@/api/voiceClone"
import { toVoiceClone, formatDuration } from "@/api/voice-clone"
import type { VoiceCloneProfile } from "@/api/voice-clone"
describe("formatDuration", () => {
it("should format seconds correctly", () => {
@@ -8,7 +8,7 @@ import {
updateVoiceClone,
getVoiceCloneStatus,
retryVoiceClone,
} from "@/api/voiceClone"
} from "@/api/voice-clone"
const mockGet = vi.fn()
const mockPost = vi.fn()
@@ -1,8 +1,8 @@
import React from "react"
import { describe, it, expect, vi } from "vitest"
import { render, screen } from "@testing-library/react"
import AssetSelector from "@/components/AssetSelector/AssetSelector"
import type { MediaAsset } from "@/api/templateEditor"
import AssetSelector from "@/components/asset-selector/AssetSelector"
import type { MediaAsset } from "@/api/template-editor"
vi.mock("@/components/ui", () => ({
Input: ({ placeholder }: any) => <input placeholder={placeholder} />,
@@ -18,7 +18,7 @@ vi.mock("@/components/ui", () => ({
Button: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
}))
vi.mock("@/components/AssetSelector/AssetSelector.css", () => ({}))
vi.mock("@/components/asset-selector/AssetSelector.css", () => ({}))
const mockAssets: MediaAsset[] = [
{
@@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"
import { render } from "@testing-library/react"
import CloneModal from "@/components/voice/CloneModal"
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
createVoiceClone: vi.fn(),
toVoiceClone: vi.fn(),
}))
View File
@@ -4,7 +4,7 @@ import { useCloneProgress } from "@/hooks/useCloneProgress"
// mock API
const mockGetVoiceClones = vi.fn()
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
getVoiceClones: (...args: unknown[]) => mockGetVoiceClones(...args),
VoiceCloneStatus: { READY: "ready" },
}))
View File
@@ -137,7 +137,7 @@ vi.mock("@/components/ui", () => ({
}))
// === API mocks ===
vi.mock("@/api/editingPlanner", () => ({
vi.mock("@/api/editing-planner", () => ({
getEditingTemplates: vi.fn().mockResolvedValue({ items: [], total: 0 }),
getEditingTemplate: vi.fn().mockResolvedValue({}),
createEditingTemplate: vi.fn().mockResolvedValue({}),
@@ -146,7 +146,7 @@ vi.mock("@/api/editingPlanner", () => ({
MODE_LABELS: { pip: "画中画", intro_outro: "片头片尾", watermark: "水印" },
}))
vi.mock("@/api/templateEditor", () => ({
vi.mock("@/api/template-editor", () => ({
getMediaAssets: vi.fn().mockResolvedValue({ items: [] }),
getEditPlanGenerations: vi.fn().mockResolvedValue({ items: [] }),
generateCover: vi.fn().mockResolvedValue({}),
@@ -204,7 +204,7 @@ vi.mock("@/api/voices", () => ({
fetchPresetVoices: vi.fn().mockResolvedValue({ items: [] }),
}))
vi.mock("@/api/editingPlanner", () => ({
vi.mock("@/api/editing-planner", () => ({
getEditingTemplates: vi.fn().mockResolvedValue({ items: [], total: 0 }),
MODE_LABELS: { pip: "画中画" },
}))
@@ -213,7 +213,7 @@ vi.mock("@/api/titles", () => ({
getTitles: vi.fn().mockResolvedValue({ items: [] }),
}))
vi.mock("@/api/templateEditor", () => ({
vi.mock("@/api/template-editor", () => ({
generateEditPlan: vi.fn().mockResolvedValue({
plan_id: "test-plan",
generation_task_id: "test-task",
@@ -234,7 +234,7 @@ vi.mock("@/api/templateEditor", () => ({
getGenerationTaskResults: vi.fn().mockResolvedValue({ items: [] }),
}))
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
formatDuration: vi.fn((s: number) => `${s}s`),
}))
+1 -1
View File
@@ -40,7 +40,7 @@ vi.mock("@ant-design/icons", () => ({
PlusOutlined: () => <span>PlusOutlined</span>,
}))
vi.mock("@/api/editingPlanner", () => ({
vi.mock("@/api/editing-planner", () => ({
getEditingTemplates: vi.fn(),
getTemplateCategories: vi.fn().mockResolvedValue([]),
deleteEditingTemplate: vi.fn(),
+1 -1
View File
@@ -73,7 +73,7 @@ vi.mock("antd", () => ({
RadioGroup: ({ children }: any) => <div>{children}</div>,
}))
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
getVoiceCloneList: vi.fn().mockResolvedValue({ items: [], total: 0 }),
deleteVoiceClone: vi.fn().mockResolvedValue({ success: true }),
createVoiceClone: vi.fn().mockResolvedValue({ success: true }),
+1 -1
View File
@@ -73,7 +73,7 @@ vi.mock("antd", () => ({
RadioGroup: ({ children }: any) => <div>{children}</div>,
}))
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
getVoiceCloneList: vi.fn().mockResolvedValue({ items: [], total: 0 }),
createVoiceClone: vi.fn().mockResolvedValue({ success: true, id: "1" }),
deleteVoiceClone: vi.fn().mockResolvedValue({ success: true }),
@@ -109,7 +109,7 @@ vi.mock("@ant-design/icons", () => ({
vi.mock("@/store/authStore", () => ({
useAuthStore: (sel: any) => sel({ user: { id: "1" }, isAuthenticated: true }),
}))
vi.mock("@/api/voiceClone", () => ({
vi.mock("@/api/voice-clone", () => ({
createVoiceClone: vi.fn().mockResolvedValue({ success: true }),
deleteVoiceClone: vi.fn().mockResolvedValue({ success: true }),
retryVoiceClone: vi.fn().mockResolvedValue({ success: true }),
@@ -0,0 +1,79 @@
import { describe, expect, it, vi, beforeEach } from "vitest"
import { render, screen } from "@testing-library/react"
import { MemoryRouter } from "react-router-dom"
import WechatCallback from "@/pages/auth/WechatCallback"
vi.mock("react-router-dom", async () => {
const actual = await vi.importActual("react-router-dom")
return {
...actual,
useNavigate: () => vi.fn(),
useSearchParams: () => [new URLSearchParams({ code: "test_code", state: "test_state" })],
}
})
vi.mock("@/api/auth", () => ({
wechatCallback: vi.fn(() => new Promise(() => {})), // pending promise,保持loading
getCurrentUser: vi.fn(),
normalizeUser: (u: unknown) => u,
}))
vi.mock("@/store/authStore", () => ({
useAuthStore: () => ({
setAuth: vi.fn(),
}),
}))
vi.mock("@/components/auth/BindContactModal", () => ({
default: ({ open }: { open: boolean }) => (
<div data-testid="bind-contact-modal" style={{ display: open ? "block" : "none" }}>
BindContactModal
</div>
),
}))
vi.mock("antd", async () => {
const actual = await vi.importActual("antd")
return {
...actual,
message: {
success: vi.fn(),
error: vi.fn(),
},
}
})
describe("WechatCallback Page", () => {
beforeEach(() => {
// mock localStorage,设置wechat_state匹配,让校验通过
const store: Record<string, string> = {
wechat_state: "test_state",
}
vi.spyOn(Storage.prototype, "getItem").mockImplementation((key) => store[key] || null)
vi.spyOn(Storage.prototype, "setItem").mockImplementation((key, val) => {
store[key] = val
})
vi.spyOn(Storage.prototype, "removeItem").mockImplementation((key) => {
delete store[key]
})
})
it("should render without crashing", () => {
const { container } = render(
<MemoryRouter>
<WechatCallback />
</MemoryRouter>,
)
expect(container).toBeTruthy()
})
it("should show loading state while processing", () => {
render(
<MemoryRouter>
<WechatCallback />
</MemoryRouter>,
)
// wechatCallback 返回 pending promise,所以应该显示 loading
expect(screen.getByText("正在登录...")).toBeTruthy()
})
})
@@ -32,7 +32,7 @@ vi.mock("antd", () => ({
},
}))
vi.mock("@/api/templateEditor", () => ({
vi.mock("@/api/template-editor", () => ({
getEditPlanClips: vi.fn().mockResolvedValue({ items: [], total: 0 }),
createEditPlanClip: vi.fn().mockResolvedValue({}),
updateEditPlanClip: vi.fn().mockResolvedValue({}),
View File
+17 -37
View File
@@ -1,42 +1,22 @@
import os
from typing import Optional
"""Worker 服务配置(向后兼容层)。
from pydantic_settings import BaseSettings, SettingsConfigDict
统一配置已迁移到 packages.config.worker_settings。
新代码请使用:
from packages.config import WorkerSettings, get_worker_settings
"""
class WorkerSettings(BaseSettings):
worker_name: str = "xiaoxia-saas-worker"
broker_url: str = "redis://redis:6379/0"
result_backend: str = "redis://redis:6379/1"
worker_concurrency: int = 4
worker_max_tasks_per_child: int = 1000
database_url: str = "postgresql+psycopg://postgres:postgres@postgres:5432/xiaoxia_saas"
database_pool_size: int = 20
database_max_overflow: int = 40
database_pool_timeout: int = 30
database_pool_recycle: int = 3600
environment: str = "development"
auto_create_schema: bool = False
redis_url: str = "redis://redis:6379/0"
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
_settings: Optional[WorkerSettings] = None
from packages.config import WorkerSettings, get_worker_settings, reload_settings_cache
def get_settings() -> WorkerSettings:
global _settings
if _settings is None:
env = os.getenv("APP_ENV", "development")
env_file = f".env.{env}" if env != "development" else ".env"
if os.path.exists(env_file):
_settings = WorkerSettings(_env_file=env_file)
else:
_settings = WorkerSettings()
return _settings
"""获取 Worker 配置单例(向后兼容)。"""
return get_worker_settings()
def reload_settings() -> WorkerSettings:
"""重新加载配置(测试用)。"""
reload_settings_cache()
return get_worker_settings()
__all__ = ["WorkerSettings", "get_settings", "reload_settings"]
+19 -377
View File
@@ -1,385 +1,27 @@
"""AI 相关异步任务 — 智能推荐 & 封面生成.
提供两个 Celery 任务:
- ai_recommend_clips: 分析素材并推荐片段编排方案
- generate_cover: 从视频中选帧或生成封面图
当前为 stub 实现(返回模拟数据),后续接入真实 AI 服务时
只需替换 _call_ai_recommend_service / _call_ai_cover_service 内部逻辑。
核心业务逻辑已迁移到 packages.shared.ai_service,
本模块仅保留 Worker 侧的 Celery 任务包装和向后兼容的直接导入。
"""
from __future__ import annotations
import json
import logging
import random
import time
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List
from packages.domain.config_schemas import DEFAULT_EDIT_PLAN_CONFIG
from packages.shared.ai_client import get_doubao_client
from packages.shared.ai_service import (
_call_ai_cover_service,
_call_ai_recommend_service,
_fallback_recommend_clips,
_parse_recommend_response,
run_ai_recommend,
run_generate_cover,
)
logger = logging.getLogger(__name__)
# ── AI 推荐片段方案 ──────────────────────────────────────────────────────────
def _fallback_recommend_clips(
plan_id: str,
template_id: str,
asset_ids: List[str],
editing_mode: str,
target_duration: float,
) -> Dict[str, Any]:
"""本地降级推荐方案(原 stub 逻辑).
当豆包 API 不可用或调用失败时使用,基于模板规则生成模拟推荐数据。
"""
# 模拟 AI 分析耗时
time.sleep(0.5)
# 根据素材数量生成推荐片段
clips: List[Dict[str, Any]] = []
order = 0
# 开场片段
clips.append(
{
"clip_type": "intro",
"order": order,
"text_content": "精彩看点",
"duration": 3.0,
"transition_effect": "fade",
"asset_id": asset_ids[0] if asset_ids else "",
"start_time": 0.0,
"config": {},
}
)
order += 1
# 为每个素材生成展示片段
per_clip_duration = max(2.0, (target_duration - 6.0) / max(len(asset_ids), 1))
for i, asset_id in enumerate(asset_ids):
clips.append(
{
"clip_type": "showcase",
"order": order,
"text_content": f"展示片段 {i + 1}",
"duration": round(per_clip_duration, 1),
"transition_effect": "cut",
"asset_id": asset_id,
"start_time": 0.0,
"config": {},
}
)
order += 1
# 结尾 CTA
clips.append(
{
"clip_type": "outro",
"order": order,
"text_content": "感谢观看",
"duration": 3.0,
"transition_effect": "fade",
"asset_id": "",
"start_time": 0.0,
"config": {},
}
)
order += 1
# 生成推荐 config
config = DEFAULT_EDIT_PLAN_CONFIG.copy()
config["title"]["text"] = f"精选视频 — {len(asset_ids)} 个片段"
config["title"]["ai_auto"] = True
return {
"clips": clips,
"config": config,
"total_duration": round(sum(c["duration"] for c in clips), 1),
"confidence": round(random.uniform(0.75, 0.95), 2),
}
def _parse_recommend_response(
content: str,
asset_ids: List[str],
target_duration: float,
) -> Optional[Dict[str, Any]]:
"""解析豆包返回的推荐方案.
期望返回结构:
{
"clips": [
{"clip_type": "intro/showcase/outro", "order": 0,
"text_content": "...", "duration": 3.0,
"transition_effect": "fade/cut", "asset_id": "...",
"start_time": 0.0, "config": {}}
],
"title": "视频标题",
"confidence": 0.85
}
"""
if not content:
return None
try:
cleaned = content.strip()
if cleaned.startswith("```"):
cleaned = cleaned.strip("`")
if cleaned.lower().startswith("json"):
cleaned = cleaned[4:]
cleaned = cleaned.strip()
data = json.loads(cleaned)
if not isinstance(data, dict):
return None
clips_data = data.get("clips", [])
if not isinstance(clips_data, list) or len(clips_data) == 0:
return None
clips: List[Dict[str, Any]] = []
for i, clip in enumerate(clips_data):
if not isinstance(clip, dict):
continue
asset_id = str(clip.get("asset_id", ""))
# 校验 asset_id 是否在输入列表中
if asset_id and asset_id not in asset_ids:
asset_id = ""
clips.append({
"clip_type": clip.get("clip_type", "showcase"),
"order": clip.get("order", len(clips)),
"text_content": str(clip.get("text_content", "")),
"duration": max(1.0, min(30.0, float(clip.get("duration", 3.0)))),
"transition_effect": clip.get("transition_effect", "cut"),
"asset_id": asset_id,
"start_time": max(0.0, float(clip.get("start_time", 0.0))),
"config": clip.get("config", {}) or {},
})
if not clips:
return None
# 按 order 排序
clips.sort(key=lambda c: c["order"])
# 重新编号 order 保证连续
for i, clip in enumerate(clips):
clip["order"] = i
config = DEFAULT_EDIT_PLAN_CONFIG.copy()
title = data.get("title", "")
if title:
config["title"]["text"] = str(title)
config["title"]["ai_auto"] = True
confidence = float(data.get("confidence", 0.7))
confidence = max(0.0, min(1.0, confidence))
total_duration = round(sum(c["duration"] for c in clips), 1)
return {
"clips": clips,
"config": config,
"total_duration": total_duration,
"confidence": round(confidence, 2),
}
except (json.JSONDecodeError, ValueError, TypeError, KeyError):
return None
def _call_ai_recommend_service(
plan_id: str,
template_id: str,
asset_ids: List[str],
editing_mode: str,
target_duration: float,
) -> Dict[str, Any]:
"""调用 AI 推荐服务生成片段编排方案.
优先使用豆包大模型生成,失败或未配置时降级为本地规则生成。
"""
client = get_doubao_client()
if not client.is_available:
logger.info("豆包API未配置,使用本地降级生成AI推荐方案")
return _fallback_recommend_clips(plan_id, template_id, asset_ids, editing_mode, target_duration)
# 构建 prompt
system_prompt = (
"你是一个专业的视频剪辑导演助手。"
"根据提供的素材列表和目标时长,设计一个完整的视频片段编排方案。\n"
"要求:\n"
"1. 片段类型分为三类:intro(开场)、showcase(展示)、outro(结尾)\n"
"2. 每个片段包含:clip_type、order、text_content(字幕/标题文字)、"
"duration(时长秒)、transition_effect(转场效果:fade/cut/dissolve)、"
"asset_id(使用的素材ID)、start_time(素材起始时间秒)\n"
"3. 总时长接近 target_duration,每个素材至少用一次\n"
"4. 转场效果合理分配,不要全用cut\n"
"5. 返回纯JSON,不要其他文字\n"
"返回格式:{\"clips\": [...], \"title\": \"视频标题\", \"confidence\": 0.85}"
)
assets_desc = "\n".join([f" - 素材ID: {aid}" for i, aid in enumerate(asset_ids[:30])])
user_prompt = (
f"剪辑计划ID: {plan_id}\n"
f"模板ID: {template_id}\n"
f"剪辑模式: {editing_mode}\n"
f"目标时长: {target_duration}秒\n"
f"素材列表(共{len(asset_ids)}个):\n{assets_desc}\n\n"
f"请设计完整的片段编排方案:"
)
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
result = client.chat_completion(
messages=messages,
temperature=0.7,
max_tokens=2048,
)
if result:
parsed = _parse_recommend_response(result, asset_ids, target_duration)
if parsed and len(parsed["clips"]) >= 2:
logger.info(
"豆包AI推荐生成成功: plan_id=%s clips=%d duration=%.1f confidence=%.2f",
plan_id,
len(parsed["clips"]),
parsed["total_duration"],
parsed["confidence"],
)
return parsed
logger.warning("豆包AI推荐返回解析失败,降级到本地方案: %s", result[:100])
# 降级
return _fallback_recommend_clips(plan_id, template_id, asset_ids, editing_mode, target_duration)
# ── AI 封面生成 ──────────────────────────────────────────────────────────────
def _call_ai_cover_service(
plan_id: str,
asset_ids: List[str],
cover_type: str,
frame_time: float | None = None,
) -> Dict[str, Any]:
"""调用 AI 封面生成服务(stub)
TODO: 接入真实 AI 服务,从视频中选帧或生成封面。
当前返回模拟封面数据。
"""
# 模拟 AI 处理耗时
time.sleep(0.3)
if cover_type == "upload":
return {
"type": "upload",
"image_url": "",
"message": "请上传封面图片",
}
if cover_type == "manual" and frame_time is not None:
return {
"type": "manual",
"image_url": f"/api/v1/assets/placeholder/cover?time={frame_time}",
"frame_time": frame_time,
}
# ai_frame / ai_regenerate
return {
"type": "ai_frame",
"image_url": f"/api/v1/assets/placeholder/cover?plan={plan_id}",
"frame_time": round(random.uniform(1.0, 10.0), 1),
"confidence": round(random.uniform(0.80, 0.98), 2),
}
# ── 任务入口(供 Celery 调度或路由直接调用) ─────────────────────────────────
def run_ai_recommend(
plan_id: str,
template_id: str,
asset_ids: List[str],
editing_mode: str = "one_take",
target_duration: float = 30.0,
) -> Dict[str, Any]:
"""执行 AI 推荐片段方案
Args:
plan_id: 剪辑计划 ID
template_id: 模板 ID
asset_ids: 素材 ID 列表
editing_mode: 剪辑模式 (one_take / pip / voice_over / voice_pip)
target_duration: 目标时长(秒)
Returns:
推荐方案 dict,包含 clips / config / total_duration / confidence
"""
logger.info(
"AI 推荐片段方案: plan_id=%s template_id=%s assets=%d mode=%s duration=%.1f",
plan_id,
template_id,
len(asset_ids),
editing_mode,
target_duration,
)
result = _call_ai_recommend_service(
plan_id=plan_id,
template_id=template_id,
asset_ids=asset_ids,
editing_mode=editing_mode,
target_duration=target_duration,
)
logger.info(
"AI 推荐完成: plan_id=%s clips=%d duration=%.1f confidence=%.2f",
plan_id,
len(result["clips"]),
result["total_duration"],
result["confidence"],
)
return result
def run_generate_cover(
plan_id: str,
asset_ids: List[str],
cover_type: str = "ai_frame",
frame_time: float | None = None,
) -> Dict[str, Any]:
"""执行 AI 封面生成
Args:
plan_id: 剪辑计划 ID
asset_ids: 素材 ID 列表(用于确定视频来源)
cover_type: 封面类型 (ai_frame / manual / upload / ai_regenerate)
frame_time: 手动选帧时间点(仅 manual 模式使用)
Returns:
封面数据 dict,包含 type / image_url / frame_time
"""
logger.info(
"AI 封面生成: plan_id=%s type=%s assets=%d",
plan_id,
cover_type,
len(asset_ids),
)
result = _call_ai_cover_service(
plan_id=plan_id,
asset_ids=asset_ids,
cover_type=cover_type,
frame_time=frame_time,
)
logger.info(
"AI 封面生成完成: plan_id=%s type=%s url=%s",
plan_id,
result.get("type"),
result.get("image_url", "")[:60],
)
return result
__all__ = [
"run_ai_recommend",
"run_generate_cover",
"_call_ai_recommend_service",
"_call_ai_cover_service",
"_fallback_recommend_clips",
"_parse_recommend_response",
]
@@ -24,6 +24,8 @@ from typing import Any
from worker_app.celery_app import celery_app
from worker_app.db import SessionLocal
from packages.domain.bgm_utils import merge_bgm_config
OUTPUT_WIDTH = 1280
OUTPUT_HEIGHT = 720
OUTPUT_FPS = 25.0
@@ -1111,6 +1113,7 @@ def _load_task_info(task_id: str) -> dict | None:
"user_id": getattr(gen_task, "created_by_user_id", "") or "",
"video_title": getattr(gen_task, "video_title", "") or "",
"resolution": getattr(gen_task, "resolution", "") or "",
"bgm_config": dict(getattr(gen_task, "bgm_config", {}) or {}),
}
finally:
session.close()
@@ -1170,6 +1173,7 @@ def _render_video(
temp_path: Path,
output_name: str,
resolution: str = "",
bgm_config: dict | None = None,
) -> tuple[Path, float]:
"""渲染视频(含配音混音)。
@@ -1201,6 +1205,20 @@ def _render_video(
list(template_config.keys()),
)
# 用户自定义 BGM 覆盖模板 BGM(用户指定优先级最高)
if bgm_config:
plan_cfg = virtual_plan.config or {}
template_bgm = plan_cfg.get("bgm", {}) or {}
merged_bgm = merge_bgm_config(template_bgm, bgm_config)
plan_cfg["bgm"] = merged_bgm
virtual_plan.config = plan_cfg
logger.info(
"[task_id=%s] [渲染] 用户自定义BGM已合并: enabled=%s source=%s",
task_id,
merged_bgm.get("enabled", False),
merged_bgm.get("source", ""),
)
# 确保输出分辨率配置存在
# 优先级:用户指定 > 模板配置 > 默认 1280x720
plan_cfg = virtual_plan.config or {}
@@ -1453,6 +1471,7 @@ def generate_video(self, task_id: str) -> dict:
temp_path=temp_path,
output_name=output_name,
resolution=task_info.get("resolution", ""),
bgm_config=task_info.get("bgm_config", {}),
)
if gen_task:
Regular → Executable
+83 -2
View File
@@ -445,5 +445,86 @@ def list_all_assets() -> list[Asset]:
---
**最后更新**: 2026-06-15
**版本**: v1.0
## 8. 前端规范(React + TypeScript)
### 8.1 文件命名规范
| 类型 | 风格 | 示例 | 说明 |
|------|------|------|------|
| **目录名** | kebab-case | `editing-planner/`, `asset-selector/` | 全小写,多单词用短横线连接 |
| **组件文件** | PascalCase | `AssetSelector.tsx`, `MediaPanel.tsx` | 与组件导出名一致 |
| **页面组件** | PascalCase | `EditingPlanner.tsx`, `MyTemplates.tsx` | 放在 kebab-case 目录中 |
| **API 文件** | kebab-case | `template-editor.ts`, `voice-clone.ts` | 与 RESTful 资源路径风格一致 |
| **Hooks** | camelCase (use前缀) | `useAuth.ts`, `useCloneProgress.ts` | React 官方惯例 |
| **Store** | kebab-case | `auth-store.ts`, `ui-store.ts` | |
| **工具函数/helpers** | kebab-case | `format-duration.ts`, `date-utils.ts` | |
| **类型定义** | kebab-case | `types.ts`, `subtitle-types.ts` | 目录内类型定义可用 `types.ts` |
| **常量** | UPPER_SNAKE_CASE | `MAX_UPLOAD_SIZE`, `API_BASE_URL` | |
| **测试文件** | 与被测文件同名 + `.test` | `auth.test.ts`, `AssetSelector.test.tsx` | 放在 `test/` 目录下,保持相同相对路径 |
### 8.2 组件命名
- 组件名使用 **PascalCase**,与文件名一致
- 默认导出组件名与文件名相同
- 高阶组件/包装器用 `with` 前缀:`withAuth(Component)`
- 渲染属性组件用 `Render` 后缀:`UserRender`
```tsx
// ✅ 正确
// 文件: AssetSelector.tsx
const AssetSelector: React.FC<AssetSelectorProps> = ({ assets }) => { ... };
export default AssetSelector;
// ❌ 错误
// 文件: asset-selector.tsx
const assetSelector = () => { ... };
```
### 8.3 变量与函数命名
- **变量/函数**:camelCase
- **布尔变量**:用 `is/has/should/can` 前缀
- **事件处理函数**:用 `handle` 前缀 + 事件名
- **事件 handler prop**:用 `on` 前缀
```tsx
// ✅ 正确
const isLoading = true;
const hasError = false;
const handleSubmit = () => { ... };
<Button onClick={onClick} />
```
### 8.4 导入路径
- 使用 `@/` 别名引用 `src/` 下的文件
- 同一目录内用相对路径 `./`
- 导入顺序:React → 第三方库 → @/内部模块 → 相对路径 → 样式
```tsx
import React, { useState } from 'react';
import { Button, Modal } from 'antd';
import { useAuth } from '@/hooks/useAuth';
import { Asset } from '@/api/asset-selector';
import { MediaPanel } from './MediaPanel';
import './AssetSelector.css';
```
### 8.5 CSS/样式命名
- CSS Modules / CSS 类名:kebab-case
- styled-components:PascalCase(与组件一致)
- Tailwind 工具类遵循官方惯例
```css
/* ✅ 正确 */
.asset-selector { ... }
.asset-item { ... }
.asset-item--active { ... }
```
---
**最后更新**: 2026-07-23
**版本**: v1.1
-14
View File
@@ -1,14 +0,0 @@
-- Deprecated schema snapshot.
--
-- Runtime schema creation is currently owned by SQLAlchemy models in:
-- packages/adapters/sqlalchemy_impl/models.py
--
-- Do not apply this file to staging or production. It is retained only for
-- historical reference while the project migrates toward a proper Alembic flow.
-- Applying it would create columns such as assets.library_id/storage_key/mime_type
-- that conflict with the current runtime table shape.
DO $$
BEGIN
RAISE EXCEPTION 'init-tables.sql is deprecated. Use SQLAlchemy runtime schema initialization / future Alembic migrations instead.';
END $$;
+7
View File
@@ -0,0 +1,7 @@
-- 一键生成支持自定义BGM
-- 为 generation_tasks 表添加 bgm_config 字段,用于存储用户自定义BGM配置
-- 创建时间: 2026-07-23
ALTER TABLE generation_tasks ADD COLUMN IF NOT EXISTS bgm_config JSON NOT NULL DEFAULT '{}'::json;
COMMENT ON COLUMN generation_tasks.bgm_config IS '自定义BGM配置,覆盖模板BGM设置';
+3 -1
View File
@@ -10,6 +10,8 @@ from typing import Optional
import redis
from redis import Redis
from packages.domain.auth.session_store import SessionStorePort
class RedisConfig:
"""Redis 配置"""
@@ -50,7 +52,7 @@ class NoopSessionStore:
return False
class SessionStore:
class SessionStore(SessionStorePort):
"""Session 存储服务"""
def __init__(self, redis_client: Optional[Redis] = None, config: Optional[RedisConfig] = None):
+3 -15
View File
@@ -4,11 +4,12 @@
"""
import smtplib
from dataclasses import dataclass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import List, Optional
from packages.domain.auth.email_service import EmailConfig, EmailServicePort
class NoopEmailService:
def send_verification_email(self, **kwargs):
@@ -18,20 +19,7 @@ class NoopEmailService:
return False, "Email delivery is disabled"
@dataclass
class EmailConfig:
"""邮件配置"""
smtp_host: str = "smtp.gmail.com"
smtp_port: int = 587
smtp_user: str = ""
smtp_password: str = ""
from_email: str = ""
from_name: str = "小虾 SaaS"
use_tls: bool = True
class EmailService:
class EmailService(EmailServicePort):
"""邮件服务类"""
def __init__(self, config: Optional[EmailConfig] = None):
@@ -35,6 +35,7 @@ def _to_domain(model: GenerationTaskModel) -> GenerationTask:
batch_id=model.batch_id or "",
video_title=getattr(model, "video_title", "") or "",
resolution=getattr(model, "resolution", "") or "",
bgm_config=dict(getattr(model, "bgm_config", {}) or {}),
logs=model.logs or "[]",
created_at=model.created_at,
updated_at=model.updated_at,
@@ -72,6 +73,7 @@ class SQLAlchemyGenerationTaskRepository:
batch_id=task.batch_id or "",
video_title=task.video_title or "",
resolution=task.resolution or "",
bgm_config=task.bgm_config or {},
logs=task.logs,
created_at=task.created_at,
updated_at=task.updated_at,
@@ -234,6 +236,8 @@ class SQLAlchemyGenerationTaskRepository:
model.video_title = task.video_title or ""
if hasattr(model, "resolution"):
model.resolution = task.resolution or ""
if hasattr(model, "bgm_config"):
model.bgm_config = task.bgm_config or {}
model.logs = task.logs
self.session.commit()
return task
@@ -292,6 +292,7 @@ class GenerationTaskModel(Base):
batch_id = Column(String(36), nullable=False, default="", index=True)
video_title = Column(String(255), nullable=False, default="")
resolution = Column(String(20), nullable=False, default="")
bgm_config = Column(JSON, nullable=False, default=dict)
extra_meta = Column("metadata", JSON, nullable=False, default=dict)
logs = Column(Text, nullable=False, default="[]", server_default="[]")
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(timezone.utc))
+3 -1
View File
@@ -6,6 +6,8 @@ from typing import Any, Dict, Optional
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
from packages.domain.auth.jwt_service import JWTServicePort
class JWTConfig:
"""JWT 配置"""
@@ -57,7 +59,7 @@ class TokenType:
REFRESH = "refresh"
class JWTService:
class JWTService(JWTServicePort):
"""JWT 服务类"""
def __init__(self, config: JWTConfig = None):
+5 -3
View File
@@ -3,12 +3,14 @@
使用 bcrypt 安全存储密码
"""
from typing import Optional
from typing import Optional, Tuple
import bcrypt
from packages.domain.auth.password_hasher import PasswordHasherPort, PasswordValidatorPort
class PasswordHasher:
class PasswordHasher(PasswordHasherPort):
"""密码哈希服务"""
def __init__(self, rounds: int = 12):
@@ -98,7 +100,7 @@ class PasswordHasher:
return False
class PasswordValidator:
class PasswordValidator(PasswordValidatorPort):
"""密码强度验证器"""
def __init__(
+2
View File
@@ -23,6 +23,7 @@ class CreateGenerationTaskCommand:
batch_id: str = ""
video_title: str = ""
resolution: str = ""
bgm_config: dict = field(default_factory=dict)
auto_retry_enabled: bool = False
auto_retry_max: int = 0
@@ -52,6 +53,7 @@ class CreateGenerationTaskUseCase:
batch_id=command.batch_id,
video_title=command.video_title,
resolution=command.resolution,
bgm_config=command.bgm_config,
auto_retry_enabled=command.auto_retry_enabled,
auto_retry_max=command.auto_retry_max,
)
+34
View File
@@ -0,0 +1,34 @@
"""统一配置入口 — 整个项目的配置都从这里获取。
所有服务共享同一个配置包,消除重复定义和不一致。
用法:
from packages.config import get_api_settings, get_worker_settings, get_shared_settings
from packages.config import APISettings, WorkerSettings, SharedSettings
架构:
packages/config/
├── base.py # SharedSettings 基类 + 统一单例管理
├── api_settings.py # APISettings(API 特有配置)
└── worker_settings.py # WorkerSettings(Worker 特有配置)
"""
from packages.config.api_settings import APISettings, get_api_settings
from packages.config.base import (
SharedSettings,
get_cached_settings,
get_shared_settings,
reload_settings_cache,
)
from packages.config.worker_settings import WorkerSettings, get_worker_settings
__all__ = [
"SharedSettings",
"APISettings",
"WorkerSettings",
"get_shared_settings",
"get_api_settings",
"get_worker_settings",
"get_cached_settings",
"reload_settings_cache",
]
+286
View File
@@ -0,0 +1,286 @@
"""API 服务配置 — 继承 SharedSettings,只追加 API 特有字段。
通用配置统一在 packages/config/base.py 的 SharedSettings 中定义,这里不重复。
历史上 API 端使用 UPPER_CASE 命名风格的字段,目前通过 property 别名向后兼容。
新代码统一使用 snake_case(继承自 SharedSettings)。
"""
import os
from typing import Optional
from pydantic import AliasChoices, Field, field_validator
from pydantic_settings import SettingsConfigDict
from packages.config.base import SharedSettings, get_cached_settings
class APISettings(SharedSettings):
"""API 服务专用配置。
通用配置继承自 SharedSettings,这里只定义 API 独有字段。
"""
# ── 应用基本信息 ────────────────────────────────────────────────────
app_name: str = "xiaoxia-saas"
app_version: str = "0.1.61"
# 应用基础 URL,用于生成认证邮件中的链接
app_base_url: str = "http://localhost:3000"
# Container bind address; external expose is controlled by Docker/Nginx.
api_host: str = "0.0.0.0" # nosec: B104
api_port: int = 8000
# ── 数据库特有 ──────────────────────────────────────────────────────
use_in_memory_db: bool = False
# ── Redis 特有 ──────────────────────────────────────────────────────
enable_redis_sessions: bool = False
# ── JWT ────────────────────────────────────────────────────────────
# JWT secret key - MUST be set via environment variable, no default allowed
jwt_secret_key: Optional[str] = None
# JWT 算法与过期时间
jwt_algorithm: str = "HS256"
jwt_access_token_expire_minutes: int = 30
jwt_refresh_token_expire_days: int = 30
@field_validator("jwt_secret_key", mode="before")
@classmethod
def validate_jwt_secret_key(cls, v):
if v is None or v == "":
raise ValueError(
"JWT_SECRET_KEY must be set via environment variable. " "Do not use default value in production!"
)
# Block known insecure default values
insecure_defaults = [
"your-secret-key-change-in-production",
"your-secret-key",
"secret",
"changeme",
"password",
]
if v.lower() in [d.lower() for d in insecure_defaults]:
raise ValueError(
f"JWT_SECRET_KEY '{v}' is insecure. " "Please set a strong random secret via environment variable."
)
return v
# ── 邮件 ────────────────────────────────────────────────────────────
enable_email_delivery: bool = False
smtp_host: str = "smtp.gmail.com"
smtp_port: int = 587
smtp_user: str = ""
smtp_password: str = ""
smtp_from_email: str = ""
smtp_from_name: str = "小虾 SaaS"
smtp_use_tls: bool = True
# ── OSS 特有校验 ────────────────────────────────────────────────────
@field_validator("oss_access_key_id", mode="before")
@classmethod
def validate_oss_access_key_id(cls, v):
if (v is None or v == "") and os.getenv("APP_ENV", "development") != "development":
raise ValueError(
"OSS_ACCESS_KEY_ID must be set via environment variable in non-development environments. "
"Check the server .env file (e.g. /var/lib/xiaoxia-saas-staging/.env)."
)
return v or ""
@field_validator("oss_access_key_secret", mode="before")
@classmethod
def validate_oss_access_key_secret(cls, v):
if (v is None or v == "") and os.getenv("APP_ENV", "development") != "development":
raise ValueError(
"OSS_ACCESS_KEY_SECRET must be set via environment variable in non-development environments. "
"Check the server .env file (e.g. /var/lib/xiaoxia-saas-staging/.env)."
)
return v or ""
oss_direct_upload_max_mb: int = Field(
default=2000,
validation_alias=AliasChoices("oss_direct_upload_max_mb", "max_upload_size_mb"),
)
# ── CORS ────────────────────────────────────────────────────────────
cors_origins_raw: str = "http://localhost:3000,http://localhost:5173,http://localhost:8000"
# ── 渲染引擎 ────────────────────────────────────────────────────────
# 渲染引擎选择:legacy=旧VideoComposeService,unified=新UnifiedRenderService
render_engine: str = "legacy"
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
@property
def cors_origins(self) -> list[str]:
return [origin.strip() for origin in self.cors_origins_raw.split(",") if origin.strip()]
# ── 向后兼容:UPPER_CASE property 别名 ──────────────────────────────
# 新代码请使用 snake_case(继承的字段名),以下别名仅用于兼容旧代码
@property
def APP_NAME(self) -> str:
return self.app_name
@property
def APP_VERSION(self) -> str:
return self.app_version
@property
def ENVIRONMENT(self) -> str:
return self.environment
@property
def DEBUG(self) -> bool:
return self.debug
@property
def APP_BASE_URL(self) -> str:
return self.app_base_url
@property
def API_HOST(self) -> str:
return self.api_host
@property
def API_PORT(self) -> int:
return self.api_port
@property
def DATABASE_URL(self) -> str:
return self.database_url
@property
def DATABASE_POOL_SIZE(self) -> int:
return self.database_pool_size
@property
def DATABASE_MAX_OVERFLOW(self) -> int:
return self.database_max_overflow
@property
def DATABASE_POOL_TIMEOUT(self) -> int:
return self.database_pool_timeout
@property
def DATABASE_POOL_RECYCLE(self) -> int:
return self.database_pool_recycle
@property
def USE_IN_MEMORY_DB(self) -> bool:
return self.use_in_memory_db
@property
def AUTO_CREATE_SCHEMA(self) -> bool:
return self.auto_create_schema
@property
def REDIS_URL(self) -> str:
return self.redis_url
@property
def ENABLE_REDIS_SESSIONS(self) -> bool:
return self.enable_redis_sessions
@property
def JWT_SECRET_KEY(self) -> Optional[str]:
return self.jwt_secret_key
@property
def JWT_ALGORITHM(self) -> str:
return self.jwt_algorithm
@property
def JWT_ACCESS_TOKEN_EXPIRE_MINUTES(self) -> int:
return self.jwt_access_token_expire_minutes
@property
def JWT_REFRESH_TOKEN_EXPIRE_DAYS(self) -> int:
return self.jwt_refresh_token_expire_days
@property
def ENABLE_EMAIL_DELIVERY(self) -> bool:
return self.enable_email_delivery
@property
def SMTP_HOST(self) -> str:
return self.smtp_host
@property
def SMTP_PORT(self) -> int:
return self.smtp_port
@property
def SMTP_USER(self) -> str:
return self.smtp_user
@property
def SMTP_PASSWORD(self) -> str:
return self.smtp_password
@property
def SMTP_FROM_EMAIL(self) -> str:
return self.smtp_from_email
@property
def SMTP_FROM_NAME(self) -> str:
return self.smtp_from_name
@property
def SMTP_USE_TLS(self) -> bool:
return self.smtp_use_tls
@property
def CELERY_BROKER_URL(self) -> str:
return self.celery_broker_url
@property
def CELERY_RESULT_BACKEND(self) -> str:
return self.celery_result_backend
@property
def OSS_ENDPOINT(self) -> str:
return self.oss_endpoint
@property
def OSS_ACCESS_KEY_ID(self) -> str:
return self.oss_access_key_id
@property
def OSS_ACCESS_KEY_SECRET(self) -> str:
return self.oss_access_key_secret
@property
def OSS_BUCKET_NAME(self) -> str:
return self.oss_bucket_name
@property
def OSS_DIRECT_UPLOAD_MAX_MB(self) -> int:
return self.oss_direct_upload_max_mb
@property
def OSS_DIRECT_UPLOAD_EXPIRE_SECONDS(self) -> int:
return self.oss_direct_upload_expire_seconds
@property
def CORS_ORIGINS_RAW(self) -> str:
return self.cors_origins_raw
@property
def CORS_ORIGINS(self) -> list[str]:
return self.cors_origins
@property
def RENDER_ENGINE(self) -> str:
return self.render_engine
def get_api_settings() -> APISettings:
"""获取 API 配置单例(统一入口)。"""
return get_cached_settings(APISettings)
+110
View File
@@ -0,0 +1,110 @@
"""统一配置基类 — 所有服务共享的基础配置。
数据库/Redis/OSS/Celery/AI服务等通用配置统一定义在此。
API 和 Worker 各自的 Settings 类继承本类,只追加服务特有字段。
单例模式和 env 文件加载逻辑也统一在这里实现。
"""
import os
from typing import Optional, Type, TypeVar
from pydantic_settings import BaseSettings, SettingsConfigDict
T = TypeVar("T", bound=BaseSettings)
class SharedSettings(BaseSettings):
"""所有服务共享的基础配置。
API 和 Worker 都继承本类,确保:
1. 数据库/Redis/OSS/Celery 等核心配置默认值一致
2. 环境变量命名统一(snake_case,pydantic-settings 自动兼容大写)
3. env 文件加载逻辑只实现一次
"""
# ── 环境 ──────────────────────────────────────────────────────────────
environment: str = "development"
debug: bool = True
auto_create_schema: bool = False
# ── 数据库 ────────────────────────────────────────────────────────────
database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/xiaoxia_saas"
database_pool_size: int = 20
database_max_overflow: int = 10 # pool_size(20) + max_overflow(10) = 最大30连接
database_pool_timeout: int = 30
database_pool_recycle: int = 3600
# ── Redis ────────────────────────────────────────────────────────────
redis_url: str = "redis://localhost:6379/0"
# ── Celery ───────────────────────────────────────────────────────────
celery_broker_url: str = "redis://localhost:6379/0"
celery_result_backend: str = "redis://localhost:6379/1"
# ── OSS 阿里云 ──────────────────────────────────────────────────────
oss_endpoint: str = "oss-cn-hangzhou.aliyuncs.com"
oss_access_key_id: str = ""
oss_access_key_secret: str = ""
oss_bucket_name: str = "xiaoxia-autocut"
oss_direct_upload_max_mb: int = 2000
oss_direct_upload_expire_seconds: int = 900
# ── CosyVoice (阿里云百炼语音合成) ───────────────────────────────────
cosyvoice_api_key: str = ""
cosyvoice_base_url: str = "https://dashscope.aliyuncs.com/api/v1"
cosyvoice_model: str = "cosyvoice-v3-flash"
cosyvoice_voice: str = "longxiaochun_v3" # 默认音色(v3 系列系统音色带 _v3 后缀)
cosyvoice_sample_rate: int = 22050
cosyvoice_format: str = "mp3" # 输出格式:mp3/wav/pcm
# 音色克隆模型名(固定为 voice-enrollment)
cosyvoice_clone_model: str = "voice-enrollment"
# ── 豆包大模型(火山引擎方舟) ────────────────────────────────────────
doubao_api_key: str = ""
doubao_model: str = "doubao-seed-1-6-250615"
doubao_base_url: str = "https://ark.cn-beijing.volces.com/api/v3"
doubao_timeout: int = 30
doubao_max_retries: int = 2
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
# ── 统一单例管理 ────────────────────────────────────────────────────────
# 所有 Settings 类的单例缓存都在这里,消除每处各自实现的重复代码
_settings_cache: dict[str, BaseSettings] = {}
def _get_env_file() -> str:
"""根据 APP_ENV 决定读取哪个 env 文件。"""
env = os.getenv("APP_ENV", "development")
env_file = f".env.{env}" if env != "development" else ".env"
return env_file if os.path.exists(env_file) else ".env"
def get_cached_settings(settings_class: Type[T], cache_key: Optional[str] = None) -> T:
"""统一的 Settings 单例获取函数。
所有服务都通过这个函数获取配置,消除重复的单例实现。
按类名缓存,同一类只初始化一次。
"""
key = cache_key or settings_class.__name__
if key not in _settings_cache:
env_file = _get_env_file()
_settings_cache[key] = settings_class(_env_file=env_file)
return _settings_cache[key] # type: ignore[return-value]
def reload_settings_cache() -> None:
"""清空配置缓存,下次获取时重新加载。测试用。"""
_settings_cache.clear()
def get_shared_settings() -> SharedSettings:
"""获取共享配置单例(统一入口)。"""
return get_cached_settings(SharedSettings)
+44
View File
@@ -0,0 +1,44 @@
"""Worker 服务配置 — 继承 SharedSettings,只追加 Worker 特有字段。
通用配置(DB/Redis/Celery/OSS/CosyVoice/Doubao 等)统一在
packages/config/base.py 的 SharedSettings 中定义,这里不重复。
"""
from pydantic_settings import SettingsConfigDict
from packages.config.base import SharedSettings, get_cached_settings
class WorkerSettings(SharedSettings):
"""Worker 服务专用配置。
通用配置继承自 SharedSettings,这里只定义 Worker 独有字段。
Celery broker/backend 使用继承的 celery_broker_url / celery_result_backend;
历史上 Worker 使用 broker_url / result_backend 字段名,通过 property 别名兼容。
"""
# ── Worker 特有 ────────────────────────────────────────────────────
worker_name: str = "xiaoxia-saas-worker"
worker_concurrency: int = 4
worker_max_tasks_per_child: int = 1000
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
extra="ignore",
)
# ── 向后兼容:Celery 字段名别名 ──────────────────────────────────
@property
def broker_url(self) -> str:
return self.celery_broker_url
@property
def result_backend(self) -> str:
return self.celery_result_backend
def get_worker_settings() -> WorkerSettings:
"""获取 Worker 配置单例(统一入口)。"""
return get_cached_settings(WorkerSettings)
Regular → Executable
+23 -29
View File
@@ -1,36 +1,30 @@
"""Authentication domain services.
"""领域层认证相关端口接口.
Only pure domain authentication helpers are exported here. Infrastructure-backed
services such as Redis session storage and SMTP email delivery live under
`packages.adapters` and should be injected into use cases.
遵循 DDD 依赖倒置原则:领域层定义端口(抽象接口),
外层(应用层、基础设施层)实现端口。
使用方式:
from packages.domain.auth import EmailServicePort, SessionStorePort
from packages.domain.auth import JWTServicePort, PasswordHasherPort
from packages.domain.auth.sms_service import SmsService
注意:具体实现请从对应的适配器层导入:
- 邮件服务: from packages.adapters.smtp import EmailService
- Session存储: from packages.adapters.redis import SessionStore
- JWT服务: from packages.application.auth.jwt_service import JWTService
- 密码哈希: from packages.application.auth.password_hasher import PasswordHasher
"""
from packages.application.auth.jwt_service import (
JWTConfig,
JWTService,
TokenType,
jwt_service,
)
from packages.application.auth.password_hasher import (
PasswordHasher,
PasswordValidator,
password_hasher,
password_validator,
)
from packages.domain.auth.email_service import EmailConfig, EmailService
from packages.domain.auth.session_store import RedisConfig, SessionStore
from packages.domain.auth.email_service import EmailConfig, EmailServicePort
from packages.domain.auth.jwt_service import JWTServicePort
from packages.domain.auth.password_hasher import PasswordHasherPort, PasswordValidatorPort
from packages.domain.auth.session_store import SessionStorePort
__all__ = [
"JWTService",
"JWTConfig",
"TokenType",
"jwt_service",
"PasswordHasher",
"PasswordValidator",
"password_hasher",
"password_validator",
"SessionStore",
"RedisConfig",
"EmailService",
"EmailConfig",
"EmailServicePort",
"JWTServicePort",
"PasswordHasherPort",
"PasswordValidatorPort",
"SessionStorePort",
]
+58 -6
View File
@@ -1,10 +1,62 @@
"""Compatibility import for SMTP email delivery.
"""邮件服务端口(领域层接口).
Infrastructure implementations live under `packages.adapters`. New code should
import `packages.adapters.smtp.email_service` directly or inject an email-sender
port into the use case.
定义邮件发送服务的抽象接口,具体实现由基础设施层(adapters)提供。
遵循 DDD 依赖倒置原则:领域层定义端口,外层实现端口。
"""
from packages.adapters.smtp.email_service import EmailConfig, EmailService
from __future__ import annotations
__all__ = ["EmailConfig", "EmailService"]
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class EmailConfig:
"""邮件配置(领域层值对象)"""
smtp_host: str = "smtp.gmail.com"
smtp_port: int = 587
smtp_user: str = ""
smtp_password: str = ""
from_email: str = ""
from_name: str = "小虾 SaaS"
use_tls: bool = True
class EmailServicePort(ABC):
"""邮件服务端口(抽象接口)"""
@abstractmethod
def send_email(
self,
to_email: str,
subject: str,
html_body: str,
text_body: Optional[str] = None,
cc: Optional[List[str]] = None,
bcc: Optional[List[str]] = None,
) -> tuple[bool, Optional[str]]:
"""发送邮件"""
...
@abstractmethod
def send_verification_email(
self,
to_email: str,
verification_code: str,
username: str = "",
) -> tuple[bool, Optional[str]]:
"""发送验证邮件"""
...
@abstractmethod
def send_password_reset_email(
self,
to_email: str,
reset_token: str,
reset_url: str = "",
username: str = "",
) -> tuple[bool, Optional[str]]:
"""发送密码重置邮件"""
...

Some files were not shown because too many files have changed in this diff Show More