Author SHA1 Message Date
jianghaifeng 2904e59e71 Merge branch 'develop' of https://git.reelshort2.com:80/jianghaifeng/FruitServer into develop
backend-ci / test (push) Failing after 4m42s
2026-11-13 16:55:07 +08:00
Zhou Weidong a5c9357a24 fix: 消除 JWT/签名密钥源码硬编码,全部改为环境变量注入
backend-ci / test (push) Failing after 4m39s
- JwtProperties.adminSecret/appSecret 默认值从 dev 密钥改为空字符串
- MediaProperties.signatureSecret 默认值从 dev 密钥改为空字符串
- app-api/admin-api application.yml 三处密钥回退值均改为空
- docker-compose.yml CORS_ALLOWED_ORIGINS 追加 ymb-site 3007 端口白名单
- .gitignore 追加 *.secrets.env / SSL 证书 / nginx 部署目录忽略规则
2026-11-13 16:53:53 +08:00
Zhou Weidong 12c28963f5 feat(commerce): 完成奖励活动管理接口 2026-11-13 13:43:16 +08:00
jianghaifeng 32cac38a0e feat(auth): Google 登录支持多客户端 audience 校验
- GoogleAuthProperties 的 clientId 改为 clientIds 列表
- GoogleIdTokenVerifier 命中任一 clientId 即通过,兼容 iOS 与 Android 不同的 aud
- app-api 注入三个客户端 id,生产可用 GOOGLE_CLIENT_IDS 覆盖
2026-11-13 12:30:55 +08:00
Zhou Weidong a706621786 fix(commerce): 奖励任务菜单改用46避免覆盖转码设置
backend-ci / test (push) Failing after 5m11s
2026-11-09 10:35:37 +08:00
Zhou Weidong 64eadf1446 feat(commerce): 新增打赏任务中心与签到发奖
backend-ci / test (push) Failing after 4m53s
2026-11-09 10:32:53 +08:00
Zhou Weidong 2fee329002 feat(creator): 内容审核返回创作者与分集信息 2026-11-09 10:32:53 +08:00
Zhou Weidong 9b2833dfd3 feat(creator): 后台录入创作者即通过并可直接开号 2026-11-09 10:32:53 +08:00
Zhou Weidong af0bf7f90e feat(creator): 新增一键发布与删除作品接口 2026-11-09 10:32:46 +08:00
Zhou Weidong a36276051d fix(system): 修复转码设置菜单误下发导致前端白屏 2026-11-09 10:32:46 +08:00
jianghaifeng 3df66c2f4c refactor(media): 抽出 MediaStorage 接口为对象存储切换铺路
backend-ci / test (push) Failing after 5m7s
本地磁盘实现 MediaStorageService 改为实现接口,五处注入点
改为依赖接口;行为不变。后期新增 S3 实现以配置切换即可。
2026-11-05 11:31:31 +08:00
jianghaifeng 32ada4c2bf feat(content): 短剧支持审核通过并上线一步流转
backend-ci / test (push) Failing after 5m8s
新增 APPROVE_PUBLISH 动作与 approve-publish 接口,草稿/审核中/已下线
可直接流转为已上线,事务内同步上线草稿分集并记录一条审核记录,
后台审核操作由三步减为一步。
2026-11-05 10:55:52 +08:00
Zhou Weidong eba7d400e1 fix(deploy): 看门狗飞书告警中文乱码改 UTF-8 发送
backend-ci / test (push) Failing after 4m39s
PS5 Invoke-RestMethod 对字符串 body 默认按 Latin-1 编码导致中文变 ???,
改为手动转 UTF-8 字节数组并声明 charset=utf-8。
2026-11-02 14:52:41 +08:00
Zhou Weidong 3faeba0589 fix(deploy): 补充 CORS 允许来源避免跨域被拒
app-api 增加 frostgiant 域名(含 nginx 非标准 80 端口)与公网 IP 来源;
admin-api 增加公网/局域网 IP 与 admin.frostgiant.vip。
Spring setAllowedOrigins 为精确字符串匹配,来源必须逐条列全。
2026-11-02 14:52:41 +08:00
Zhou Weidong 8a5a381b44 feat(catalog): 新增分类推荐榜快照接口
backend-ci / test (push) Failing after 4m45s
2026-11-02 14:45:43 +08:00
jianghaifeng afd8d00752 feat(catalog): 卡片下发完整简介不再截断
backend-ci / test (push) Canceled after 0s
2026-10-30 22:53:22 +08:00
jianghaifeng 958de5ef22 feat(config): /app/config 下发登录页背景地址
backend-ci / test (push) Canceled after 0s
2026-10-30 17:14:46 +08:00
jianghaifeng f2103f6604 feat(cover): 短剧新增横版封面字段并在进度接口下发
backend-ci / test (push) Canceled after 0s
- Drama/DramaSaveReqVO/DramaRespVO 新增 horizontalCover,打通后台上传链路
- AppDramaCardVO/AppDramaDetailVO 新增 coverLandscape
- ProgressRespVO 新增 dramaCoverLandscape,继续观看横幅可直接取横版图
2026-10-29 17:32:49 +08:00
jianghaifeng 0d4d510aee feat(content): 标签增加语义码并随卡片下发
backend-ci / test (push) Canceled after 0s
标签名称会随语言和运营文案变化,客户端按名称判断板块(如推荐页「上新」
横滑)一改名就失效。content_tag 新增 code 列并在后台维护,
卡片与详情以 tagCode 下发,已有「上新 / 热剧 / 新剧 / 热播」一并回填。
2026-10-29 15:45:34 +08:00
Zhou Weidong 4d796089a0 ops(grafana): 告警规则入库(服务下线/响应慢/磁盘满)
backend-ci / test (push) Failing after 4m38s
2026-10-29 10:53:07 +08:00
Zhou Weidong f71498339c ci: 新增 Gitea Actions 流水线(测试/分析/构建门禁)
backend-ci / test (push) Failing after 7m31s
2026-10-29 10:47:44 +08:00
Zhou Weidong e4fe82283c docs: 更新第一阶段进度表与尚未完成清单(C2/C3 标记已实现) 2026-10-29 10:47:44 +08:00
Zhou Weidong 26102332ac fix(deploy): 看门狗改由用户会话任务启动 Docker Desktop
以 SYSTEM 身份直接 Start-Process Docker Desktop.exe 会命中 WSL_E_LOCAL_SYSTEM_NOT_SUPPORTED,把 docker-desktop 发行版搞成僵死状态(VHD 已挂载无法终止),导致登录用户自己也起不来。改为触发以登录用户身份运行的 FruitShorts-DockerDesktop 计划任务(先停再起,规避 IgnoreNew)。
2026-10-29 10:11:02 +08:00
Zhou Weidong aa5954ef6a chore(merge): 合并 main 的印尼语敏感词库种子到 develop 2026-10-29 09:21:19 +08:00
Zhou Weidong 963bf5c0da test(playback): 补充合并预写缓冲与迟到条目丢弃用例 2026-10-28 19:02:33 +08:00
Zhou Weidong a71d2701d1 fix(playback): 登录合并前预写设备缓冲,迟到条目不得复活已删记录
- 新增 flushIdentity:把某身份缓冲里未落库的进度立即写进权威表;
  mergeDeviceIntoUser 先调用它再扫库,否则登录前 2 秒内的上报会被漏掉,
  稍后落库还会生成一条登录用户看不到的匿名孤儿行;合并完清掉设备侧缓冲。
- planOne 增加判定:逻辑删除会刷新 updated_at,上报时间不晚于它的条目直接丢弃,
  防止删除瞬间已 drain 的在途引用把 deleted 写回 0。
- 去掉 save(Long userId, ...) 上多余的 @Transactional(缓冲路径白开事务)。
2026-10-28 19:02:32 +08:00
Zhou Weidong 025fbe73f0 perf(playback): 上报改用 Lua 单次往返写入缓冲
原先 HSET、EXPIRE、LPUSH、LTRIM 分四次往返,进程若死在写状态与入队之间,
该剧进度只留在 HASH 里永远不落库、12 小时后被 TTL 清掉。合并成一个脚本后
热路径只需 1 次往返,脚本顺带返回 HLEN 是否超 30 决定要不要补裁剪。
2026-10-28 19:02:32 +08:00
Zhou Weidong 0d161f318f chore(merge): 合并 origin/develop 的看门狗周期巡检与 admin-api Redis 配置
watchdog.ps1 冲突取本地实现:计数落盘用 Import/Export 函数,另含 Webhook
三级兜底与告警节流,为远程内联版本的超集。
2026-10-28 18:53:11 +08:00
Zhou Weidong 2eac1fe31d test(playback): 补充缓冲删除双写、已删剧不读回与失效条目丢弃用例 2026-10-28 18:51:52 +08:00
Zhou Weidong 09b0f89e8d fix(deploy): 看门狗失败计数落盘并补齐告警 Webhook 兜底
计划任务每 2 分钟起新进程,进程内计数永远到不了阈值,告警静默哑火;计数改
JSON 落盘跨进程累加,达阈值后只在首达与每 30 轮提醒。Webhook 支持参数、环境
变量、deploy/feishu-webhook.txt 三级兜底,密钥文件不入库。
2026-10-28 18:51:52 +08:00
Zhou Weidong 8fb1f52777 fix(config): 调度线程池扩到 4 条,避免落库与其它定时任务互相排队 2026-10-28 18:51:52 +08:00
Zhou Weidong 44b7abcd0f fix(playback): 删除观看历史时同步清理进度缓冲
缓冲已是读接口的权威来源,只删库行会被读覆盖层读回、并被下一次落库把行复活。
缓冲补 remove/clear(HDEL/DEL),删除路径先清缓冲再删库行,读覆盖层按库行
deleted 过滤;落库时缓冲状态已失效的条目直接丢弃,不再整批退回队列。
2026-10-28 18:51:52 +08:00
Zhou Weidong 181b338780 fix(ops): 修复管理端 Redis 未配置与看门狗未真正周期巡检
- admin-api 的 application.yml 缺少 spring.data.redis 配置,容器内默认连
  127.0.0.1 导致 /actuator/health 返回 DOWN(redis 组件不可用);
  补齐后与 app-api 共用 REDIS_HOST/REDIS_PORT,健康检查恢复 UP
- 计划任务原先用 BootTrigger 挂 Repetition,Windows 不生效(Next Run Time
  为 N/A,9 小时只跑过一次),看门狗形同虚设;改为 TimeTrigger + PT2M
  无限重复 + StartWhenAvailable,实测每 2 分钟稳定巡检
- watchdog.ps1 的连续失败计数改为落盘 watchdog-state.json,避免每轮进程
  重启后清零导致「连续 3 次失败告警」永不触发
2026-10-28 18:23:48 +08:00
Zhou Weidong 657190d5a8 chore(deploy): 加入服务看门狗脚本与 Windows 计划任务注册文件
- watchdog.ps1:每 2 分钟健康检查,Docker/DB/Redis/API/Grafana 任一
  不健康自动重启,连续 3 次失败发飞书告警,C 盘超 85% 也告警
- backend-watchdog-task.xml:开机触发、2 分钟循环的计划任务配置
2026-10-28 15:00:58 +08:00
Zhou Weidong 3e2d6a06d9 perf(playback): 观看进度上报异步化(Redis write-behind 批量落库)
- POST /app/watch/progress 只写 Redis 缓冲立即返回(p95 75ms→2ms),
  WatchProgressFlusher 每 2s 把 watch:pg:dirty 队列按身份合并批量 UPSERT,
  Redis 异常自动回退同步写库,接口契约不变
- 读接口用缓冲覆盖 DB 行保证读己之写;Caffeine 缓存剧集校验免去上报路径两条 DB 查询
- 落库按「新增进度/新增流水/更新行」分组攒批(MyBatis BATCH 只合并连续同形状语句),
  配合 reWriteBatchedInserts 多值 INSERT,12.4 万积压 45 秒消化完,
  1650 QPS 持续压测队列稳态归零
2026-10-28 14:59:09 +08:00
Zhou Weidong fc9e429187 feat(monitoring): 接入 Loki + Promtail 日志采集,Grafana 可直接搜索容器日志 2026-10-28 10:38:41 +08:00
Zhou Weidong 5d139783c9 fix(media): 缩略图唯一索引改为部分索引,避免软删行占用 episode_id 导致登记冲突 2026-10-27 21:07:10 +08:00
Zhou Weidong ddd2406f32 fix(build): Docker 构建阶段固定阿里云 Maven 中央镜像
容器内从 Maven Central 拉依赖时 maven-filtering:3.3.1 解析失败,
且 dependency:go-offline 被 || true 静默吞掉,导致发布时才暴露。
构建阶段写入 settings.xml 走阿里云 central 镜像,并让 go-offline 失败即中断。
2026-10-27 20:14:19 +08:00
Vicky 272aa62434 feat: phase1 UI prep — P1 安全(XFF防护), P2 规模化(平台索引+region保护), P3 文档补全
P1 安全: WebUtils.getClientIp 改为 remoteAddr 优先 + 可信代理 CIDR 配置
P2 规模化: DISTINCT ON 查询补匹配排序的部分索引 (migrate-k113)
P2 一致性: syncCountryByIp regionCode 同语言/时区/币种加保护,不覆盖用户自定义
P3 文档: api-phase1.md 新增 platform 参数说明, IpRegionService 新增集成测试 + VERSION
新增: CountryProfile 52 国映射 + IpRegionService 离线 ip2region 解析
平台筛选: app-users/favorites/likes/watch-history 按最近一次会话 ANDROID/IOS 筛选
2026-10-27 15:45:15 +08:00
jianghaifeng a41ab18636 perf(admin): 优化观看记录列表并统一时间格式
- 新增 watched_at 索引,默认倒序翻页走 Merge Append 而不是全表排序
- 装配只取展示所需列,会话查询不再拉 refresh_token_hash
- 关键词预检索加 2000 条上限
- admin-api 的 LocalDateTime 统一输出 yyyy-MM-dd HH:mm:ss
2026-10-27 14:39:13 +08:00
jianghaifeng 8999ff395d feat(admin): 收藏/点赞/观看记录支持按客户端平台筛选
- 设备画像按 device_id 命中,登录用户按最近一次登录会话的平台命中
- 修正 orderBy 先于动态条件导致 SQL 拼接错误的问题
2026-10-27 14:27:10 +08:00
jianghaifeng 229f1d0198 refactor(device): 设备平台只记 iOS/Android
去掉系统版本、机型与版本号上报,表结构收敛为 device_id + platform。
2026-10-27 14:00:12 +08:00
jianghaifeng 2dadca6288 chore(merge): 合并设备画像与后台系统展示 2026-10-27 13:53:49 +08:00
Vicky 2cf8f9a1c3 feat(device): 按 device_id 记录客户端系统与机型
- 新增 app_device_profile 表与 upsert,匿名请求同样建档
- app-api 设备画像过滤器,同设备 60 秒节流写一次
- 收藏/点赞/观看列表优先用设备画像,缺失回退最近会话
2026-10-27 13:53:47 +08:00
jianghaifeng d9a1670a72 chore(merge): 合并互动计数校准 2026-10-27 13:29:09 +08:00
Vicky 5ff4626b33 chore(sql): 校准被压测数据污染的互动计数
剧集点赞数与剧收藏数改回按实际未删除互动行重算,可重复执行。
2026-10-27 13:29:09 +08:00
jianghaifeng 6bbde0b100 chore(merge): 合并剧级点赞历史数据清理 2026-10-27 13:28:15 +08:00
Vicky 884324b8fd chore(sql): 清理历史遗留的剧级点赞数据
客户端点赞入口只作用于剧集,13 条 DRAMA 记录为旧模型遗留;
软删并同步校准 drama.like_count。
2026-10-27 13:28:15 +08:00
jianghaifeng 7baaeddf26 chore(merge): 合并点赞筛选说明文档 2026-10-27 13:25:52 +08:00
Vicky 99d49a1765 docs(admin): 说明点赞列表三种目标与 episodeId 筛选边界
- 明确客户端点赞落 EPISODE,DRAMA 为历史数据
- 说明 episodeId 只命中该集及该集评论,不含对短剧本身的点赞
2026-10-27 13:25:51 +08:00
jianghaifeng 92f7606f65 chore(merge): 合并收藏与点赞列表查询加固 2026-10-27 13:23:23 +08:00
Vicky c2ba3df47c fix(admin): 加固收藏与点赞列表查询
- 关键词/剧名预检索加 2000 条上限,避免 IN 列表超限并给出可操作提示
- 新增 created_at 分页索引迁移,避免无条件列表退化为全表排序
- dramaPublished 改为三态,短剧已不存在时不再误报未发布
2026-10-27 13:23:21 +08:00
Zhou Weidong 226dc275bb merge(admin): 合并收藏与点赞只读查询 2026-10-27 12:32:23 +08:00
Zhou Weidong 7a2ff3f80e feat(admin): 新增收藏与点赞只读查询接口 2026-10-27 12:32:23 +08:00
Zhou Weidong 23321a0b0c feat(favorites): 支持设备批量取消收藏 2026-10-27 10:33:59 +08:00
Zhou Weidong 5d44ac239b fix(watch): 修复匿名进度查询参数类型 2026-10-27 10:01:21 +08:00
Zhou Weidong 848c746505 feat(watch): 支持设备观看与登录合并 2026-10-27 09:54:47 +08:00
Zhou Weidong 4b0fbd73d3 feat(interaction): 支持游客互动与登录合并 2026-10-26 22:34:14 +08:00
Zhou Weidong 2fe24b9db7 feat(interaction): 新增分集计数统计接口 2026-10-26 21:31:17 +08:00
Zhou Weidong 15b540cdd6 chore(merge): 合并内容多语言与转码通知 2026-10-24 16:57:31 +08:00
Zhou Weidong 50b3dd4a8e docs(api): 同步多语言筛选与转码通知契约 2026-10-24 16:53:26 +08:00
Zhou Weidong 1d34e47673 feat(admin): 增加工作台指标和转码通知 2026-10-24 16:53:26 +08:00
Zhou Weidong 2367a5d12b feat(app): 全部短剧改为请求体分页 2026-10-24 16:53:26 +08:00
Zhou Weidong ebc5f890fd feat(playback): 观看记录返回标题多语言 2026-10-24 16:53:26 +08:00
Zhou Weidong e60c47123c feat(content): 短剧分类和标签支持多语言 2026-10-24 16:53:26 +08:00
Zhou Weidong 5c20cf1ab9 Merge branch feat/app-version-and-c-end 2026-10-23 16:45:55 +08:00
Zhou Weidong 45cf405285 feat(api): 加C端分类频道和剧单详情接口 2026-10-23 16:45:28 +08:00
Zhou Weidong 4f80a691d1 feat(app-version): 加批量创建接口 2026-10-23 16:45:20 +08:00
Zhou Weidong 47f19a98eb chore(merge): 合并 App 版本管理后端 2026-10-23 15:27:35 +08:00
Zhou Weidong 62792413df feat(app): 新增后台 App 版本管理接口 2026-10-23 15:27:35 +08:00
Zhou Weidong 34c775620d chore(merge): 合并 compose Redis 依赖修复 2026-10-23 14:58:46 +08:00
Zhou Weidong b3774e0112 fix(deploy): compose 编排补充 REDIS_HOST 依赖 2026-10-23 14:58:46 +08:00
Zhou Weidong 0e6f7531d4 chore(merge): 合并大盘趋势与分布接口 2026-10-23 14:58:33 +08:00
Zhou Weidong 73a8db8498 feat(dashboard): 大盘趋势与分布接口 2026-10-23 14:58:33 +08:00
Zhou Weidong cf657707f9 chore(merge): 合并转码补齐功能 2026-10-23 14:14:39 +08:00
Zhou Weidong 40728e685b feat(media): 新增缺失转码产物自动补齐 2026-10-23 14:14:39 +08:00
Zhou Weidong 6abb09e5c2 chore(merge): 将 release/v1.0.0 同步到 main 2026-10-23 13:07:42 +08:00
Zhou Weidong df2da25833 chore(merge): 合并用户系统协议与播放改动 2026-10-23 12:34:26 +08:00
Zhou Weidong 1ea4cfeba3 test(media): 按物理删除校验重转码清理 2026-10-23 12:34:13 +08:00
Zhou Weidong ce6e3ef70a docs(api): 同步搜索协议播放与收藏契约 2026-10-23 12:34:13 +08:00
Zhou Weidong 87e20c31a9 feat(security): 允许匿名搜索与打开协议页 2026-10-23 12:34:13 +08:00
Zhou Weidong 22edf34ff1 feat(system): 支持后台维护三语协议 2026-10-23 12:34:13 +08:00
Zhou Weidong 16ba79a336 feat(interaction): 支持批量取消收藏 2026-10-23 12:34:13 +08:00
Zhou Weidong 9c25b1b397 fix(playback): 恢复已删除的观看进度 2026-10-23 12:34:13 +08:00
Zhou Weidong 5a80e6693f feat(playback): 播放票据返回各清晰度地址 2026-10-23 12:34:13 +08:00
Zhou Weidong ab58641bbe feat(user): 展示用户最近使用的系统 2026-10-23 12:34:13 +08:00
Zhou Weidong 45e3d84f59 docs(api): 补充分类与剧单管理接口文档 2026-10-22 22:17:58 +08:00
Zhou Weidong a3ff636e45 chore(sql): 补充转码设置菜单初始化补丁 2026-10-22 22:17:58 +08:00
Zhou Weidong 7b360ddccd feat(content): 新增运营分类与剧单分类管理 2026-10-22 22:17:58 +08:00
Zhou Weidong 758c7521bb Merge remote-tracking branch 'origin/develop' into develop 2026-10-22 18:21:05 +08:00
Zhou Weidong e730cfaa7d fix(media): 重转码物理清理旧产物避免唯一键冲突 2026-10-22 18:21:00 +08:00
Zhou Weidong 60a87a8d15 docs(client): 回填首页与我的视觉改版记录 2026-10-22 17:08:05 +08:00
Zhou Weidong 0b519b8ca1 docs(nav): 回填客户端四 Tab 导航记录 2026-10-22 16:22:07 +08:00
Zhou Weidong e6b4a747ce merge: 修复转码 rendition 幂等与失败落库 2026-10-22 15:37:01 +08:00
Zhou Weidong f009f75c03 docs(media): 回填转码修复记录 2026-10-22 15:36:51 +08:00
Zhou Weidong 91b621fe75 fix(media): 清理旧 rendition 并确保失败状态落库 2026-10-22 15:36:35 +08:00
Zhou Weidong 5d1a157085 merge: 修复转码任务认领与媒资校验 2026-10-22 15:27:58 +08:00
Zhou Weidong 5552caa6c1 fix(media): 修正转码任务认领与媒资 id 校验 2026-10-22 15:27:51 +08:00
Zhou Weidong ad84704d28 test(media): 覆盖转码认领与非法媒资 id 2026-10-22 15:27:37 +08:00
Zhou Weidong 08eddc9ed2 merge: 修复转码错误截断与进度上报 2026-10-22 15:13:50 +08:00
Zhou Weidong 660afaf66d fix(media): 转码错误信息截断并上报进度 2026-10-22 15:12:05 +08:00
Zhou Weidong f9bc6eee6d merge: 修复转码媒资 id 精度与存量兜底 2026-10-22 14:59:46 +08:00
Zhou Weidong 5ef5dd8eaf fix(media): 修正转码媒资 id 解析与存量分集补登记 2026-10-22 14:59:16 +08:00
Zhou Weidong a35b02dd18 merge: 修复转码保持原始宽高比 2026-10-22 14:31:30 +08:00
Zhou Weidong 04d25cd23d fix(media): 转码按短边等比定档并回写实际尺寸 2026-10-22 14:31:22 +08:00
Zhou Weidong 217ff24f1c test(media): 覆盖转码保持原始宽高比 2026-10-22 14:30:08 +08:00
Zhou Weidong 40a884cc85 merge: 补齐转码产物查询接口 2026-10-22 14:14:21 +08:00
Zhou Weidong 345408d5e7 feat(media): 新增清晰度与帧图查询接口 2026-10-22 14:14:13 +08:00
Zhou Weidong 090f149b31 test(media): 覆盖转码产物查询接口 2026-10-22 14:10:15 +08:00
Zhou Weidong f66eae5baf merge: 打通后台转码链路 2026-10-22 14:03:13 +08:00
Zhou Weidong 4219186ab0 feat(media): 上传与改片自动入队转码并支持手动重转 2026-10-22 14:03:04 +08:00
Zhou Weidong 7e6075a2e9 test(media): 覆盖转码入队与重转幂等 2026-10-22 14:01:26 +08:00
Zhou Weidong cd51aabe7e merge: 观看历史统一分页契约并移除 limit 2026-10-22 13:21:35 +08:00
Zhou Weidong c5468a669b refactor(app): 观看历史统一分页契约并移除 limit 2026-10-22 13:21:07 +08:00
Zhou Weidong 7b694938c6 merge: 收藏与观看历史支持分页 2026-10-22 12:23:52 +08:00
Zhou Weidong 71b0c7315a feat(app): 收藏与观看历史支持分页 2026-10-22 12:23:43 +08:00
Zhou Weidong ec15950851 merge: 修复转码分集绑定与产物回填 2026-10-22 12:04:08 +08:00
Zhou Weidong 7d563f2cd6 fix(media): 补齐分集转码绑定与产物回填 2026-10-22 12:03:58 +08:00
Zhou Weidong 6bdd245a83 merge: 合并转码配置与缩略图轴 2026-10-22 11:20:35 +08:00
Zhou Weidong 316baf28d6 feat(media): 支持后台转码配置与缩略图轴 2026-10-22 11:20:28 +08:00
Zhou Weidong 70da939a58 docs(plans): 合并剧集列表分页作者偏差登记 2026-10-22 09:18:42 +08:00
Zhou Weidong 07754ff4e4 docs(plans): 登记剧集列表分页合并提交作者偏差 2026-10-22 09:18:42 +08:00
Zhou Weidong 4159af1732 merge: 剧集列表接口支持分页 2026-10-21 23:09:42 +08:00
Zhou Weidong 0143fa036c feat(admin): 剧集列表接口支持分页 2026-10-21 23:09:30 +08:00
Zhou Weidong 5227762aeb docs(plans): 短剧价格同步幂等纠偏留痕 2026-10-21 22:56:36 +08:00
jianghaifeng a4317bb6f1 merge: 短剧保存时始终同步分集价格 2026-10-21 22:49:43 +08:00
Zhou Weidong 8b37e23951 feat: 印尼语敏感词库种子数据(id-ID 增量补全 78 词) 2026-10-19 18:43:01 +08:00
394 changed files with 22903 additions and 534 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Author: fruit.com.cn
# FruitServer 后端 CI:编译 + 测试门禁
name: backend-ci
on:
push:
branches: [develop, main]
pull_request:
branches: [develop, main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
cache: maven
- name: 编译 + 单测
run: mvn -B -T 1C test -DfailIfNoTests=false
- name: 打包(跳过测试)
if: success()
run: mvn -B package -DskipTests -q
+16
View File
@@ -19,3 +19,19 @@ data/uploads/*
# 部署用的真实环境变量(含密钥),只提交 .env.example # 部署用的真实环境变量(含密钥),只提交 .env.example
.env .env
*.secrets.env
dump.rdb
# 看门狗飞书告警 Webhook,只存在于部署机
deploy/feishu-webhook.txt
# SSL 证书与私钥(.crt/.cer/.pem/.key/.p12/.jks)—— 部署机本地文件,禁止入库
*.crt
*.cer
*.pem
*.key
*.p12
*.jks
# 部署用 nginx 配置目录(挂载卷的本地配置,随环境而异)
nginx/
+15 -1
View File
@@ -15,6 +15,20 @@
FROM maven:3.9-eclipse-temurin-21 AS build FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build WORKDIR /build
# Maven Central 在国内网络下拉依赖不稳定(构建时曾出现 maven-filtering:3.3.1 解析失败),
# 构建阶段固定走阿里云 central 镜像;其它仓库仍直连。
RUN mkdir -p /root/.m2 \
&& printf '%s\n' \
'<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0">' \
' <mirrors>' \
' <mirror>' \
' <id>aliyun-central</id>' \
' <mirrorOf>central</mirrorOf>' \
' <url>https://maven.aliyun.com/repository/central</url>' \
' </mirror>' \
' </mirrors>' \
'</settings>' > /root/.m2/settings.xml
# 先只拷各模块 pom 再拉依赖:依赖层可复用,改业务代码不会重新下载依赖 # 先只拷各模块 pom 再拉依赖:依赖层可复用,改业务代码不会重新下载依赖
COPY pom.xml . COPY pom.xml .
COPY fruitshorts-common/pom.xml fruitshorts-common/ COPY fruitshorts-common/pom.xml fruitshorts-common/
@@ -30,7 +44,7 @@ COPY fruitshorts-module-creator/pom.xml fruitshorts-module-creator/
COPY fruitshorts-admin-api/pom.xml fruitshorts-admin-api/ COPY fruitshorts-admin-api/pom.xml fruitshorts-admin-api/
COPY fruitshorts-app-api/pom.xml fruitshorts-app-api/ COPY fruitshorts-app-api/pom.xml fruitshorts-app-api/
COPY fruitshorts-transcode-worker/pom.xml fruitshorts-transcode-worker/ COPY fruitshorts-transcode-worker/pom.xml fruitshorts-transcode-worker/
RUN mvn -B -q -DskipTests dependency:go-offline || true RUN mvn -B -q -DskipTests dependency:go-offline
COPY . . COPY . .
ARG MODULE=fruitshorts-app-api ARG MODULE=fruitshorts-app-api
+10 -10
View File
@@ -191,7 +191,7 @@ java -jar fruitshorts-app-api/target/fruitshorts-app-api-1.0.0-SNAPSHOT.jar
## 第一阶段实现进度 ## 第一阶段实现进度
> 最后更新:2026-10-16(后端 `develop` 分支 `4418a84`)。**未完成清单见文末「尚未完成」。** > 最后更新:2026-10-24(拉取 `develop` 最新代码后)。**未完成清单见文末「尚未完成」。**
| 模块 | 状态 | 说明 | | 模块 | 状态 | 说明 |
| --- | --- | --- | | --- | --- | --- |
@@ -200,11 +200,11 @@ java -jar fruitshorts-app-api/target/fruitshorts-app-api-1.0.0-SNAPSHOT.jar
| 03 内容发现与详情 | 已实现 | 首页/发现/分类/详情;内容分级、可播区域、版权窗口、标签字段 | | 03 内容发现与详情 | 已实现 | 首页/发现/分类/详情;内容分级、可播区域、版权窗口、标签字段 |
| 04 播放器与播放控制 | 已实现 | 播放票据 + 签名地址 + 进度;多码率 HLS 由转码 worker 产出(见 10) | | 04 播放器与播放控制 | 已实现 | 播放票据 + 签名地址 + 进度;多码率 HLS 由转码 worker 产出(见 10) |
| 05 记录、收藏与下载 | 已实现 | 进度、观看流水、收藏、离线下载授权与任务 | | 05 记录、收藏与下载 | 已实现 | 进度、观看流水、收藏、离线下载授权与任务 |
| 06 评论、点赞与分享 | 已实现 | 评论(游标翻页/审核/删除)、点赞、举报、敏感词;**分享埋点待 C3** | | 06 评论、点赞与分享 | 已实现 | 评论(游标翻页/审核/删除)、点赞、举报、敏感词、分享 |
| 07 创作者中心 | 已实现 | **在后台管理(Web 端 `ReelShortWeb`)**:工作台、内容编辑、分片上传与断点续传、提交审核与上下架、分集收费与试看、数据看板;不含提现/结算。**App 客户端不提供创作者中心**(口径 2026-10-16) | | 07 创作者中心 | 已实现 | **在后台管理(Web 端 `ReelShortWeb`)**:工作台、内容编辑、分片上传与断点续传、提交审核与上下架、分集收费与试看、数据看板;不含提现/结算。**App 客户端不提供创作者中心**(口径 2026-10-16) |
| 08 平台运营后台 | 已实现 | 用户管理、内容治理、订单与权益、创作者与内容审核、数据看板 + 四个后台页面 | | 08 平台运营后台 | 已实现 | 用户管理、内容治理、订单与权益、创作者与内容审核、数据看板 + 四个后台页面 |
| 09 分集收费与支付 | 部分 | **Google Play 票据校验闭环已实现**(校验→建单→发权益、幂等与防重放、恢复购买、退款拒付回收、对账);**Apple IAP 只留端口未实现**(印尼 iOS 占比低,文档口径为"预留") | | 09 分集收费与支付 | 部分 | **Google Play 票据校验闭环已实现**(校验→建单→发权益、幂等与防重放、恢复购买、退款拒付回收、对账);**Apple IAP 只留端口未实现**(印尼 iOS 占比低,文档口径为"预留") |
| 10 质量、数据与上线 | 部分 | **转码 worker(C1)已实现**;**Redis 缓存与限流(C2)、埋点(C3)、压测未做** | | 10 质量、数据与上线 | 部分 | **转码 worker(C1)、Redis 缓存与限流(C2)、埋点(C3)均已实现**;**压测未做** |
### 已完成批次(按提交顺序) ### 已完成批次(按提交顺序)
@@ -426,18 +426,18 @@ public Result<Long> create(@Valid @RequestBody DramaCategorySaveReqVO req) { ...
## 尚未完成 ## 尚未完成
> 最后更新:2026-10-16。完成后请同步本表与 [docs/api-phase1.md](docs/api-phase1.md)。 > 最后更新:2026-10-24。完成后请同步本表与 [docs/api-phase1.md](docs/api-phase1.md)。
### 一、后端研发(剩余) ### 一、后端研发(剩余)
> 已完成的项(不再列出):**C2 Redis 缓存与限流**(`framework/redis` 的 `RedisService` + `RateLimit` 切面)、**C3 埋点**(客户端埋点 SDK),均于 10-20 ~ 10-23 落地。
| # | 项 | 内容 | 依据 | | # | 项 | 内容 | 依据 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| 1 | **C2 Redis 缓存与限流** | 首页/发现/分类等热点接口缓存(Cache-Aside)+ 验证码/注册/登录限流;生产 Redis 规格 `4C16G 主从 2~3 哨兵` | 任务清单 C2、`17-风险评估` R-10、`10-安全方案` §三 | | 1 | **Apple IAP 票据校验** | 目前只留端口与枚举,未做真实校验(印尼 iOS 占比低,文档口径为"预留") | `api-phase1` §1.8 |
| 2 | **C3 埋点** | 播放/支付/转化事件 + 数据字典对齐(含 06 的分享埋点) | 任务清单 C3、`api-phase1` §3 | | 2 | **压测** | 目标 `P95 < 50ms`(预热后);容量口径文档里有两套("1 万并发"与"2 万并发 + 3000 QPS"),需定稿 | `09-测试计划` §五、`13/14-容量` |
| 3 | **Apple IAP 票据校验** | 目前只留端口与枚举,未做真实校验(印尼 iOS 占比低,文档口径为"预留") | `api-phase1` §1.8 | | 3 | **对账数据源** | 结算金额/手续费/税只能从 Play Console 财务报告取(需报表权限);当前 `storeAmountSum` 恒为 `null` + `notes` 说明 | B1-2 待确认 |
| 4 | **压测** | 目标 `P95 < 50ms`(预热后);容量口径文档里有两套("1 万并发"与"2 万并发 + 3000 QPS"),需定稿 | `09-测试计划` §五、`13/14-容量` | | 4 | **退款口径完善** | 部分退款按比例回收、退款实时性(当前由每日对账 + 手动驱动,未接 RTDN 推送) | B1-2 待确认 |
| 5 | **对账数据源** | 结算金额/手续费/税只能从 Play Console 财务报告取(需报表权限);当前 `storeAmountSum` 恒为 `null` + `notes` 说明 | B1-2 待确认 |
| 6 | **退款口径完善** | 部分退款按比例回收、退款实时性(当前由每日对账 + 手动驱动,未接 RTDN 推送) | B1-2 待确认 |
### 二、上线前必补(P0 / Go-No-Go:非研发,但阻塞上线) ### 二、上线前必补(P0 / Go-No-Go:非研发,但阻塞上线)
+38
View File
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Description>FruitShorts backend watchdog: health check every 2 minutes and restart unhealthy services.</Description>
</RegistrationInfo>
<Principals>
<Principal id="Author">
<UserId>S-1-5-18</UserId>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<StartWhenAvailable>true</StartWhenAvailable>
<ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
</Settings>
<Triggers>
<!-- BootTrigger 上挂 <Repetition> 在 Windows 计划任务里不生效(导入后 Next Run Time 为 N/A,
实际只在开机跑一次)。改成 TimeTrigger + 无限重复,配合 StartWhenAvailable
保证开机后若错过也会立即补跑;这样才真正做到每 2 分钟巡检一次。 -->
<TimeTrigger>
<StartBoundary>2026-01-01T00:00:00</StartBoundary>
<Repetition>
<Interval>PT2M</Interval>
<Duration>P3650D</Duration>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
</TimeTrigger>
</Triggers>
<Actions Context="Author">
<Exec>
<Command>powershell.exe</Command>
<Arguments>-NoProfile -ExecutionPolicy Bypass -File "C:\Users\Administrator\Desktop\ReelShorts\FruitServer\deploy\watchdog.ps1" -ComposeDir "C:\Users\Administrator\Desktop\ReelShorts\FruitServer" -LogDir "C:\Users\Administrator\Desktop\ReelShorts\FruitServer\logs"</Arguments>
</Exec>
</Actions>
</Task>
+232
View File
@@ -0,0 +1,232 @@
# Author: fruit.com.cn
#
# 服务看门狗:每 2 分钟检查一次,挂了自动拉起,连续失败发飞书告警。
# 注册为 Windows 计划任务后无人值守运行。
param(
[string]$ComposeDir = "C:\FruitServer",
[string]$LogDir = "C:\FruitServer\logs",
[string]$FeishuWebhook = "",
[int]$MaxRestarts = 3,
[string]$FrontendTask = "FruitShorts-Web-3005"
)
$ErrorActionPreference = "Continue"
$ComposeFile = Join-Path $ComposeDir "docker-compose.yml"
$LogFile = Join-Path $LogDir "watchdog-$(Get-Date -Format 'yyyy-MM-dd').log"
# 连续失败计数落盘文件:计划任务每 2 分钟起一个新进程,计数只放进程内永远累积不到
# $MaxRestarts,告警会静默哑火。
$StateFile = Join-Path $LogDir "watchdog-state.json"
function Write-Log($msg) {
$line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') $msg"
Add-Content -Path $LogFile -Value $line -ErrorAction SilentlyContinue
}
function Send-Alert($title, $msg) {
if (-not $FeishuWebhook) { return }
$json = @{
msg_type = "text"
content = @{ text = "[$title] $msg" }
} | ConvertTo-Json -Depth 3
try {
# PS5 的 Invoke-RestMethod 对字符串 body 默认按 Latin-1 编码,中文会变成 ???,
# 必须手动转 UTF-8 字节数组发送
$bytes = [System.Text.Encoding]::UTF8.GetBytes($json)
Invoke-RestMethod -Uri $FeishuWebhook -Method Post -Body $bytes -ContentType "application/json; charset=utf-8" -TimeoutSec 10
} catch {
Write-Log "飞书告警发送失败: $_"
}
}
# 连续失败计数的读写:JSON 落盘,跨进程保留
function Import-FailCounts {
$counts = @{}
if (-not (Test-Path $StateFile)) { return $counts }
try {
$saved = Get-Content -Path $StateFile -Raw | ConvertFrom-Json
foreach ($prop in $saved.PSObject.Properties) {
$counts[$prop.Name] = [int]$prop.Value
}
} catch {
Write-Log "看门狗计数文件解析失败,各服务按 0 重新计数: $_"
}
return $counts
}
function Export-FailCounts($counts) {
try {
$counts | ConvertTo-Json | Set-Content -Path $StateFile -Encoding UTF8
} catch {
Write-Log "看门狗计数文件写入失败: $_"
}
}
function Test-Docker {
docker info --format "{{.ServerVersion}}" 2>$null | Out-Null
return ($LASTEXITCODE -eq 0)
}
function Test-Http([string]$url) {
try {
$response = Invoke-WebRequest -Uri $url -TimeoutSec 10 -UseBasicParsing -ErrorAction Stop
return ($response.StatusCode -ge 200 -and $response.StatusCode -lt 400)
} catch {
return $false
}
}
function Test-Container([string]$container) {
$status = docker inspect -f "{{.State.Status}}" $container 2>$null
return ($status -eq "running")
}
function Invoke-Compose([string[]]$composeArgs) {
& docker compose -f $ComposeFile @composeArgs 2>&1 | Out-Null
return $LASTEXITCODE
}
# 确保日志目录存在
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
# 告警 Webhook:命令行参数 > 环境变量 > deploy 目录下的 feishu-webhook.txt。
# 计划任务注册命令里不写密钥(密钥不该进版本库),由部署机本地放文件或配环境变量。
if (-not $FeishuWebhook) { $FeishuWebhook = $env:FRUITSHORTS_FEISHU_WEBHOOK }
if (-not $FeishuWebhook) {
$webhookFile = Join-Path $PSScriptRoot "feishu-webhook.txt"
if (Test-Path $webhookFile) {
$FeishuWebhook = (Get-Content -Path $webhookFile -Raw -ErrorAction SilentlyContinue)
if ($FeishuWebhook) { $FeishuWebhook = $FeishuWebhook.Trim() }
}
}
if (-not $FeishuWebhook) {
Write-Log "未配置飞书 Webhook(参数/环境变量/feishu-webhook.txt 均为空),告警只写本地日志"
}
# Docker Desktop 登录后偶尔尚未就绪,先等待并尝试拉起。
# 注意:本脚本以 SYSTEM 身份运行,绝不能直接 Start-Process Docker Desktop.exe。
# WSL 不支持本地系统账户运行(WSL_E_LOCAL_SYSTEM_NOT_SUPPORTED),
# 以 SYSTEM 启动会把 docker-desktop 发行版搞成僵死状态(VHD 已挂载无法终止),
# 结果是登录用户会话里的 Docker Desktop 也永远起不来。
# 因此改为触发以登录用户身份运行的 FruitShorts-DockerDesktop 计划任务。
if (-not (Test-Docker)) {
Write-Log "Docker 未就绪,尝试通过用户会话启动 Docker Desktop"
$desktopTask = "FruitShorts-DockerDesktop"
try {
# Docker Desktop.exe 是任务进程树的一部分,GUI 活着时任务一直是 Running,
# 直接 Start-ScheduledTask 会被 IgnoreNew 忽略,所以先结束旧实例再拉起。
$t = Get-ScheduledTask -TaskName $desktopTask -ErrorAction Stop
if ($t.State -eq "Running") {
Stop-ScheduledTask -TaskName $desktopTask -ErrorAction SilentlyContinue
Start-Sleep -Seconds 5
}
Start-ScheduledTask -TaskName $desktopTask -ErrorAction Stop
} catch {
Write-Log "触发 Docker Desktop 启动任务失败: $_"
}
for ($i = 0; $i -lt 18; $i++) {
Start-Sleep -Seconds 5
if (Test-Docker) { break }
}
}
if (-not (Test-Docker)) {
Write-Log "Docker 在 90 秒内未就绪,跳过本轮检查"
Send-Alert "服务异常" "Docker Desktop 无法启动,请人工检查桌面机。"
exit 1
}
# 健康检查定义:名称 → 检查方式
$checks = @(
@{ Name = "app-api"; Type = "http"; Url = "http://127.0.0.1:8081/healthz"; Service = "app-api"; Container = "fruitshorts-app-api" },
@{ Name = "admin-api"; Type = "http"; Url = "http://127.0.0.1:8080/healthz"; Service = "admin-api"; Container = "fruitshorts-admin-api" },
@{ Name = "frontend"; Type = "frontend"; Url = "http://127.0.0.1:3005/dist-dev/" },
@{ Name = "Grafana"; Type = "http"; Url = "http://127.0.0.1:3000/api/health"; Service = "grafana"; Container = "fruitshorts-grafana" },
@{ Name = "PostgreSQL"; Type = "docker"; Service = "db"; Container = "fruitshorts-db" },
@{ Name = "Redis"; Type = "docker"; Service = "redis"; Container = "fruitshorts-redis" },
@{ Name = "Prometheus"; Type = "http"; Url = "http://127.0.0.1:9090/-/healthy"; Service = "prometheus"; Container = "fruitshorts-prometheus" }
)
# 跟踪每个服务的连续失败次数(跨进程从状态文件恢复)
$failCounts = Import-FailCounts
foreach ($check in $checks) {
$name = $check.Name
$healthy = $false
if ($check.Type -eq "http") {
$healthy = Test-Http $check.Url
} elseif ($check.Type -eq "frontend") {
$healthy = Test-Http $check.Url
} else {
$healthy = Test-Container $check.Container
}
if ($healthy) {
if ($failCounts[$name] -gt 0) {
Write-Log "$name 恢复正常(此前连续失败 $($failCounts[$name]) 次)"
Send-Alert "服务恢复" "$name 已恢复正常"
}
$failCounts[$name] = 0
} else {
if ($null -eq $failCounts[$name]) {
$failCounts[$name] = 0
}
$failCounts[$name] = $failCounts[$name] + 1
$count = $failCounts[$name]
Write-Log "$name 不健康(第 $count 次)"
if ($check.Type -eq "frontend") {
Write-Log "$name 重启计划任务 $FrontendTask"
Stop-ScheduledTask -TaskName $FrontendTask -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
Start-ScheduledTask -TaskName $FrontendTask -ErrorAction SilentlyContinue
Start-Sleep -Seconds 6
$healthy = Test-Http $check.Url
} elseif ($check.Type -eq "http") {
Write-Log "$name 重启 Compose 服务 $($check.Service)"
Invoke-Compose @("restart", $check.Service) | Out-Null
Start-Sleep -Seconds 12
$healthy = Test-Http $check.Url
if (-not $healthy) {
Write-Log "$name 重启后仍不健康,执行 compose up -d"
Invoke-Compose @("up", "-d", $check.Service) | Out-Null
}
} else {
Write-Log "$name 拉起容器 $($check.Container)"
docker start $check.Container 2>&1 | Out-Null
Start-Sleep -Seconds 5
$healthy = Test-Container $check.Container
if (-not $healthy) {
Write-Log "$name 启动失败,执行 compose up -d"
Invoke-Compose @("up", "-d", $check.Service) | Out-Null
}
}
# 连续失败达到上限 → 告警。计数会跨进程累积,所以只在首次达阈值和
# 之后每 30 轮(约 1 小时)提醒一次,避免每 2 分钟刷屏。
if (-not $healthy -and $count -ge $MaxRestarts -and
($count -eq $MaxRestarts -or $count % 30 -eq 0)) {
Send-Alert "服务异常" "$name 已连续 $count 次不健康,已尝试重启。请人工介入检查。"
Write-Log "$name 连续 $count 次失败,已发告警"
} elseif ($healthy) {
Write-Log "$name 已自动恢复"
}
}
}
# 磁盘检查:超过 85% 告警
$drive = (Get-PSDrive C -ErrorAction SilentlyContinue)
if ($drive) {
$pct = [math]::Round(($drive.Used / ($drive.Used + $drive.Free)) * 100)
if ($pct -gt 85) {
Write-Log "磁盘使用率 ${pct}%(超过 85%)"
Send-Alert "磁盘告警" "C 盘使用率 ${pct}%,请清理日志或扩容"
}
}
# 本轮结果落盘,供下一轮(2 分钟后的新进程)继续累加
Export-FailCounts $failCounts
+52 -3
View File
@@ -71,8 +71,16 @@ services:
env_file: .env env_file: .env
environment: environment:
SERVER_PORT: "8081" SERVER_PORT: "8081"
# 默认连编排里的 db;要连外部库就在 .env 里覆盖 DB_URL # 默认连编排里的 db;要连外部库就在 .env 里覆盖 DB_URL。
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}} # reWriteBatchedInserts=true:pgjdbc 把 JDBC 批内多条 INSERT 重写成多值
# INSERT,观看进度缓冲落库(watch:pg:dirty 消费任务)依赖它跑满吞吐。
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}?reWriteBatchedInserts=true}
# 限流/缓存用 Redis;容器内 127.0.0.1 是容器自身,必须指向编排里的 redis
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
# CORS:公网入口 nginx 把 SSL 跑在 80 端口上(腾讯云安全组只放 80),
# 浏览器 fetch 带 Origin 时端口不匹配会被 Spring CORS 拒(必须精确字符串匹配)。
CORS_ALLOWED_ORIGINS: "https://api.frostgiant.vip:80,https://api.frostgiant.vip,http://api.frostgiant.vip,https://39.162.50.99:8081,http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3007,http://192.168.31.250:3007"
ports: ports:
- "8081:8081" - "8081:8081"
volumes: volumes:
@@ -81,6 +89,8 @@ services:
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
redis:
condition: service_healthy
healthcheck: healthcheck:
test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8081/healthz || exit 1"] test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8081/healthz || exit 1"]
interval: 30s interval: 30s
@@ -101,11 +111,14 @@ services:
SERVER_PORT: "8080" SERVER_PORT: "8080"
SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE: "2GB" SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE: "2GB"
SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE: "2GB" SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE: "2GB"
CORS_ALLOWED_ORIGINS: "http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3005,http://192.168.31.250:3005" # 浏览后台时 Origin 是实际访问地址,必须精确列全:本机、局域网、公网 IP、域名。
CORS_ALLOWED_ORIGINS: "http://localhost:3005,http://127.0.0.1:3005,http://39.162.50.99:3005,http://192.168.31.250:3005,https://api.frostgiant.vip,https://admin.frostgiant.vip"
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}} DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
# 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名), # 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名),
# 因此这里不启用 /files/episode/** 的签名校验;公开的 app-api 仍保持开启。 # 因此这里不启用 /files/episode/** 的签名校验;公开的 app-api 仍保持开启。
FRUITSHORTS_MEDIA_PROTECTED_PREFIXES: "" FRUITSHORTS_MEDIA_PROTECTED_PREFIXES: ""
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
ports: ports:
# docs/12-上线检查清单「管理端仅内网」:只对局域网开放;不在路由器做端口转发,公网访问不到 # docs/12-上线检查清单「管理端仅内网」:只对局域网开放;不在路由器做端口转发,公网访问不到
- "8080:8080" - "8080:8080"
@@ -134,12 +147,16 @@ services:
env_file: .env env_file: .env
environment: environment:
DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}} DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
volumes: volumes:
# 与两个入口同一个媒资根,否则找不到源文件 # 与两个入口同一个媒资根,否则找不到源文件
- ./data/uploads:/data/uploads - ./data/uploads:/data/uploads
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
redis:
condition: service_healthy
healthcheck: healthcheck:
# worker 不监听端口(server.port=0),用进程存活判断 # worker 不监听端口(server.port=0),用进程存活判断
test: ["CMD-SHELL", "pgrep -f app.jar >/dev/null || exit 1"] test: ["CMD-SHELL", "pgrep -f app.jar >/dev/null || exit 1"]
@@ -186,9 +203,40 @@ services:
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin} GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Grafana 管理员密码必填,见 .env.example} GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Grafana 管理员密码必填,见 .env.example}
GF_USERS_ALLOW_SIGN_UP: "false" GF_USERS_ALLOW_SIGN_UP: "false"
# 新用户默认界面语言:简体中文
GF_USERS_LANGUAGE: "zh-Hans"
TZ: Asia/Shanghai TZ: Asia/Shanghai
depends_on: depends_on:
- prometheus - prometheus
- loki
# ─────────── 日志(Loki + Promtail)───────────
# Loki:日志存储与查询引擎;Promtail:采集容器 stdout/stderr 推给 Loki。
# Grafana 里通过 Loki 数据源可直接搜索/过滤各容器的请求日志。
loki:
image: grafana/loki:latest
container_name: fruitshorts-loki
restart: unless-stopped
command: -config.file=/etc/loki/local-config.yaml
volumes:
- ./loki-config.yml:/etc/loki/local-config.yaml:ro
- loki-data:/loki
expose:
- "3100"
# 镜像为 distroless(无 shell/wget),无法在容器内做 HTTP 探活;
# 靠 restart: unless-stopped 自动拉起,Grafana 数据源状态可反映可用性。
promtail:
image: grafana/promtail:latest
container_name: fruitshorts-promtail
restart: unless-stopped
command: -config.file=/etc/promtail/config.yml
volumes:
- ./promtail-config.yml:/etc/promtail/config.yml:ro
# 读取容器日志需要 Docker socket
- /var/run/docker.sock:/var/run/docker.sock:ro
depends_on:
- loki
# 黑盒探活:从外部探测接口可用性与耗时 # 黑盒探活:从外部探测接口可用性与耗时
blackbox: blackbox:
@@ -216,3 +264,4 @@ volumes:
redis-data: redis-data:
prometheus-data: prometheus-data:
grafana-data: grafana-data:
loki-data:
+613 -24
View File
@@ -115,6 +115,8 @@ POST /app/auth/register
| 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) | | 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) |
| 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) | | 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) |
| 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 | | 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 |
| 国家 / 语言 / 时区 / 币种 | 优先按客户端 IP(`X-Forwarded-For` / `X-Real-IP`,离线 ip2region)解析国家;内网或解析失败才用请求体 `countryCode`(ISO-2),最后兜底 `ID`。`language` / `timezone` / `currency` 随国家映射,不再写死 `id-ID` / `IDR` |
| 登录时修正国家 | `/app/auth/login`、`/app/auth/google` 会用 IP 重新解析国家并更新 `country_code` / `region_code`(历史账号下次登录即自愈);`language` / `timezone` / `currency` 只在仍是旧国家映射值时才同步,用户自己改过就保留 |
频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。 频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。
@@ -168,9 +170,30 @@ app.register.max-per-device-per-day
| GET | `/app/home/feed` | 首页:轮播 + 分区,卡片带 `preview` 可播预览集与 `language` 语种 | | GET | `/app/home/feed` | 首页:轮播 + 分区,卡片带 `preview` 可播预览集与 `language` 语种 |
| GET | `/app/discover/feed` | 发现页分区 | | GET | `/app/discover/feed` | 发现页分区 |
| GET | `/app/feed?types=ANIME,LIVE&categoryId=7&cursor=&size=20` | 推荐流;支持内容类型与分类叠加过滤,游标翻页 | | GET | `/app/feed?types=ANIME,LIVE&categoryId=7&cursor=&size=20` | 推荐流;支持内容类型与分类叠加过滤,游标翻页 |
| GET | `/app/categories` | 分类列表 | | GET | `/app/categories` | 已启用首页分类。名称在 `locales`;另带 `code`、`layoutType`(`GRID` / `RANKING`)、`revision` |
| GET | `/app/categories/{id}/dramas?pageIndex=&pageSize=` | 分类下已上线短剧,分页。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50 |
| GET | `/app/categories/{id}/ranking` | 推荐榜快照;只接受 `layoutType=RANKING` 的已启用分类,按后台位置返回连续排名 |
| GET | `/app/drama-categories` | 已启用类型。`locales` 为 `{zh,en,id}` |
| GET | `/app/tags` | 已启用标签。`locales` 为 `{zh,en,id}` |
| POST | `/app/dramas/page` | 全部短剧分页。请求体 `pageIndex`(默认 1)、`pageSize`(默认 20、最大 50)、`categoryIds`、`classificationIds`、`tagIds`。id 用 JSON 数组,不放查询串。同一组多选为或,组与组之间为且 |
| GET | `/app/playlists?pageIndex=&pageSize=` | 已启用剧单列表,分页。`pageIndex` 默认 1,`pageSize` 默认 10、最大 20 |
| GET | `/app/playlists/{id}?pageIndex=&pageSize=` | 剧单详情。短剧按页返回。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50。下架或不存在返回 `200002` |
| GET | `/app/dramas/{id}` | 详情(含剧集列表,免费集带**已签名**播放地址) | | GET | `/app/dramas/{id}` | 详情(含剧集列表,免费集带**已签名**播放地址) |
| GET | `/app/search?keyword=&pageIndex=&pageSize=` | 搜索已上线短剧:按标题/简介模糊匹配,分页返回卡片列表 | | GET | `/app/search?keyword=&pageIndex=&pageSize=` | **匿名**。搜索已上线短剧:按标题/简介模糊匹配,分页返回卡片列表 |
`POST /app/dramas/page` 请求体:
```json
{
"pageIndex": 1,
"pageSize": 20,
"categoryIds": ["2112443900437336065"],
"classificationIds": ["2112807182243336193"],
"tagIds": ["2113500000000000002"]
}
```
省略的 id 数组表示这一组不筛选。`pageIndex` 小于 1 按 1,`pageSize` 小于 1 按 1,大于 50 按 50。响应仍是 `{total, list}`,卡片结构与首页一致。
> 卡片(`AppDramaCardVO`)统一新增 `language` 字段(取值如 `zh-CN` / `id`), > 卡片(`AppDramaCardVO`)统一新增 `language` 字段(取值如 `zh-CN` / `id`),
> 首页、发现页、分类、收藏、搜索等所有下发卡片的场景都带该字段,客户端可据此做语言筛选。 > 首页、发现页、分类、收藏、搜索等所有下发卡片的场景都带该字段,客户端可据此做语言筛选。
@@ -180,9 +203,47 @@ app.register.max-per-device-per-day
> `drama_episode.like_count` 与 `content_comment.episode_id` 统计(排除逻辑删除与 `status = 'deleted'`); > `drama_episode.like_count` 与 `content_comment.episode_id` 统计(排除逻辑删除与 `status = 'deleted'`);
> `viewCount` 热度仍取整部剧。首页、发现、分类、收藏、搜索等列表卡片结构一致。 > `viewCount` 热度仍取整部剧。首页、发现、分类、收藏、搜索等列表卡片结构一致。
> >
> 卡片文案只放语言表:`titleLocales`、`synopsisLocales`、`types`、`tagLocales`。
> `tagColor` 是标签背景色。中文取各表的 `zh`。
>
> `tagCode` 是标签语义码(如 `NEW_ARRIVAL`),来自 `content_tag.code`。
> 客户端按码判断板块(推荐页「上新」横滑),`tagLocales` 只用于展示;
> 码为空时客户端才退回按文案匹配。后台标签管理可配置该码。
>
> 卡片新增 `dramaType`:`ANIME` 表示漫剧,`LIVE` 表示真人剧。 > 卡片新增 `dramaType`:`ANIME` 表示漫剧,`LIVE` 表示真人剧。
> 客户端字段仍返回主内容类型;后台多选值保存在 `drama.drama_types`, > 客户端字段仍返回主内容类型;后台多选值保存在 `drama.drama_types`,
> App 类型筛选按逗号列整词匹配,因此 `ANIME,LIVE` 多标签剧可被任一类型命中。 > App 类型筛选按逗号列整词匹配,因此 `ANIME,LIVE` 多标签剧可被任一类型命中。
>
> `GET /app/playlists` 与 `GET /app/playlists/{id}` 匿名可访问。列表返回 `{total, list}`。
> 列表项与详情的名称在 `locales`,描述在 `descriptionLocales`,key 为 `zh` / `en` / `id`。
> `name` 与 `description` 等于中文。客户端按当前语言取对应 key,没有则用 `zh`。
> 其余字段:`id`、`dramaCount`(已上线短剧条数),
> 列表里每条剧单的 `list` 只是短剧第 1 页、每页 10 条。短剧翻页走详情:
> `pageIndex`、`pageSize` 会原样回在详情里,`dramaCount` 是短剧总数,`list` 是当前页卡片。
> 只返回 `status = 1` 的剧单,排序与后台剧单排序一致,卡片顺序与后台关联顺序一致。
> 剧单列表越界页返回空 `list`,`total` 仍是全部剧单数。详情越界页同样返回空 `list`。
#### 推荐榜(`GET /app/categories/{id}/ranking`)
- 分类列表中的 `layoutType=RANKING` 表示客户端必须使用榜单布局,禁止按分类名称判断。
- 榜单内容与顺序以 `drama_classification_drama.position asc` 为准;客户端不得按播放量重新排序。
- 已下架、未发布或不存在的短剧会被过滤,剩余项目的 `rank` 从 1 连续补齐。
- 最多返回 50 部;`revision` 在后台保存内容或顺序后递增,供缓存与曝光埋点使用。
- 响应 `list` 项结构为 `{rank, drama}`,其中 `drama` 沿用 `AppDramaCardVO`。
```json
{
"id": "2112807182243336193",
"code": "RECOMMEND_RANKING",
"locales": {"zh": "推荐榜", "en": "Top Picks", "id": "Pilihan Teratas"},
"revision": "8",
"generatedAt": "2026-11-02T10:00:00",
"total": 1,
"list": [
{"rank": 1, "drama": {"id": "2112807182243336194", "titleLocales": {"zh": "短剧 A"}}}
]
}
```
#### 推荐类型流(`GET /app/feed`) #### 推荐类型流(`GET /app/feed`)
@@ -227,7 +288,8 @@ app.register.max-per-device-per-day
"unlockCoin": 0, "unlockCoin": 0,
"likeCount": "45", "likeCount": "45",
"commentCount": "8", "commentCount": "8",
"playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c..." "playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...",
"thumbnailsUrl": "/files/transcoded/88/thumbnails/thumbnails.vtt?e=1760000000&s=8a1d..."
} }
] ]
} }
@@ -244,6 +306,7 @@ app.register.max-per-device-per-day
| `viewCount` | Long(JSON 字符串) | 取 `drama.view_count`,累计播放量,既有字段语义不变 | | `viewCount` | Long(JSON 字符串) | 取 `drama.view_count`,累计播放量,既有字段语义不变 |
| `episodes[].likeCount` | Long(JSON 字符串) | 本集点赞数,取 `drama_episode.like_count` | | `episodes[].likeCount` | Long(JSON 字符串) | 本集点赞数,取 `drama_episode.like_count` |
| `episodes[].commentCount` | Long(JSON 字符串) | 本集未删除评论数,按 `episode_id` 统计 | | `episodes[].commentCount` | Long(JSON 字符串) | 本集未删除评论数,按 `episode_id` 统计 |
| `episodes[].thumbnailsUrl` | String / null | 本集雪碧图 WebVTT 时间轴签名地址;没有 READY 产物时为 `null` |
计数是只读快照:互动操作完成后客户端重新拉取详情即可刷新;`Long` 字段一律按字符串下发, 计数是只读快照:互动操作完成后客户端重新拉取详情即可刷新;`Long` 字段一律按字符串下发,
客户端需要转成数字再展示(与 `viewCount` 相同)。 客户端需要转成数字再展示(与 `viewCount` 相同)。
@@ -252,7 +315,8 @@ app.register.max-per-device-per-day
| 方法 | 路径 | 鉴权 | 说明 | | 方法 | 路径 | 鉴权 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| GET | `/app/episodes/{id}/play` | 可选 | 签发播放票据与签名地址 | | GET | `/app/episodes/{id}/play` | 免费集可选;锁定集必须登录 | 签发播放票据与签名地址 |
| GET | `/app/episodes/{id}/stats` | 可选 | 播放页轻量计数快照,不签发地址、不写票据缓存 |
```json ```json
{ {
@@ -262,7 +326,12 @@ app.register.max-per-device-per-day
"accessible": true, "accessible": true,
"accessType": "FREE", "accessType": "FREE",
"playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...", "playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...",
"qualities": ["AUTO"], "qualities": ["AUTO", "720p", "1080p"],
"tracks": [
{"quality": "AUTO", "playUrl": "/files/transcoded/88/master.m3u8?e=1760000000&s=9f2c..."},
{"quality": "720p", "playUrl": "/files/transcoded/88/720p/index.m3u8?e=1760000000&s=a1b2..."}
],
"thumbnailsUrl": "/files/transcoded/88/thumbnails/thumbnails.vtt?e=1760000000&s=8a1d...",
"unlockCoin": 0, "unlockCoin": 0,
"previewSeconds": 0, "previewSeconds": 0,
"likeCount": "45", "likeCount": "45",
@@ -271,28 +340,184 @@ app.register.max-per-device-per-day
} }
``` ```
`accessType` 取值:`FREE`(免费集)、`ENTITLED`(已购权益)、`COIN_REQUIRED`(需解锁, `accessType` 取值:`FREE`(免费集)、`ENTITLED`(已购权益)、`COIN_REQUIRED`(已登录但
此时 `playUrl` 为空、`unlockCoin` 有值)、`NO_MEDIA`(还没上传片源或未转码完成)。 尚未解锁,此时 `playUrl` 为空、`unlockCoin` 有值)、`NO_MEDIA`(已登录用户访问的剧集还
没上传片源或未转码完成)。未登录请求锁定集在查询片源前直接返回 `UNAUTHORIZED`,不会
按设备身份取票或降级为匿名播放。
**判定顺序由服务端决定,客户端不得自行推断可否播放。** 签名默认 15 分钟有效; **判定顺序由服务端决定,客户端不得自行推断可否播放。** 签名默认 15 分钟有效;
开启 `fruitshorts.media.signature-required` 后,`/files/episode/**` 没带有效签名会返回 403。 开启 `fruitshorts.media.signature-required` 后,`/files/episode/**` 没带有效签名会返回 403。
`thumbnailsUrl` 指向 WebVTT:cue 链接为同目录相对雪碧图
`sprite_XXX.jpg#xywh=x,y,w,h`。有 READY `media_thumbnail` 时返回签名地址,
无产物时为 `null`;该字段不影响 `playUrl`、`qualities` 和 HLS/原文件回落。
**`GET /app/episodes/{id}/stats`(播放页计数刷新)**
只读返回本集点赞数、本集未删除评论数、所属剧收藏数,以及当前用户对
本集/所属剧的互动状态。已登录时按账号读取;匿名请求时按 `X-Device-Id`
读取设备互动状态,未带设备号时 `liked`、`favorited` 均为 `false`。
接口不生成播放签名地址、不写 `playback_ticket` 缓存,计数变化后立即可读。
```json
{
"code": 0,
"message": "ok",
"data": {
"episodeId": "12",
"dramaId": "5",
"likeCount": "45",
"commentCount": "8",
"favoriteCount": "1800",
"liked": true,
"favorited": false
}
}
```
`likeCount`、`commentCount`、`favoriteCount` 与其他计数一样按 Long 字符串下发。
### 1.5 观看记录与收藏(已实现) ### 1.5 观看记录与收藏(已实现)
| 方法 | 路径 | 说明 | | 方法 | 路径 | 鉴权 | 说明 |
| --- | --- | --- | | --- | --- | --- | --- |
| POST | `/app/watch/progress` | 上报进度(建议每 10s 一次,切集时补一次) | | POST | `/app/watch/progress` | 可选登录 | 上报进度;匿名按 `X-Device-Id`,建议每 10s 一次,切集时补一次 |
| GET | `/app/watch/progress?dramaId=` | 某剧续看位置 | | GET | `/app/watch/progress?dramaId=` | 可选登录 | 某剧续看位置,匿名按设备读取 |
| GET | `/app/watch/recent?limit=20` | 最近观看 | | GET | `/app/watch/recent` | 可选登录 | 最近观看分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
| DELETE | `/app/watch/progress/{dramaId}` | 删除某剧记录 | | DELETE | `/app/watch/progress/{dramaId}` | 可选登录 | 删除当前账号或设备的某剧记录 |
| DELETE | `/app/watch/progress` | 清空记录 | | DELETE | `/app/watch/progress` | 可选登录 | 清空当前账号或设备的记录 |
| POST | `/app/favorites/toggle` | 收藏/取消收藏,返回切换后状态 | | POST | `/app/favorites/toggle` | 可选登录 | 收藏/取消收藏,返回切换后状态;匿名按 `X-Device-Id` |
| GET | `/app/favorites` | 收藏列表(卡片结构与首页一致) | | GET | `/app/favorites` | 可选登录 | 收藏分页;匿名按设备读取,`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
| DELETE | `/app/favorites/{dramaId}` | 取消收藏 | | DELETE | `/app/favorites/{dramaId}` | 可选登录 | 取消收藏;匿名按 `X-Device-Id` |
| POST | `/app/favorites/remove` | 可选登录 | 批量取消收藏;匿名按 `X-Device-Id`,返回实际删除数量 |
进度合并规则:同一集内只前进不后退;换集直接采纳新集;`finished` 只在接近片尾或客户端显式上报时置位。 进度合并规则:同一集内只前进不后退;换集直接采纳新集;`finished` 只在接近片尾或客户端显式上报时置位。
这样用户换设备不会看到进度倒退。 这样用户换设备不会看到进度倒退。
收藏与观看数据的身份解析顺序统一为登录 `userId` → `X-Device-Id` → 请求参数或请求体
`deviceId`,全部缺失时返回业务码 `200007`。匿名读取不按设备限流;上报、删除和清空等写操作
沿用设备级限流。登录或注册成功后,同一事务会把设备收藏、观看进度和观看流水合并到账号:
同一部剧的进度先比较集号,同集再比较播放位置,最后用更新时间兜底,只保留更靠前的一条;
观看流水按剧集去重并保留更靠后的位置。`playCount` 只取最终保留记录,不重复累加。
#### 批量取消收藏
`POST /app/favorites/remove`
```json
{
"dramaIds": ["12", "15"],
"deviceId": "optional-device-id"
}
```
| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `dramaIds` | array&lt;Long&gt; | 是 | 待取消的短剧 ID,最多 200 条,服务端去重后删除 |
| `deviceId` | string | 否 | 未登录且未携带 `X-Device-Id` 时的设备号兜底 |
身份解析优先登录用户,其次 `X-Device-Id`,最后请求体 `deviceId`。登录用户按
`user_id` 删除,匿名用户按 `device_id` 删除;匿名写操作沿用设备级限流。
所有删除和剧级收藏数回退在单一事务内完成,其中任一步失败会整体回滚。
响应 `data` 为实际删除的收藏关系数:
```json
{
"code": 0,
"message": "ok",
"data": 2
}
```
空列表返回业务码 `400`;超过 200 条同样返回 `400`。
#### 收藏分页
`GET /app/favorites?pageIndex=1&pageSize=20`
请求参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `pageIndex` | int | 否 | 1 | 页码,小于 1 按 1 处理 |
| `pageSize` | int | 否 | 20 | 每页数量,上限 100,小于 1 按 1 处理 |
响应 `data` 为 `PageResult<AppDramaCardVO>`:
```json
{
"total": "23",
"list": [
{
"id": "12",
"title": "替嫁新娘:总裁的掌心宠",
"cover": "/files/drama_cover/12.jpg",
"preview": {}
}
]
}
```
排序固定为收藏时间倒序 `created_at DESC`,收藏时间相同时按 `drama_id DESC`。
仅统计和返回仍处于已上线状态的短剧。
#### 最近观看分页
`GET /app/watch/recent?pageIndex=1&pageSize=20`
请求参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `pageIndex` | int | 否 | 1 | 页码,小于 1 按 1 处理 |
| `pageSize` | int | 否 | 20 | 每页数量,上限 100,小于 1 按 1 处理 |
分页响应 `data` 为 `PageResult<ProgressRespVO>`:
```json
{
"total": "18",
"list": [
{
"dramaId": "12",
"episodeId": "88",
"dramaTitle": "替嫁新娘:总裁的掌心宠",
"titleLocales": {
"zh": "替嫁新娘:总裁的掌心宠",
"en": "The Stand-in Bride: The CEO's Beloved",
"id": "Pengantin Pengganti: Kesayangan Presiden Direktur"
},
"dramaCover": "/files/drama_cover/12.jpg",
"dramaCoverLandscape": "/files/drama_cover/12-wide.jpg",
"episodeNumber": 6,
"totalEpisodes": 68,
"viewCount": "1800",
"positionMs": "80000",
"durationMs": "120000",
"finished": false,
"playCount": 3,
"updatedAt": "2026-10-22 10:00:00"
}
]
}
```
排序固定为 `updated_at DESC, id DESC`。每页记录通过批量 IN 查询装配短剧和分集,
不逐条访问数据库。越界页返回空 `list` 且 `total` 保持正确。
`ProgressRespVO` 展示字段:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `dramaTitle` | string / null | 短剧中文标题,旧客户端回退用 |
| `titleLocales` | object / null | 短剧标题语言表,key 为 `zh` / `en` / `id`。客户端按当前语言取,没有对应语言时回退 `zh` |
| `dramaCover` | string / null | 短剧竖版封面 |
| `dramaCoverLandscape` | string / null | 短剧横版封面,供继续观看横幅等横向位使用;为空时客户端回退 `dramaCover` |
| `episodeNumber` | int / null | 当前续看集号 `ep_no` |
| `totalEpisodes` | int / null | 短剧总集数 |
| `viewCount` | Long(JSON 字符串)/ null | 短剧热度,取 `drama.view_count`。`playCount` 是用户自己的播放次数 |
### 1.6 离线下载(已实现) ### 1.6 离线下载(已实现)
服务端只发**授权**与**短时效地址**,分片由客户端直接向 CDN 拉取 —— 服务端只发**授权**与**短时效地址**,分片由客户端直接向 CDN 拉取 ——
@@ -318,13 +543,22 @@ app.register.max-per-device-per-day
| 方法 | 路径 | 鉴权 | 说明 | | 方法 | 路径 | 鉴权 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| POST | `/app/comments` | 登录 | 发表评论/回复:过敏感词后按策略发布或转待审 | | POST | `/app/comments` | 可选登录 | 发表评论/回复;匿名按 `X-Device-Id`,过敏感词后按策略发布或转待审 |
| GET | `/app/comments?dramaId=&cursor=&size=` | 匿名 | 游标翻页;不传 `rootId` 返回顶层评论,传了返回该楼层回复 | | GET | `/app/comments?dramaId=&cursor=&size=` | 匿名 | 游标翻页;不传 `rootId` 返回顶层评论,传了返回该楼层回复 |
| GET | `/app/comments/count?dramaId=&episodeId=` | 匿名 | 传 `episodeId` 返回该集评论数;仅传 `dramaId` 返回全剧兼容汇总 | | GET | `/app/comments/count?dramaId=&episodeId=` | 匿名 | 传 `episodeId` 返回该集评论数;仅传 `dramaId` 返回全剧兼容汇总 |
| DELETE | `/app/comments/{id}` | 登录 | 删除自己的评论(逻辑置为 `deleted`) | | DELETE | `/app/comments/{id}` | 可选登录 | 删除自己的评论(匿名按设备);逻辑置为 `deleted` |
| POST | `/app/likes/toggle` | 登录 | 点赞/取消点赞,`targetType` 支持 `DRAMA` / `EPISODE` / `COMMENT`;新客户端点赞按集 | | POST | `/app/likes/toggle` | 可选登录 | 点赞/取消点赞,`targetType` 支持 `DRAMA` / `EPISODE` / `COMMENT`;匿名按 `X-Device-Id` |
| POST | `/app/reports` | 登录 | 举报评论/用户/短剧;同一目标只保留一条待处理工单 | | POST | `/app/reports` | 登录 | 举报评论/用户/短剧;同一目标只保留一条待处理工单 |
**非付费互动身份与合并**:点赞、收藏、评论的身份解析顺序为登录 `userId` →
`X-Device-Id` → 请求体 `deviceId`。三者都没有时返回业务码 `200007`。匿名写入按设备号
每分钟限流;评论同时做长度、空白、短时间重复内容和频率校验。登录或注册成功后,服务端
在同一登录事务内把该设备未归属的点赞、收藏、评论、观看进度和观看流水迁移到账号;
账号已有同内容时保留账号记录并删除设备重复记录,计数同步回退,不重复累加。
匿名评论展示为「游客」,头像为空占位。解锁、金币/VIP 权益、锁定集正片票据不在本规则内,
仍必须登录。
**敏感词三档处置**:`BLOCK` 直接拒绝并返回原因、`REPLACE` 替换后放行、`REVIEW` 转人工待审。 **敏感词三档处置**:`BLOCK` 直接拒绝并返回原因、`REPLACE` 替换后放行、`REVIEW` 转人工待审。
审核策略由 `fruitshorts.interaction.comment-audit-mode` 控制: 审核策略由 `fruitshorts.interaction.comment-audit-mode` 控制:
`MACHINE_FIRST`(机审通过即发布,当前默认)或 `PRE_REVIEW`(全部先审后发,生产建议)。 `MACHINE_FIRST`(机审通过即发布,当前默认)或 `PRE_REVIEW`(全部先审后发,生产建议)。
@@ -352,6 +586,53 @@ app.register.max-per-device-per-day
解锁后播放入口与下载入口会同时放行 —— 权益判定由交易模块的 `EntitlementPort` 实现提供, 解锁后播放入口与下载入口会同时放行 —— 权益判定由交易模块的 `EntitlementPort` 实现提供,
播放域与下载域都不需要改代码。金币变动一律带幂等键并写 `coin_ledger`,钱包余额与流水同事务。 播放域与下载域都不需要改代码。金币变动一律带幂等键并写 `coin_ledger`,钱包余额与流水同事务。
### 1.8.1 奖励中心(已实现)
奖励中心复用钱包和金币流水,首发时区固定为 `Asia/Jakarta`。任务配置、奖励金币、任务文案、动作、周期和上下线状态均由后台维护;客户端不能直接提交任务进度,观看进度由服务端在 `/app/watch/progress` 校验成功后累计。
| 方法 | 路径 | 鉴权 | 说明 |
| --- | --- | --- | --- |
| GET | `/app/rewards/overview` | 匿名 | 返回任务配置、任务分组、签到规则和活动卡片;未登录时余额为 `0`、用户进度为 `0`、签到状态为未签到;登录后补充用户数据;`locale` 可选 `id/en/zh` |
| GET | `/app/rewards/activities` | 匿名 | 返回当前生效活动卡片,活动一期只展示和跳转 |
| GET | `/app/rewards/check-in` | 登录 | 返回今日是否签到、连续天数、7 天规则 |
| POST | `/app/rewards/check-in` | 登录 | 按服务端日期和连续签到规则发放金币;同用户同日期幂等 |
| POST | `/app/rewards/tasks/{taskId}/claim` | 登录 | 领取已完成任务;同任务同周期幂等 |
总览响应核心字段:
```json
{
"serverDate": "2026-11-05",
"timezone": "Asia/Jakarta",
"coinBalance": "135",
"checkin": {
"taskId": "202611050001",
"checkedInToday": false,
"streak": 2,
"currentDay": 3,
"days": [{"dayIndex": 1, "rewardCoin": "35", "checked": true, "current": false}]
},
"sections": [{
"code": "DAILY",
"title": "Tugas harian",
"tasks": [{
"id": "202611050002",
"code": "watch_5_minutes",
"type": "WATCH_DURATION",
"progressValue": "120",
"targetValue": "300",
"rewardCoin": "20",
"status": "IN_PROGRESS"
}]
}],
"activities": []
}
```
一期任务类型为 `DAILY_CHECK_IN`、`WATCH_DURATION`、`WATCH_EPISODES`、`COMPLETE_PROFILE`、`FIRST_PURCHASE`;`FIRST_LOGIN` 预留给登录事件接入。任务状态为 `IN_PROGRESS`、`COMPLETED`、`CLAIMED`。奖励发放使用 `coin_ledger.biz_type=REWARD`,任务领取幂等键为 `reward:{taskCode}:{userId}:{cycleKey}`,签到幂等键为 `reward:checkin:{userId}:{date}`。重复请求返回既有发放结果,不重复增加钱包余额。
失败场景:任务未完成或已停用返回 `200003`;任务、签到规则不存在返回 `200002`;奖励金币为 0 或请求参数非法返回 `400`;钱包余额和发放单不一致时整笔事务回滚。
**`POST /app/orders/verify`(B1-1:Google Play 票据校验闭环)** **`POST /app/orders/verify`(B1-1:Google Play 票据校验闭环)**
请求体: 请求体:
@@ -428,6 +709,7 @@ B1-2 的退款/拒付复验依赖它。服务端凭据(`packageName` + service
| `noticeEnabled` | `app.notice.enabled` | `true` | 公告入口开关 | | `noticeEnabled` | `app.notice.enabled` | `true` | 公告入口开关 |
| `coinUnlockEnabled` | `app.coin.unlock.enabled` | `true` | 金币解锁开关 | | `coinUnlockEnabled` | `app.coin.unlock.enabled` | `true` | 金币解锁开关 |
| `downloadEnabled` | `app.download.enabled` | `true` | 离线下载开关 | | `downloadEnabled` | `app.download.enabled` | `true` | 离线下载开关 |
| `loginBackgroundUrl` | `app.login.background.url` | `""` | 登录页全屏海报背景;留空 App 用内置默认图。**建议尺寸 1170×2532**(iPhone 14 Pro Max 3× 整屏竖图),后台走 `/admin/media/upload/` 任意 bizType 上传后把返回的相对路径(`/files/login_bg/xxx.jpg`)写入即可 |
**口径**:**只下发上述白名单键**(服务端硬编码白名单),后台配置里的其它键(可能含内部开关) **口径**:**只下发上述白名单键**(服务端硬编码白名单),后台配置里的其它键(可能含内部开关)
**一律不下发**;库里缺键时用「契约默认值」兜底,**不返回 null 让客户端自己猜默认值**。 **一律不下发**;库里缺键时用「契约默认值」兜底,**不返回 null 让客户端自己猜默认值**。
@@ -460,6 +742,17 @@ GET /app/notices?pageIndex=1&pageSize=20
`expire_at` 为空或未过期的公告;按 `publish_at desc, id desc` 排序。 `expire_at` 为空或未过期的公告;按 `publish_at desc, id desc` 排序。
**表里没有数据时返回 `total=0, list=[]`(HTTP 与 code 都是成功),不是 404。** **表里没有数据时返回 `total=0, list=[]`(HTTP 与 code 都是成功),不是 404。**
#### 1.9.2a 协议公开页(匿名 HTML)
客户端按当前界面语言打开,不走 `{code,message,data}` 包装。正文在后台「协议设置」用 Markdown 维护,页面不另加标题。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/privacy/{lang}` | 隐私协议。`lang` 为 `zh` / `en` / `id` |
| GET | `/terms/{lang}` | 服务条款。语言同上 |
响应 `Content-Type: text/html;charset=UTF-8`。语言或路径不在上表时 HTTP 404。库里还没有该语言时返回内置缺省文案,不返回空页。
#### 1.9.3 `POST /app/creator/apply`(登录) #### 1.9.3 `POST /app/creator/apply`(登录)
```json ```json
@@ -521,6 +814,8 @@ GET /app/notices?pageIndex=1&pageSize=20
| 角色分类 | PUT · DELETE | `/admin/role-categories/{id}` | `system:role-category` | | 角色分类 | PUT · DELETE | `/admin/role-categories/{id}` | `system:role-category` |
| 系统配置 | GET | `/admin/configs` | `system:role` / `system:menu` | | 系统配置 | GET | `/admin/configs` | `system:role` / `system:menu` |
| 系统配置 | PUT | `/admin/configs` | `system:role` | | 系统配置 | PUT | `/admin/configs` | `system:role` |
| 协议 | GET | `/admin/legal-documents` | `system:role` / `system:menu` |
| 协议 | PUT | `/admin/legal-documents` | `system:role` |
| 操作日志 | GET | `/admin/operation-logs/page` · `/{id}` | `log:list` | | 操作日志 | GET | `/admin/operation-logs/page` · `/{id}` | `log:list` |
| 字典 | GET | `/admin/dicts/drama-category` · `/content-status` | `drama:list` | | 字典 | GET | `/admin/dicts/drama-category` · `/content-status` | `drama:list` |
@@ -553,6 +848,16 @@ GET /app/notices?pageIndex=1&pageSize=20
- 列表响应返回 `dramaTypes[]`、`categoryIds[]` 与按选中顺序映射的 `categoryNames[]`; - 列表响应返回 `dramaTypes[]`、`categoryIds[]` 与按选中顺序映射的 `categoryNames[]`;
分类名缺失时回退 `genre`。 分类名缺失时回退 `genre`。
- 后台与 App 过滤均使用 `(',' || column || ',') LIKE '%,value,%'` 整词匹配。 - 后台与 App 过滤均使用 `(',' || column || ',') LIKE '%,value,%'` 整词匹配。
- 短剧另有单选标签 `tagId`。不传保持原值,传 `0` 清空。列表返回 `tagId`、`tagName`、`tagNameEn`、`tagNameId`。后台编辑不再提交内容类型。
**标签**
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/content-tags?enabledOnly=` | `drama:list` | 标签列表。`enabledOnly=true` 只返回启用项 |
| POST | `/admin/content-tags` | `drama:create` | 新建。`locales` 勾选语言,中文必填,英文和印尼语可选 |
| PUT | `/admin/content-tags/{id}` | `drama:update` | 编辑 |
| DELETE | `/admin/content-tags/{id}` | `drama:delete` | 删除,并清空已选该标签的短剧 |
**剧集** **剧集**
@@ -597,19 +902,76 @@ GET /app/notices?pageIndex=1&pageSize=20
**上传会话归属**:`uploadId` 相当于上传凭证,`chunk` / `complete` / 进度查询都校验会话发起人, **上传会话归属**:`uploadId` 相当于上传凭证,`chunk` / `complete` / 进度查询都校验会话发起人,
别人拿到 `uploadId` 也塞不进分片(`{"code":403,"message":"无权操作该上传会话"}`)。 别人拿到 `uploadId` 也塞不进分片(`{"code":403,"message":"无权操作该上传会话"}`)。
**转码档位配置**
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/media/transcode-profile` | `episode:upload` | 读取当前配置;缺省返回四档默认值 |
| PUT | `/admin/media/transcode-profile` | `episode:upload` | 保存配置并记录操作日志 |
配置保存在 `sys_config` 的 `media.transcode.profile`,JSON 结构:
```json
{
"enabled": true,
"segmentSeconds": 6,
"ladder": [
{
"quality": "360p",
"width": 640,
"height": 360,
"videoBitrateKbps": 400,
"audioBitrateKbps": 64,
"enabled": true
}
],
"sprite": {
"enabled": true,
"intervalSeconds": 1,
"columns": 10,
"thumbWidth": 160
}
}
```
`quality` 必须唯一且非空,宽高必须为大于 0 的偶数,音视频码率必须大于 0,
至少启用一档;`segmentSeconds` 2–10、`intervalSeconds` 1–10、`columns` 5–20、
`thumbWidth` 120–240。非法请求返回统一错误码 `400` 且不写库。
### 2.3 App 用户管理(已实现) ### 2.3 App 用户管理(已实现)
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource | | GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource、platform(ANDROID/IOS,按用户**最近一次**会话平台筛选) |
| GET | `/admin/app-users/{id}` | `app-user:list` | 详情 | | GET | `/admin/app-users/{id}` | `app-user:list` | 详情 |
| GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 | | GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 |
| GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) | | GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) |
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime | | GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime、platform(ANDROID/IOS,按**最近一次会话**) |
| GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
| PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned | | PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned |
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。 状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
收藏和点赞分页参数:`pageIndex` 默认 1,`pageSize` 默认 10、最大 100;
`keyword` 模糊匹配 uid/昵称,`userId`、`deviceId`、`dramaId` 精确匹配,
`dramaTitle` 模糊匹配;`startTime/endTime` 按创建时间闭区间过滤,
格式 `yyyy-MM-dd HH:mm:ss`。点赞另支持 `targetType`(DRAMA/EPISODE/COMMENT)、
`targetId` 和 `episodeId` 精确过滤,短剧和剧集过滤会解析评论及剧集所属关系。
按 `createdAt DESC, id DESC` 排序,用户/短剧预检索无结果返回 total=0、list=[]。
点赞的三种目标语义:客户端点赞按钮作用于当前播放剧集,落库为 `targetType=EPISODE`;
`DRAMA` 是早期按整部剧点赞的历史数据;`COMMENT` 为评论点赞。筛选行为:
`dramaTitle` / `dramaId` 同时命中「该剧本身的点赞」与「该剧下各集的点赞」,
`episodeId` 只命中「该集本身的点赞」与该集下的评论点赞,**不包含对短剧本身的点赞**;
不传 `episodeId` 时不受此限制。
收藏行字段:`id,userId,uid,nickname,deviceId,anonymous,dramaId,dramaTitle,dramaCover,
dramaStatus,dramaPublished,createdAt`。点赞行字段:`id,userId,uid,nickname,deviceId,
anonymous,targetType,targetId,dramaId,dramaTitle,dramaCover,episodeId,episodeNo,episodeTitle,
commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评论摘要最多 30 字。
关联资料逻辑删除后展示字段为空,不排除原始互动记录。
### 2.4 下载管理(已实现) ### 2.4 下载管理(已实现)
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
@@ -688,6 +1050,7 @@ GET /app/notices?pageIndex=1&pageSize=20
| --- | --- | --- | --- | | --- | --- | --- | --- |
| GET | `/admin/dashboard/overview` | `dashboard:view` | 总览:用户 / 内容 / 播放 / 收入 / 成本 | | GET | `/admin/dashboard/overview` | `dashboard:view` | 总览:用户 / 内容 / 播放 / 收入 / 成本 |
| GET | `/admin/dashboard/transcode` | `dashboard:view` | 转码队列积压与失败任务明细(含 `errorMsg` / `retryCount`) | | GET | `/admin/dashboard/transcode` | `dashboard:view` | 转码队列积压与失败任务明细(含 `errorMsg` / `retryCount`) |
| GET | `/admin/notifications/transcode` | `drama:list` | 转码通知:`running` / `success` / `failed` 角标,以及各状态最近 20 条(含 `dramaTitle`、`episodeNo`、`episodeTitle`) |
**口径(与代码注释一致,前端 tooltip 可直接复用)** **口径(与代码注释一致,前端 tooltip 可直接复用)**
@@ -695,6 +1058,8 @@ GET /app/notices?pageIndex=1&pageSize=20
| --- | --- | --- | | --- | --- | --- |
| 用户 | `total` / `newToday` / `new7d` | `app_user` 未删除总数;按 `created_at` 落在当天 / 近 7 天 | | 用户 | `total` / `newToday` / `new7d` | `app_user` 未删除总数;按 `created_at` 落在当天 / 近 7 天 |
| 用户 | `active7d` | `last_login_at` 在近 7 天内。**不是 DAU**,日活需要逐日登录快照,当前无产出 | | 用户 | `active7d` | `last_login_at` 在近 7 天内。**不是 DAU**,日活需要逐日登录快照,当前无产出 |
| 用户 | `androidActive7d` / `iosActive7d` | `app_user_device` 中 `status=active` 且 `last_seen_at` 在近 7 天的去重设备,平台分别为 `ANDROID` / `IOS` |
| 用户 | `retention1d` / `retention7d` | 次日留存:昨日注册且今天仍登录的比例。7 日留存:8 至 14 天前注册、近 7 天仍登录的比例。队列为空返回 `null`,取值 0 到 1 |
| 用户 | `banned` / `limited` / `deactivated` | 按 `status` 计数 | | 用户 | `banned` / `limited` / `deactivated` | 按 `status` 计数 |
| 内容 | `drama*` | 短剧按 `status` 计数(`reviewing` 为待审、`published` 为已上线) | | 内容 | `drama*` | 短剧按 `status` 计数(`reviewing` 为待审、`published` 为已上线) |
| 内容 | `episodeTotal` / `Published` / `WithMedia` | 剧集总数 / 已上线数 / `video_url` 非空数(均排除逻辑删除) | | 内容 | `episodeTotal` / `Published` / `WithMedia` | 剧集总数 / 已上线数 / `video_url` 非空数(均排除逻辑删除) |
@@ -811,8 +1176,9 @@ GET /app/notices?pageIndex=1&pageSize=20
只接受 `bizType=EPISODE` 且状态为 `ready` / `uploaded` 的产物。 只接受 `bizType=EPISODE` 且状态为 `ready` / `uploaded` 的产物。
**收费配置**:`previewSeconds` 落在 `drama_episode.preview_seconds`(0 = 不限制), **收费配置**:`previewSeconds` 落在 `drama_episode.preview_seconds`(0 = 不限制),
与 `is_free` / `unlock_coin` 一起就是播放与下载付费判定读的字段,**改完立即生效**(实测:未登录请求付费集返回 与 `is_free` / `unlock_coin` 一起就是播放与下载付费判定读的字段,**改完立即生效**(实测:未登录请求锁定集直接
`{"accessType":"COIN_REQUIRED","unlockCoin":50,"previewSeconds":15}`;免费集直接返回签名播放地址)。 返回 `UNAUTHORIZED`;已登录未解锁用户返回 `{"accessType":"COIN_REQUIRED","unlockCoin":50,"previewSeconds":15}`;
免费集直接返回签名播放地址)。
定价沿用「可编辑状态」口径:`draft` / `offline` 可改,已上线要改价需先申请下线(避免创作者悄悄改已上线内容的价格); 定价沿用「可编辑状态」口径:`draft` / `offline` 可改,已上线要改价需先申请下线(避免创作者悄悄改已上线内容的价格);
`dramaId` 以路径为准,body 里传别人的剧 id 无效,列表里带别人的 `episodeId` 会被忽略(只作用于自己剧的分集)。 `dramaId` 以路径为准,body 里传别人的剧 id 无效,列表里带别人的 `episodeId` 会被忽略(只作用于自己剧的分集)。
@@ -914,6 +1280,24 @@ GET /app/notices?pageIndex=1&pageSize=20
> `id` 以字符串下发:见 **§0「ID 字段一律以字符串下发」**(本节不再单独规定)。 > `id` 以字符串下发:见 **§0「ID 字段一律以字符串下发」**(本节不再单独规定)。
### 2.11.1 奖励中心管理(已实现)
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/rewards/tasks/page` · `/tasks/{id}` | `reward:list` | 奖励任务分页与详情 |
| POST | `/admin/rewards/tasks` | `reward:update` | 新建任务,默认下线 |
| PUT | `/admin/rewards/tasks/{id}` · `/{id}/status` | `reward:update` | 编辑、上线 / 下线;编辑会递增版本 |
| GET | `/admin/rewards/activities/page` · `/activities/{id}` | `reward:list` | 奖励活动分页与详情 |
| POST | `/admin/rewards/activities` | `reward:update` | 新建活动,默认下线 |
| PUT | `/admin/rewards/activities/{id}` · `/{id}/status` | `reward:update` | 编辑、上线 / 下线 |
| GET · PUT | `/admin/rewards/check-in/rules` | `reward:checkin` | 查看 / 保存签到每日奖励规则,天数不能重复 |
| GET | `/admin/rewards/grants/page` | `reward:grant` | 用户、任务、来源、状态筛选发放记录 |
| POST | `/admin/rewards/grants/manual` | `reward:grant` | 人工补发;仍写 `REWARD` 钱包流水并要求幂等键 |
后台任务保存字段包括 `code`、`sectionCode`、`type`、`verifyMode`、`targetValue`、`rewardCoin`、`cycleType`、`cycleLimit`、三语言文案、动作、排序和生效时间。任务配置不允许后台写任意脚本,扩展字段只能放在 `configJson`。
后台活动保存字段包括 `code`、`coverUrl`、`actionType`、`actionUrl`、三语言标题、三语言摘要、三语言按钮文案、排序和生效时间。活动与任务共用 `reward:update` 权限,新建活动默认下线。
**校验与错误码**: **校验与错误码**:
| 场景 | 结果 | | 场景 | 结果 |
@@ -955,6 +1339,211 @@ GET /app/notices?pageIndex=1&pageSize=20
**筛选与错误码**:`title` 必填(1–128);`content` 最长 2000;公告不存在 → `200002 公告不存在`; **筛选与错误码**:`title` 必填(1–128);`content` 最长 2000;公告不存在 → `200002 公告不存在`;
`status` 只接受 0/1,其他值 → `400`。 `status` 只接受 0/1,其他值 → `400`。
### 2.13 运营分类管理(已实现)
> 「分类」是运营自定义的分组,与短剧**类型**(`/admin/drama-categories`,写 `drama_category`)是两套独立概念。
> 分类存在 `drama_classification`,通过 `drama_classification_drama` 关联任意多部短剧。
> 后台页面:菜单 **分类管理**(`/content/category-dramas` → `CategoryDramaView.vue`)。
**接口清单**(前缀 `/admin/drama-classifications`)
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/drama-classifications` | `drama:list` | 分类列表(带关联短剧数量) |
| POST | `/admin/drama-classifications` | `drama:create` | 新建分类,返回新分类 id |
| PUT | `/admin/drama-classifications/{id}` | `drama:update` | 编辑分类 |
| DELETE | `/admin/drama-classifications/{id}` | `drama:delete` | 删除分类(级联删关联,短剧本身保留) |
| GET | `/admin/drama-classifications/{id}/dramas` | `drama:list` | 分类下已关联的短剧(分页) |
| GET | `/admin/drama-classifications/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
| POST | `/admin/drama-classifications/{id}/dramas` | `drama:update` | 批量关联短剧,返回实际新增数量 |
| DELETE | `/admin/drama-classifications/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
| PUT | `/admin/drama-classifications/{id}/ranking-items` | `drama:update` | 原子保存推荐榜完整顺序,最多 50 部;空数组表示清空 |
**列表响应**
```json
{
"code": 0,
"message": "ok",
"data": [
{
"id": "2112807182243336193",
"name": "本周必看",
"code": "CLASSIFICATION_2112807182243336193",
"layoutType": "GRID",
"revision": "1",
"sort": 1,
"status": 1,
"dramaCount": 12,
"updatedAt": "2026-10-22T19:41:02"
}
]
}
```
排序规则固定为 `sort asc, id desc`;`dramaCount` 是关联表按分类聚合的实时数量。
时间字段为 `LocalDateTime` 的 ISO 字符串(`yyyy-MM-ddTHH:mm:ss`,秒级),前端按需替换 `T` 为空格。
**新建 / 编辑请求体**
```json
{
"name": "推荐榜",
"code": "RECOMMEND_RANKING",
"layoutType": "RANKING",
"sort": 1,
"status": 1
}
```
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写分类名称」 |
| `code` | 否 | 稳定语义码,只允许大写字母、数字、下划线;不传时生成 `CLASSIFICATION_{id}` |
| `layoutType` | 否 | `GRID` 普通分类 / `RANKING` 推荐榜;默认 `GRID` |
| `sort` | 否 | 新建不传时取 `现有条数 + 1`;编辑不传(null)时保持原值 |
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1`,编辑不传保持原值 |
**关联短剧**
```json
POST /admin/drama-classifications/2112807182243336193/dramas
{ "dramaIds": ["2112807182243336194", "2112807182243336195"] }
```
返回 `data` 为实际新增条数(整数)。已关联的、以及不存在的 `dramaId` 会被静默跳过,不报错;
全部跳过时返回 `0`。`dramaIds` 为空数组 → `400 请选择短剧`。
推荐榜应使用 `PUT /{id}/ranking-items` 一次提交完整有序 `dramaIds`。接口会去重、校验短剧存在,
按数组顺序写入 `position=1..N` 并递增分类 `revision`;`dramaIds` 必须显式传数组,空数组表示清空。
普通分类调用该接口返回 `200003`;推荐榜调用旧的 `POST /{id}/dramas` 或
`DELETE /{id}/dramas/{dramaId}` 同样返回 `200003`,防止绕过版本与排序更新。
**短剧列表项(`GET /{id}/dramas` 与 `/dramas/candidates` 共用)**
```json
{
"total": 12,
"list": [
{
"id": "2112807182243336194",
"title": "闪婚后首富老公竟是我老板",
"cover": "https://.../cover.jpg",
"status": "published",
"totalEpisodes": 80,
"sort": 100,
"updatedAt": "2026-10-22T18:00:00"
}
]
}
```
- 查询参数:`keyword`(按 `title` 模糊匹配,可空)、`pageIndex`(默认 1)、`pageSize`(默认 10,上限 100)
- 排序:`sort desc, id desc`
- `status` 取值:`draft` 草稿 / `reviewing` 审核中 / `approved` 待发布 / `published` 已上线 / `offline` 已下线
- `cover` 取自短剧 `cover_url`
**错误码**
| 场景 | 返回 |
| --- | --- |
| 分类名称重复(新建或改名撞已有) | `200001 分类名称已存在` |
| 分类 id 不存在(编辑/删除/查询/关联/移出) | `200002 分类不存在` |
| `name` 为空 | `400 请填写分类名称` |
| `dramaIds` 为空 | `400 请选择短剧` |
> 所有写操作带 `@OperationLog(module = "内容管理")` 操作日志。ID 下发口径见 **§0**。
### 2.14 剧单管理(已实现)
> 剧单使用**自己的一套分类**(`drama_playlist_category`),与「分类管理」和「类型」都没有关系。
> **没有「剧单」这一层实体**:分类直接挂短剧,关联表 `drama_playlist_category_drama(category_id, drama_id)`。
> 后台页面:菜单 **剧单管理**(`/content/drama-playlists` → `DramaPlaylistView.vue`)。
**接口清单**(前缀 `/admin/drama-playlist-categories`)
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/drama-playlist-categories` | `drama:list` | 剧单分类列表(带短剧数量) |
| POST | `/admin/drama-playlist-categories` | `drama:create` | 新建剧单分类,返回新分类 id |
| PUT | `/admin/drama-playlist-categories/{id}` | `drama:update` | 编辑剧单分类 |
| DELETE | `/admin/drama-playlist-categories/{id}` | `drama:delete` | 删除剧单分类(级联删关联,短剧本身保留) |
| GET | `/admin/drama-playlist-categories/{id}/dramas` | `drama:list` | 分类下已关联的短剧(分页) |
| GET | `/admin/drama-playlist-categories/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
| POST | `/admin/drama-playlist-categories/{id}/dramas` | `drama:update` | 批量把短剧加入分类,返回实际新增数量 |
| DELETE | `/admin/drama-playlist-categories/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
**列表响应**
```json
{
"code": 0,
"message": "ok",
"data": [
{
"id": "2112807182243336196",
"name": "高甜先婚后爱",
"description": "站内投放位使用,按周更新",
"sort": 1,
"status": 1,
"dramaCount": 8
}
]
}
```
排序规则 `sort asc, id desc`;`dramaCount` 为该分类下已关联短剧数量。
**新建 / 编辑请求体**
```json
{
"name": "高甜先婚后爱",
"description": "站内投放位使用,按周更新",
"sort": 1,
"status": 1
}
```
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写剧单分类名称」 |
| `description` | 否 | 最长 255 字符(超长 → `400 描述最多 255 个字符`);新建不传存空串,编辑不传保持原值 |
| `sort` | 否 | 新建不传取 `现有条数 + 1`;编辑不传保持原值 |
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1` |
**关联短剧**
```json
POST /admin/drama-playlist-categories/2112807182243336196/dramas
{ "dramaIds": ["2112807182243336194"] }
```
返回实际新增条数;已关联或不存在的短剧自动跳过;`dramaIds` 为空 → `400 请选择短剧`。
`GET /{id}/dramas` 与 `GET /{id}/dramas/candidates` 的查询参数和响应结构与 **§2.13** 完全一致
(`keyword` / `pageIndex` / `pageSize`,响应 `{ total, list }`,列表项含
`id` / `title` / `cover` / `status` / `totalEpisodes` / `sort` / `updatedAt`)。
**错误码**
| 场景 | 返回 |
| --- | --- |
| 剧单分类名称重复 | `200001 剧单分类名称已存在` |
| 剧单分类 id 不存在 | `200002 剧单分类不存在` |
| `name` 为空 | `400 请填写剧单分类名称` |
| `description` 超过 255 | `400 描述最多 255 个字符` |
| `dramaIds` 为空 | `400 请选择短剧` |
**与「分类管理」的差异**
| 项 | 运营分类(2.13) | 剧单分类(2.14) |
| --- | --- | --- |
| 数据表 | `drama_classification` + `drama_classification_drama` | `drama_playlist_category` + `drama_playlist_category_drama` |
| 描述字段 | 无 | 有(`description`,≤255) |
| 列表返回 | 含 `updatedAt` | 含 `description`,不含 `updatedAt` |
| 菜单 | 分类管理(`/content/category-dramas`) | 剧单管理(`/content/drama-playlists`) |
| 用途 | 内容侧分组 | 运营侧投放/剧单位分组 |
## 3. 契约与实现状态对照 ## 3. 契约与实现状态对照
> 最后更新:2026-10-16(`develop` 分支)。未完成项汇总见仓库根 `README.md`「尚未完成」。 > 最后更新:2026-10-16(`develop` 分支)。未完成项汇总见仓库根 `README.md`「尚未完成」。
@@ -0,0 +1,24 @@
# 客户端收藏与观看历史分页
## 目标
- `/app/favorites` 改为 `PageResult<AppDramaCardVO>`,默认第 1 页、每页 20,最大 100。
- `/app/watch/recent` 默认返回 `PageResult<ProgressRespVO>`;请求带 `limit` 时保留一版旧
`List<ProgressRespVO>` 响应。
- 观看历史补充短剧标题、封面、集号和总集数,剧/集均批量查询。
## 实现步骤
1. 收藏关系使用 `selectPage`,按 `created_at DESC, drama_id DESC` 稳定排序;
只统计已上线短剧收藏,再按当前页 ID 批量加载短剧。
2. 观看进度使用 `selectPage`,按 `updated_at DESC, drama_id DESC` 稳定排序。
3. 当前页的 dramaId / episodeId 去重排序后,分别执行一次 IN 查询并装配展示字段。
4. Controller 归一化 pageIndex/pageSize;观看历史根据是否传 `limit` 分流新旧响应。
5. 更新 API 契约 §1.5,补 service/controller 测试。
## 风险与约束
- `limit` 分支仅用于旧客户端兼容,新分页响应与旧 List 响应不能混用。
- 已下线短剧不计入收藏 total,也不出现在收藏页。
- 观看历史展示字段找不到对应剧或集时保持 null,不影响历史记录返回。
- 不修改客户端、不改表结构、不启停服务、不操作真机。
@@ -0,0 +1,38 @@
# 转码产物查询接口
## 目标
- 媒体维度查询 rendition 与帧图产物。
- 分集维度聚合转码任务、rendition、帧图状态。
- `/admin/dashboard/transcode` 改为明确 VO,OpenAPI 不再出现匿名 Object。
## 设计
1. `MediaTranscodeOutputService` 统一读取媒体、任务、rendition 与 thumbnail。
2. rendition 按高度、视频码率、质量倒序,id 正序保证稳定。
3. thumbnail 优先读取 `thumbnails.vtt`,解析 cue 后分页;无记录返回 `EMPTY`,
记录失败返回 `FAILED`,不把缺产物当服务错误。
4. 分集聚合对不存在、无视频、无媒资、无任务返回明确 status 和空列表。
5. dashboard 使用强类型 queue/failed task VO,保留现有字段语义并补 total。
## 接口
- `GET /admin/media/{id}/renditions`
- `GET /admin/media/{id}/thumbnails?pageIndex=1&pageSize=100`
- `GET /admin/episodes/{id}/transcode`
- `GET /admin/dashboard/transcode`(响应类型由 Map 收敛为 VO)
缩略图响应内嵌 `PageResult<MediaThumbnailFrameVO>`,同时返回 sprite/VTT 元数据;
空产物 status 为 `EMPTY`,无绑定分集为 `NO_EPISODE`,损坏 VTT 为 `INVALID`。
## TDD
- 先提交媒体有/无产物、不存在、VTT 解析与分页边界测试。
- 再提交接口、VO、聚合服务和 dashboard 类型收敛实现。
- 门禁:`mvn -pl fruitshorts-module-media test`。
## 红线
- 不改 `/app` 契约、specs、ReelShortWeb、Flutter。
- 不改 P1 入队与手动重转逻辑。
- 不启停服务,不操作真机。
@@ -0,0 +1,40 @@
# 后台转码链路打通
## 现状取证
- 上传完成时 `MediaService.complete` 已为视频调用 `TranscodeService.enqueue`。
- 分集创建/替换视频地址时 `EpisodeService` 已调用
`EpisodeTranscodeBindingService.bind`,会复用并绑定同一媒体的未完成任务。
- 转码失败原因已写入 `transcode_task.error_msg`,最终状态写入 `status`。
- 缺口是后台手动触发/重转接口,以及对应幂等和链路测试。
## 实现
1. 保留上传完成和改片自动入队逻辑,补测试锁定行为。
2. `TranscodeService` 增加手动触发:
- QUEUED/RUNNING 直接返回现有任务;
- FAILED 重置原任务为 QUEUED;
- SUCCESS 才创建新任务,紧接着重复触发会复用新 QUEUED 任务。
3. 新增 `POST /admin/media/{id}/transcode`,校验媒资存在,复用 `episode:upload`。
4. 返回任务 id 与状态,便于后台提示。
实现时对同一媒资行使用 `FOR UPDATE`,让重复请求在事务内串行判定;
平台不存在的媒资保持 `DATA_NOT_FOUND`,不产生任务或 500。
## TDD 测试矩阵
| 场景 | 断言 |
| --- | --- |
| 视频上传完成 | `MediaService.complete` 调用一次 `enqueue(assetId, 0, 0, sourceUrl)` |
| 图片上传完成 | 不创建转码任务 |
| 手动触发成功媒资 | 新建一个 QUEUED 任务,重复调用复用同一任务 |
| 手动触发进行中媒资 | 直接返回 QUEUED/RUNNING 任务,不新增记录 |
| 手动触发失败媒资 | 原任务重置为 QUEUED,保留任务 id |
| 媒资不存在 | 返回既有 `DATA_NOT_FOUND`,控制器不产生 500 |
| worker 最终失败 | 任务状态 FAILED,`error_msg` 保留 ffmpeg 原因 |
## 验证
- 先提交失败测试,再提交实现。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`
- 不启停任何服务,不执行数据库变更,不改 Web/Flutter/specs/API 文档。
@@ -0,0 +1,53 @@
# 转码档位配置、雪碧图与播放缩略图轴
## 目标
1. 后台可配置转码档位与雪碧图参数,worker 对之后的新任务在 30 秒内自动生效。
2. 转码成功后生成雪碧图与 VTT,登记到 `media_thumbnail`。
3. 播放接口与详情剧集返回 `thumbnailsUrl`,无产物时为 `null`。
## 配置模型
- `sys_config.config_key = media.transcode.profile`,值为 JSON。
- 配置包含总开关、分片秒数、码率阶梯与雪碧图参数。
- 缺省配置等价于现有 360p/480p/720p/1080p 四档。
- 后台 GET 缺省或历史配置非法时返回 yml 等价默认值;PUT 非法时返回统一 400,且不写库。
- worker 读取配置缓存 30 秒;缺省、解析失败或校验失败时回退 yml 默认阶梯。
## 权限取舍
现有权限点没有 `media:transcode`。本次两个接口复用最小可用的
`episode:upload`,避免新增权限点导致已有角色需要补授权;不新增菜单或权限 SQL。
## 数据与产物
- 新增 `media_thumbnail`,按 `episode_id` 唯一,记录 VTT、雪碧图前缀、采样参数、
尺寸、帧数、时长、状态、错误与总大小。
- 雪碧图目录固定在 `transcoded/{taskId}/thumbnails/`:
`thumbnails.vtt` + `sprite_001.jpg` 等多张图。
- VTT cue 链接使用相对路径 `sprite_XXX.jpg#xywh=x,y,w,h`,同一 VTT 目录下可直接解析。
- 缩略图失败只把 `media_thumbnail.status` 置 `FAILED` 并记录错误;主 HLS 仍成功。
## 播放
- `PlayRespVO` 和 `AppEpisodeVO` 增加 `thumbnailsUrl`。
- 查询 `media_thumbnail` 仅读取 `READY` 产物;objectKey 经
`MediaStorageService.toPublicUrl` 后使用现有 `PlaybackSigner` 签名。
- 详情剧集列表批量查询缩略图,禁止 N+1。
- 不改变现有 HLS/原文件回落与 qualities 列表。
## 测试
- worker:配置解析、非法配置回退 yml、30 秒缓存、VTT 坐标、多雪碧图索引、
缩略图失败不阻断主转码。
- admin:GET 默认值、PUT 非法不落库、PUT 成功落库。
- playback:有 READY 缩略图返回签名 `thumbnailsUrl`,无产物返回 `null`。
- 门禁:`mvn -pl fruitshorts-transcode-worker,fruitshorts-admin-api,fruitshorts-app-api -am test`。
## 风险 / 边界
- 本次只对合并后的新转码任务生效,不回跑历史任务。
- 配置中的顶层 `enabled` 会持久化并返回;本单不改变既有队列消费开关语义,
worker 仍以 `worker-enabled` 决定是否消费任务。
- 雪碧图生成依赖 ffmpeg `tile` 滤镜;真实产物由 worker 门禁和 PM 后续环境验收,
本任务不启动服务、不改客户端。
@@ -0,0 +1,38 @@
# 转码分集绑定与运行态修复
## 已确认现场
admin-api/app-api/worker 均运行旧包;worker 未运行;`media_thumbnail` 表缺失;
新上传任务 drama_id/episode_id 为 0;旧 worker jar 缺 MediaThumbnail。
## 代码修复
1. 分集保存后按视频 URL 的 objectKey 查找 `media_asset`。
2. media 域新增绑定服务:
- 将 dramaId/episodeId 回填到对应 `transcode_task`;
- QUeued/RUNNING/SUCCESS 任务复用,不重复入队;
- FAILED/CANCELED 或不存在时新建任务;
- 已成功但 episodeId=0 的 rendition 同步回填。
3. `claimNext` 只认领 `episode_id > 0`,零绑定任务保留 QUEUED。
4. 缩略图登记使用 REQUIRES_NEW 独立事务;生成或登记失败只记 warn/error_msg,
主任务仍 SUCCESS。
5. 对 episode_id=0 且源文件不存在的明显测试垃圾标记 CANCELED,不删除。
## 迁移与运行
1. 确认 `media_thumbnail` 不存在后执行幂等 patch。
2. `mvn -DskipTests package` 全量重建。
3. 检查三个 jar 分别含:
- admin-api:MediaTranscodeProfile;
- app-api:PlayRespVO.thumbnailsUrl 对应新类;
- worker:MediaThumbnail / MediaThumbnailMapper。
4. 重启 8080/8081/worker,日志写 `logs/*.log`。
5. 冒烟 admin 配置、App 详情 thumbnailsUrl、worker 轮询。
6. 上传真实视频,创建绑定分集,等待 worker 消费,验证任务、四档 HLS、
media_thumbnail、VTT 与 sprite HTTP 200。
## 风险
- 旧 QUEUED 中无法绑定且源文件不存在的测试任务将被取消并记录 id。
- 真实视频端到端验证会写入运行数据库和媒资目录。
- 不修改 Web/Flutter,不操作真机。
@@ -0,0 +1,24 @@
# 转码任务认领与媒资 ID 校验
## 现场结论
- `media_asset.id=21` 确实存在,source_url 对应分集 id=13。
- 分集 13 的 video_asset_id=0,旧手动触发只拿媒资,不知道分集绑定,
因而创建了 media_asset_id=21、episode_id=0 的 QUEUED 任务。
- claim 只筛选 episode_id>0,因此该任务永久跳过且没有原因日志。
## 修复
1. POST /admin/media/{id}/transcode 严格只按 media_asset.id 查询;
不再把候选 id 当分集 id 兜底或补登记。
2. 媒资存在时按 source_url 反查分集;找到后绑定 drama_id/episode_id。
3. 找不到分集时拒绝建任务,避免生成永远无法认领的 episode_id=0 记录。
4. claim 增加 media_asset_id/source_url 条件,并记录被跳过任务 id 与原因。
5. RUNNING 无更新阈值收敛到 5 分钟,覆盖 worker 重启后的孤儿任务。
6. 一次性 patch 将 media_asset_id 不存在且 episode_id=0 的 QUEUED/RUNNING 标记 FAILED。
## 验证
- 非法 media id 拒绝、未绑定分集拒绝、合法 URL 自动绑定。
- claim 跳过原因、进度更新、僵尸任务恢复。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,28 @@
# 转码媒资 ID 精度与存量兜底修复
## 取证
- 示例分集 `2113150431755636737` 的 `video_asset_id` 为
`2113150398670966786`,与 `media_asset.id` 完全一致。
- JS `Number('2113150398670966786')` 序列化为 `2113150398670966800`,
超出安全整数后发生精度丢失,导致手动转码查询了错误 ID。
## 修复
1. 聚合响应的 episodeId/mediaAssetId/taskId 使用字符串。
2. 手动转码仍由后端 Long 接收精确路径 ID。
3. 媒资不存在时通过 content 模块的端口按候选 ID 查找分集:
- 分集 id;
- video_asset_id;
- transcode_task.id。
4. 找到分集后按 video_url/source_url/objectKey 反查媒资;
文件存在但媒资缺失时补登记并回填分集 video_asset_id。
5. 无可用视频时保持明确空态/错误语义。
## 验证
- 超 2^53 ID 字符串契约。
- 聚合无媒资空态。
- video_url 反查命中。
- 文件存在时补登记。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,27 @@
# 转码保持原始宽高比
## 目标
- 横屏源按档位短边作为高度,竖屏源按档位短边作为宽度。
- 源短边小于档位短边时按源短边输出,不放大。
- 输出宽高均为偶数,SAR 固定为 1。
- rendition 的 width/height 使用 ffprobe 探测到的实际值。
## 实施
1. ffprobe 读取源显示方向尺寸,旋转 90/270 度时交换宽高。
2. `effectiveShort = min(sourceShort, rungShort)` 并向下取偶数。
3. 横屏使用 `scale=-2:<effectiveShort>:flags=lanczos,setsar=1`;
竖屏使用 `scale=<effectiveShort>:-2:flags=lanczos,setsar=1`。
4. 转码完成后 ffprobe variant playlist,写入实际输出尺寸。
5. master playlist 的 RESOLUTION 同步使用实际尺寸。
## 不放大策略
选用“用源尺寸输出”:高于源短边的档位仍保留原 quality 标识和码率,
但分辨率封顶到源短边,避免所有档位都被跳过导致无产物。
## 验证
- 先补横屏、竖屏、小源码片、偶数、SAR=1 与实际尺寸回写测试。
- 门禁:`mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,29 @@
# 转码错误截断与进度上报
## 问题
- ffmpeg 错误输出超过 `error_msg varchar(500)`,失败回写 UPDATE 再次失败,
任务停在 RUNNING/0。
- worker 未解析 ffmpeg progress,前端只能看到 0。
- 缺少 RUNNING 超时收口。
## 修复
1. SQL patch 将 transcode_task/media_thumbnail 的 error_msg 改为 TEXT,可重复执行。
2. 新增统一错误消息截断,最多保留 500 字符并附总长度;即使补丁尚未执行,
也不会超过旧 varchar(500) 限制。
3. ffmpeg 使用 `-progress` 临时文件,worker 节流为约 1 秒写 transcode_task.progress。
4. rendition 阶段映射 0-90%,封面/缩略图 90-99%,成功后 100。
5. 失败保留最后进度;RUNNING 超过 10 分钟无 updated_at 变化标记 FAILED。
6. 手动重转复用最新任务,SUCCESS/FAILED/CANCELED 原地重置为 QUEUED、progress=0。
7. 成功写 rendition 前替换同媒资旧产物,避免重复重转唯一键冲突。
## 风险
- 进度写入只允许 RUNNING 状态,避免覆盖已完成/失败状态。
- 历史僵尸任务由 worker 下一轮自动收口,无需手工 SQL。
## 验证
- 错误截断、进度更新、僵尸重置、重复触发幂等测试。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,24 @@
# 转码 rendition 幂等与失败落库
## 根因
- 成功事务只按 media_asset_id 删除旧 rendition。
- 同一分集替换视频后 media_asset_id 改变、episode_id 不变,
旧行未被删除,触发 uk_rendition(episode_id, quality, format)。
- rendition 插入异常后任务未被可靠置为 FAILED。
## 修复
1. 成功事务删除条件分组为:
`media_asset_id = 本次媒体 OR (episode_id > 0 AND episode_id = 本次分集)`。
2. 缩略图登记按 episode_id 删除旧行后重新插入。
3. 主流程异常调用 failFinal,直接写 FAILED、错误、finished_at,保留 progress。
4. failFinal 自身异常在 worker 中 catch 并打印 ERROR,不静默。
5. error 截断同时保留头部与尾部,长度仍 <= 500。
## 验证
- 不同 media_asset_id、同 episode_id 的重复转码清理条件。
- thumbnail 旧行替换。
- 失败落库字段与尾段错误保留。
- `mvn -q -DskipTests=false test -pl ... -am`。
+19
View File
@@ -0,0 +1,19 @@
# 标签管理(替换短剧内容类型)
## 决定
不做「语言开关」总控。分类和剧单已经用 `name` / `nameEn` / `nameId` 三列。标签沿用同一套,避免两套国际化。语言总控要改短剧标题、简介、剧集标题,单独开一轮。
## 本轮
- 短剧编辑去掉「内容类型」。库里的 `drama_type` 先留着,推荐流的 `ANIME` / `LIVE` 筛选不受影响,后台不再改它。
- 内容管理下新增「标签管理」。
- 标签字段:中文名、英文名、印尼语名、排序、启用状态。三个名称都必填。
- 短剧 `tag_id` 单选,可空。编辑页用下拉,只列出启用中的标签。
- 已有短剧按原内容类型回填:`ANIME` → 漫剧,`LIVE` → 真人剧。
## 接口
- `GET/POST /admin/content-tags`,`PUT/DELETE /admin/content-tags/{id}`,权限沿用 `drama:list` / `create` / `update` / `delete`。
- 短剧保存增加 `tagId`。不传则保持原值;传 `0` 表示清空。
- 短剧列表返回 `tagId`、`tagName`、`tagNameEn`、`tagNameId`。
+1256 -3
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,28 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.config;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.format.DateTimeFormatter;
/**
* 后台接口的时间格式统一成 `yyyy-MM-dd HH:mm:ss`。
*
* <p>application.yml 里的 `spring.jackson.date-format` 只作用于 java.util.Date,
* LocalDateTime 仍会输出 ISO 的 `2026-10-27T14:14:12.644`,后台表格里会露出一串带 T 的原文。
* 该配置只放在 admin-api,C 端保持 ISO,避免影响客户端解析。
*/
@Configuration
public class AdminJacksonTimeConfig {
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Bean
public Jackson2ObjectMapperBuilderCustomizer adminLocalDateTimeFormat() {
return builder -> builder.serializers(new LocalDateTimeSerializer(DATE_TIME));
}
}
@@ -4,6 +4,7 @@ package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.admin.service.AppSessionSystemService;
import com.fruitshorts.admin.vo.AppUserWatchHistoryVO; import com.fruitshorts.admin.vo.AppUserWatchHistoryVO;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
@@ -13,6 +14,7 @@ import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.framework.log.OperationLog; import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.dal.entity.WatchHistory; import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.playback.service.WatchProgressService; import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.user.dal.entity.AppUserBanRecord; import com.fruitshorts.user.dal.entity.AppUserBanRecord;
import com.fruitshorts.user.service.AppUserAdminService; import com.fruitshorts.user.service.AppUserAdminService;
@@ -44,6 +46,7 @@ public class AppUserAdminController {
private final WatchProgressService watchProgressService; private final WatchProgressService watchProgressService;
private final DramaService dramaService; private final DramaService dramaService;
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final AppSessionSystemService sessionSystem;
@Operation(summary = "App 用户分页查询") @Operation(summary = "App 用户分页查询")
@GetMapping("/page") @GetMapping("/page")
@@ -83,11 +86,15 @@ public class AppUserAdminController {
Map<Long, DramaEpisode> episodes = episodeService Map<Long, DramaEpisode> episodes = episodeService
.listByIds(rows.stream().map(WatchHistory::getEpisodeId).distinct().toList()) .listByIds(rows.stream().map(WatchHistory::getEpisodeId).distinct().toList())
.stream().collect(Collectors.toMap(DramaEpisode::getId, item -> item, (a, b) -> a)); .stream().collect(Collectors.toMap(DramaEpisode::getId, item -> item, (a, b) -> a));
return Result.ok(rows.stream().map(row -> toVo(row, dramas, episodes)).toList()); List<AppUserSession> sessions = sessionSystem.groupByUser(List.of(id))
.getOrDefault(id, List.of());
return Result.ok(rows.stream()
.map(row -> toVo(row, dramas, episodes, sessionSystem.match(sessions, row.getDeviceId())))
.toList());
} }
private AppUserWatchHistoryVO toVo(WatchHistory row, Map<Long, Drama> dramas, private AppUserWatchHistoryVO toVo(WatchHistory row, Map<Long, Drama> dramas,
Map<Long, DramaEpisode> episodes) { Map<Long, DramaEpisode> episodes, AppUserSession session) {
AppUserWatchHistoryVO vo = new AppUserWatchHistoryVO(); AppUserWatchHistoryVO vo = new AppUserWatchHistoryVO();
vo.setId(row.getId()); vo.setId(row.getId());
vo.setDramaId(row.getDramaId()); vo.setDramaId(row.getDramaId());
@@ -100,6 +107,10 @@ public class AppUserAdminController {
long position = row.getPositionMs() == null ? 0L : row.getPositionMs(); long position = row.getPositionMs() == null ? 0L : row.getPositionMs();
long duration = row.getDurationMs() == null ? 0L : row.getDurationMs(); long duration = row.getDurationMs() == null ? 0L : row.getDurationMs();
vo.setFinished(duration > 0 && position + 1000L >= duration); vo.setFinished(duration > 0 && position + 1000L >= duration);
if (session != null) {
vo.setPlatform(session.getPlatform());
vo.setOsVersion(session.getOsVersion());
}
Drama drama = dramas.get(row.getDramaId()); Drama drama = dramas.get(row.getDramaId());
if (drama != null) { if (drama != null) {
vo.setDramaTitle(drama.getTitle()); vo.setDramaTitle(drama.getTitle());
@@ -0,0 +1,98 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.system.service.AppVersionService;
import com.fruitshorts.system.vo.AppVersionQueryReqVO;
import com.fruitshorts.system.vo.AppVersionRespVO;
import com.fruitshorts.system.vo.AppVersionSaveReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** 后台 - App 版本管理。 */
@Tag(name = "后台-App 版本")
@RestController
@RequestMapping("/admin/app-versions")
@RequiredArgsConstructor
public class AppVersionAdminController {
private final AppVersionService appVersionService;
@Operation(summary = "版本分页查询")
@GetMapping("/page")
@PreAuthorize("@ss.hasPermission('app-version:list')")
public Result<PageResult<AppVersionRespVO>> page(@Validated AppVersionQueryReqVO req) {
return Result.ok(appVersionService.page(req));
}
@Operation(summary = "版本详情")
@GetMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:list')")
public Result<AppVersionRespVO> detail(@PathVariable Long id) {
return Result.ok(appVersionService.detail(id));
}
@Operation(summary = "新建版本(默认发布)")
@PostMapping
@PreAuthorize("@ss.hasPermission('app-version:create')")
@OperationLog(module = "版本管理", action = "新建版本")
public Result<Long> create(@Valid @RequestBody AppVersionSaveReqVO req) {
return Result.ok(appVersionService.create(req));
}
@Operation(summary = "批量新建版本(一次事务)")
@PostMapping("/batch")
@PreAuthorize("@ss.hasPermission('app-version:create')")
@OperationLog(module = "版本管理", action = "批量新建版本")
public Result<java.util.List<Long>> batchCreate(
@NotEmpty(message = "请至少传一条")
@Size(max = 16, message = "单次不超过 16 条")
@Valid @RequestBody java.util.List<@Valid AppVersionSaveReqVO> reqs) {
return Result.ok(appVersionService.batchCreate(reqs));
}
@Operation(summary = "编辑版本")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:update')")
@OperationLog(module = "版本管理", action = "编辑版本")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody AppVersionSaveReqVO req) {
appVersionService.update(id, req);
return Result.ok();
}
@Operation(summary = "发布 / 下架")
@PutMapping("/{id}/status")
@PreAuthorize("@ss.hasPermission('app-version:update')")
@OperationLog(module = "版本管理", action = "版本上下架")
public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
appVersionService.updateStatus(id, status);
return Result.ok();
}
@Operation(summary = "删除版本")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:delete')")
@OperationLog(module = "版本管理", action = "删除版本")
public Result<Void> delete(@PathVariable Long id) {
appVersionService.delete(id);
return Result.ok();
}
}
@@ -32,12 +32,13 @@ import java.util.List;
public class AuthController { public class AuthController {
private final AuthService authService; private final AuthService authService;
private final WebUtils webUtils;
@Operation(summary = "管理端登录") @Operation(summary = "管理端登录")
@PostMapping("/login") @PostMapping("/login")
@OperationLog(module = "认证", action = "登录") @OperationLog(module = "认证", action = "登录")
public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) { public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) {
return Result.ok(authService.login(req, WebUtils.getClientIp(request))); return Result.ok(authService.login(req, webUtils.clientIp(request)));
} }
/** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */ /** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */
@@ -0,0 +1,72 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.service.ContentTagService;
import com.fruitshorts.content.vo.ContentTagRespVO;
import com.fruitshorts.content.vo.ContentTagSaveReqVO;
import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 短剧标签管理。短剧编辑时单选其中一个启用标签。 */
@Tag(name = "后台-标签")
@RestController
@RequestMapping("/admin/content-tags")
@RequiredArgsConstructor
public class ContentTagController {
private final ContentTagService contentTagService;
@Operation(summary = "标签列表")
@GetMapping
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<List<ContentTagRespVO>> list(
@RequestParam(required = false) Boolean enabledOnly) {
if (Boolean.TRUE.equals(enabledOnly)) {
return Result.ok(contentTagService.listEnabled());
}
return Result.ok(contentTagService.list());
}
@Operation(summary = "新建标签")
@PostMapping
@PreAuthorize("@ss.hasPermission('drama:create')")
@OperationLog(module = "内容管理", action = "新增标签")
public Result<Long> create(@Valid @RequestBody ContentTagSaveReqVO req) {
return Result.ok(contentTagService.create(req));
}
@Operation(summary = "编辑标签")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "编辑标签")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody ContentTagSaveReqVO req) {
contentTagService.update(id, req);
return Result.ok();
}
@Operation(summary = "删除标签")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:delete')")
@OperationLog(module = "内容管理", action = "删除标签")
public Result<Void> delete(@PathVariable Long id) {
contentTagService.delete(id);
return Result.ok();
}
}
@@ -70,8 +70,8 @@ public class CreatorAdminController {
return Result.ok(creatorService.audit(id, req, SecurityUtils.getUserId())); return Result.ok(creatorService.audit(id, req, SecurityUtils.getUserId()));
} }
/** 手工录入创作者主体(C 端申请入驻还没实现,先用它打通链路)。 */ /** 手工录入创作者主体:录入即通过,可直接开号。 */
@Operation(summary = "手工录入创作者主体") @Operation(summary = "手工录入创作者主体(录入即通过)")
@PostMapping @PostMapping
@PreAuthorize("@ss.hasPermission('creator:audit')") @PreAuthorize("@ss.hasPermission('creator:audit')")
@OperationLog(module = "创作者管理", action = "新增创作者") @OperationLog(module = "创作者管理", action = "新增创作者")
@@ -79,8 +79,8 @@ public class CreatorAdminController {
return Result.ok(creatorService.create(req)); return Result.ok(creatorService.create(req));
} }
/** 开通创作者账号:仅审核通过可开;已开通则幂等返回,不重复建号。 */ /** 开通创作者账号:不再校验入驻审核,仅冻结状态拒绝;已开通则幂等返回。 */
@Operation(summary = "开通创作者账号(仅审核通过可开通,幂等)") @Operation(summary = "开通创作者账号(仅冻结状态拒绝,幂等)")
@PostMapping("/{id}/account") @PostMapping("/{id}/account")
@PreAuthorize("@ss.hasPermission('creator:account')") @PreAuthorize("@ss.hasPermission('creator:account')")
@OperationLog(module = "创作者管理", action = "开通创作者账号") @OperationLog(module = "创作者管理", action = "开通创作者账号")
@@ -12,6 +12,8 @@ import com.fruitshorts.creator.service.CreatorContentService;
import com.fruitshorts.creator.vo.CreatorAttachReqVO; import com.fruitshorts.creator.vo.CreatorAttachReqVO;
import com.fruitshorts.creator.vo.CreatorDramaEditReqVO; import com.fruitshorts.creator.vo.CreatorDramaEditReqVO;
import com.fruitshorts.creator.vo.CreatorEpisodeReqVO; import com.fruitshorts.creator.vo.CreatorEpisodeReqVO;
import com.fruitshorts.creator.vo.CreatorPublishReqVO;
import com.fruitshorts.creator.vo.CreatorPublishRespVO;
import com.fruitshorts.creator.vo.CreatorSubmitReqVO; import com.fruitshorts.creator.vo.CreatorSubmitReqVO;
import com.fruitshorts.framework.log.OperationLog; import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
@@ -53,6 +55,15 @@ public class CreatorContentController {
return Result.ok(creatorContentService.createDrama(req)); return Result.ok(creatorContentService.createDrama(req));
} }
/** 一键发布:建作品 + 建分集 + 绑定视频(可选同时提交审核),一个事务完成。 */
@Operation(summary = "一键发布(建作品 / 分集 / 绑定视频 / 可选提交审核)")
@PostMapping("/publish")
@PreAuthorize("@ss.hasPermission('creator-center:drama:edit')")
@OperationLog(module = "创作者中心", action = "一键发布作品")
public Result<CreatorPublishRespVO> publish(@Valid @RequestBody CreatorPublishReqVO req) {
return Result.ok(creatorContentService.publish(req));
}
/** 编辑作品信息(仅草稿 / 已下线可改)。 */ /** 编辑作品信息(仅草稿 / 已下线可改)。 */
@Operation(summary = "编辑作品信息(仅草稿 / 已下线可改)") @Operation(summary = "编辑作品信息(仅草稿 / 已下线可改)")
@PutMapping("/dramas/{id}") @PutMapping("/dramas/{id}")
@@ -101,6 +112,15 @@ public class CreatorContentController {
return Result.ok(); return Result.ok();
} }
@Operation(summary = "删除作品")
@DeleteMapping("/dramas/{id}")
@PreAuthorize("@ss.hasPermission('creator-center:drama:edit')")
@OperationLog(module = "创作者中心", action = "删除作品")
public Result<Void> deleteDrama(@PathVariable Long id) {
creatorContentService.deleteDrama(id);
return Result.ok();
}
/** 批量排序:body 里按新顺序给出分集 id。 */ /** 批量排序:body 里按新顺序给出分集 id。 */
@Operation(summary = "分集批量排序") @Operation(summary = "分集批量排序")
@PutMapping("/dramas/{id}/episodes/sort") @PutMapping("/dramas/{id}/episodes/sort")
@@ -3,6 +3,9 @@
package com.fruitshorts.admin.controller; package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.DashboardService; import com.fruitshorts.admin.service.DashboardService;
import com.fruitshorts.admin.vo.DashboardDistributionRespVO;
import com.fruitshorts.admin.vo.DashboardTrendRespVO;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@@ -40,7 +43,23 @@ public class DashboardAdminController {
@Operation(summary = "转码看板(队列积压与失败任务)") @Operation(summary = "转码看板(队列积压与失败任务)")
@GetMapping("/transcode") @GetMapping("/transcode")
@PreAuthorize("@ss.hasPermission('dashboard:view')") @PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<Map<String, Object>> transcode() { public Result<TranscodeDashboardRespVO> transcode() {
return Result.ok(dashboardService.transcode()); return Result.ok(dashboardService.transcode());
} }
/** 近 7 天每日趋势(用户注册 / 播放事件 / 转码任务)。 */
@Operation(summary = "大盘趋势(近 7 天每日数据,给折线图用)")
@GetMapping("/trend")
@PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<DashboardTrendRespVO> trend() {
return Result.ok(dashboardService.trend());
}
/** 分布:短剧状态 / 转码状态 / 片源覆盖 / 待处理审核。 */
@Operation(summary = "大盘分布(给饼图用)")
@GetMapping("/distribution")
@PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<DashboardDistributionRespVO> distribution() {
return Result.ok(dashboardService.distribution());
}
} }
@@ -31,14 +31,14 @@ public class DictController {
@Operation(summary = "短剧分类字典") @Operation(summary = "短剧分类字典")
@GetMapping("/drama-category") @GetMapping("/drama-category")
@PreAuthorize("@ss.hasPermission('drama:list')") @PreAuthorize("@ss.hasAnyPermission('drama:list','creator-center:view')")
public Result<List<DramaCategoryRespVO>> dramaCategories() { public Result<List<DramaCategoryRespVO>> dramaCategories() {
return Result.ok(dramaCategoryService.list()); return Result.ok(dramaCategoryService.list());
} }
@Operation(summary = "内容状态字典") @Operation(summary = "内容状态字典")
@GetMapping("/content-status") @GetMapping("/content-status")
@PreAuthorize("@ss.hasPermission('drama:list')") @PreAuthorize("@ss.hasAnyPermission('drama:list','creator-center:view')")
public Result<List<Map<String, String>>> contentStatus() { public Result<List<Map<String, String>>> contentStatus() {
return Result.ok(Arrays.stream(ContentStatus.values()) return Result.ok(Arrays.stream(ContentStatus.values())
.map(status -> Map.of("code", status.getCode(), "text", status.getText())) .map(status -> Map.of("code", status.getCode(), "text", status.getText()))
@@ -0,0 +1,126 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.service.DramaClassificationService;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaClassificationRespVO;
import com.fruitshorts.content.vo.DramaClassificationSaveReqVO;
import com.fruitshorts.content.vo.DramaIdsReqVO;
import com.fruitshorts.content.vo.DramaRankingItemsReqVO;
import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 运营分类管理。分类与短剧类型(drama-categories)是两套独立概念,
* 分类可自定义增删,并关联任意多部短剧。
*/
@Tag(name = "后台-运营分类")
@RestController
@RequestMapping("/admin/drama-classifications")
@RequiredArgsConstructor
public class DramaClassificationController {
private final DramaClassificationService classificationService;
@Operation(summary = "分类列表(带关联数量)")
@GetMapping
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<List<DramaClassificationRespVO>> list() {
return Result.ok(classificationService.list());
}
@Operation(summary = "新建分类")
@PostMapping
@PreAuthorize("@ss.hasPermission('drama:create')")
@OperationLog(module = "内容管理", action = "新增分类")
public Result<Long> create(@Valid @RequestBody DramaClassificationSaveReqVO req) {
return Result.ok(classificationService.create(req));
}
@Operation(summary = "编辑分类")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "编辑分类")
public Result<Void> update(@PathVariable Long id,
@Valid @RequestBody DramaClassificationSaveReqVO req) {
classificationService.update(id, req);
return Result.ok();
}
@Operation(summary = "删除分类")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:delete')")
@OperationLog(module = "内容管理", action = "删除分类")
public Result<Void> delete(@PathVariable Long id) {
classificationService.delete(id);
return Result.ok();
}
@Operation(summary = "分类下已关联的短剧")
@GetMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> dramas(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(classificationService.pageDramas(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "尚未关联到该分类的短剧")
@GetMapping("/{id}/dramas/candidates")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> candidates(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(classificationService.pageCandidates(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "批量关联短剧")
@PostMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "分类关联短剧")
public Result<Integer> bindDramas(@PathVariable Long id,
@Valid @RequestBody DramaIdsReqVO req) {
return Result.ok(classificationService.bindDramas(id, req.getDramaIds()));
}
@Operation(summary = "保存推荐榜完整内容与顺序")
@PutMapping("/{id}/ranking-items")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "保存推荐榜顺序")
public Result<Void> saveRankingItems(@PathVariable Long id,
@Valid @RequestBody DramaRankingItemsReqVO req) {
classificationService.saveRankingItems(id, req.getDramaIds());
return Result.ok();
}
@Operation(summary = "移除分类下的短剧")
@DeleteMapping("/{id}/dramas/{dramaId}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "分类移除短剧")
public Result<Void> unbindDrama(@PathVariable Long id, @PathVariable Long dramaId) {
classificationService.unbindDrama(id, dramaId);
return Result.ok();
}
}
@@ -113,6 +113,15 @@ public class DramaController {
return Result.ok(); return Result.ok();
} }
@Operation(summary = "审核通过并上线")
@PostMapping("/{id}/approve-publish")
@PreAuthorize("@ss.hasPermission('drama:review')")
@OperationLog(module = "内容管理", action = "审核通过并上线")
public Result<Void> approvePublish(@PathVariable Long id, @RequestBody(required = false) DramaStatusReqVO req) {
changeStatus(id, "APPROVE_PUBLISH", req);
return Result.ok();
}
@Operation(summary = "上线") @Operation(summary = "上线")
@PostMapping("/{id}/publish") @PostMapping("/{id}/publish")
@PreAuthorize("@ss.hasPermission('drama:review')") @PreAuthorize("@ss.hasPermission('drama:review')")
@@ -0,0 +1,115 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.service.DramaPlaylistCategoryService;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaIdsReqVO;
import com.fruitshorts.content.vo.DramaPlaylistCategoryRespVO;
import com.fruitshorts.content.vo.DramaPlaylistCategorySaveReqVO;
import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 剧单分类管理:分类直接关联短剧,没有「剧单」这一层。
* 与「类型」「分类管理」均无关。
*/
@Tag(name = "后台-剧单分类")
@RestController
@RequestMapping("/admin/drama-playlist-categories")
@RequiredArgsConstructor
public class DramaPlaylistCategoryController {
private final DramaPlaylistCategoryService categoryService;
@Operation(summary = "剧单分类列表")
@GetMapping
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<List<DramaPlaylistCategoryRespVO>> list() {
return Result.ok(categoryService.list());
}
@Operation(summary = "新建剧单分类")
@PostMapping
@PreAuthorize("@ss.hasPermission('drama:create')")
@OperationLog(module = "内容管理", action = "新增剧单分类")
public Result<Long> create(@Valid @RequestBody DramaPlaylistCategorySaveReqVO req) {
return Result.ok(categoryService.create(req));
}
@Operation(summary = "编辑剧单分类")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "编辑剧单分类")
public Result<Void> update(@PathVariable Long id,
@Valid @RequestBody DramaPlaylistCategorySaveReqVO req) {
categoryService.update(id, req);
return Result.ok();
}
@Operation(summary = "删除剧单分类")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:delete')")
@OperationLog(module = "内容管理", action = "删除剧单分类")
public Result<Void> delete(@PathVariable Long id) {
categoryService.delete(id);
return Result.ok();
}
@Operation(summary = "分类下已关联的短剧")
@GetMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> dramas(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(categoryService.pageDramas(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "尚未关联到该分类的短剧")
@GetMapping("/{id}/dramas/candidates")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> candidates(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(categoryService.pageCandidates(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "批量关联短剧")
@PostMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "剧单分类关联短剧")
public Result<Integer> bindDramas(@PathVariable Long id,
@Valid @RequestBody DramaIdsReqVO req) {
return Result.ok(categoryService.bindDramas(id, req.getDramaIds()));
}
@Operation(summary = "移除分类下的短剧")
@DeleteMapping("/{id}/dramas/{dramaId}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "剧单分类移除短剧")
public Result<Void> unbindDrama(@PathVariable Long id, @PathVariable Long dramaId) {
categoryService.unbindDrama(id, dramaId);
return Result.ok();
}
}
@@ -2,6 +2,7 @@
package com.fruitshorts.admin.controller; package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
@@ -39,12 +40,15 @@ public class EpisodeController {
private final CommentService commentService; private final CommentService commentService;
private final DramaService dramaService; private final DramaService dramaService;
@Operation(summary = "剧集列表") @Operation(summary = "剧集列表(分页)")
@GetMapping @GetMapping
@PreAuthorize("@ss.hasPermission('episode:list')") @PreAuthorize("@ss.hasPermission('episode:list')")
public Result<List<EpisodeRespVO>> list(@RequestParam Long dramaId, public Result<PageResult<EpisodeRespVO>> list(@RequestParam Long dramaId,
@RequestParam(required = false) String status) { @RequestParam(required = false) String status,
List<EpisodeRespVO> episodes = episodeService.listByDrama(dramaId, status); @RequestParam(required = false) Integer pageIndex,
@RequestParam(required = false) Integer pageSize) {
PageResult<EpisodeRespVO> page = episodeService.pageByDrama(dramaId, status, pageIndex, pageSize);
List<EpisodeRespVO> episodes = page.getList();
Map<Long, Long> commentCounts = commentService.countByEpisodes( Map<Long, Long> commentCounts = commentService.countByEpisodes(
episodes.stream().map(EpisodeRespVO::getId).toList()); episodes.stream().map(EpisodeRespVO::getId).toList());
Drama drama = dramaService.getExisting(dramaId); Drama drama = dramaService.getExisting(dramaId);
@@ -53,7 +57,7 @@ public class EpisodeController {
episode.setFavoriteCount(drama.getFavoriteCount()); episode.setFavoriteCount(drama.getFavoriteCount());
episode.setHeat(drama.getViewCount()); episode.setHeat(drama.getViewCount());
}); });
return Result.ok(episodes); return Result.ok(new PageResult<>(page.getTotal(), episodes));
} }
@Operation(summary = "新建剧集") @Operation(summary = "新建剧集")
@@ -0,0 +1,32 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.EpisodeTranscodeAdminService;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台剧集转码聚合查询。 */
@Tag(name = "后台-剧集转码")
@RestController
@RequestMapping("/admin/episodes")
@RequiredArgsConstructor
public class EpisodeTranscodeController {
private final EpisodeTranscodeAdminService service;
@Operation(summary = "查询分集转码聚合信息")
@GetMapping("/{id}/transcode")
@PreAuthorize("@ss.hasPermission('episode:list')")
public Result<EpisodeTranscodeRespVO> detail(@PathVariable Long id) {
return Result.ok(service.detail(id));
}
}
@@ -0,0 +1,34 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.FavoriteAdminService;
import com.fruitshorts.admin.vo.AdminFavoriteVO;
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台收藏只读查询入口。 */
@Tag(name = "后台-收藏列表")
@RestController
@RequestMapping("/admin/favorites")
@RequiredArgsConstructor
public class FavoriteAdminController {
private final FavoriteAdminService service;
/** 按用户、设备、内容和时间分页查询收藏。 */
@Operation(summary = "收藏列表分页查询")
@GetMapping("/page")
@PreAuthorize("@ss.hasPermission('favorite:list')")
public Result<PageResult<AdminFavoriteVO>> page(@Valid FavoriteQueryReqVO req) {
return Result.ok(service.page(req));
}
}
@@ -0,0 +1,47 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.system.service.LegalDocumentService;
import com.fruitshorts.system.vo.LegalDocumentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后台维护服务条款和隐私协议。公开页面由客户端服务按语言输出。
*/
@Tag(name = "后台-协议")
@RestController
@RequestMapping("/admin/legal-documents")
@RequiredArgsConstructor
public class LegalDocumentAdminController {
private final LegalDocumentService legalDocumentService;
@Operation(summary = "协议列表(服务条款、隐私协议,各含中英印尼语)")
@GetMapping
@PreAuthorize("@ss.hasAnyPermission('system:role','system:menu')")
public Result<List<LegalDocumentVO>> list() {
return Result.ok(legalDocumentService.list());
}
@Operation(summary = "保存协议")
@PutMapping
@PreAuthorize("@ss.hasPermission('system:role')")
@OperationLog(module = "后台管理", action = "修改服务条款或隐私协议")
public Result<Void> save(@RequestBody List<LegalDocumentVO> items) {
legalDocumentService.save(items);
return Result.ok();
}
}
@@ -0,0 +1,34 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.LikeAdminService;
import com.fruitshorts.admin.vo.AdminLikeVO;
import com.fruitshorts.admin.vo.LikeQueryReqVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台点赞只读查询入口。 */
@Tag(name = "后台-点赞列表")
@RestController
@RequestMapping("/admin/likes")
@RequiredArgsConstructor
public class LikeAdminController {
private final LikeAdminService service;
/** 按用户、设备、内容和时间分页查询点赞。 */
@Operation(summary = "点赞列表分页查询")
@GetMapping("/page")
@PreAuthorize("@ss.hasPermission('like:list')")
public Result<PageResult<AdminLikeVO>> page(@Valid LikeQueryReqVO req) {
return Result.ok(service.page(req));
}
}
@@ -5,12 +5,18 @@ package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.framework.security.ImpersonationGuard; import com.fruitshorts.framework.security.ImpersonationGuard;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.media.config.MediaTranscodeProfile;
import com.fruitshorts.media.service.MediaService; import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.media.vo.MediaAssetRespVO; import com.fruitshorts.media.vo.MediaAssetRespVO;
import com.fruitshorts.media.vo.TranscodeTriggerRespVO;
import com.fruitshorts.media.vo.UploadCompleteReqVO; import com.fruitshorts.media.vo.UploadCompleteReqVO;
import com.fruitshorts.media.vo.UploadInitReqVO; import com.fruitshorts.media.vo.UploadInitReqVO;
import com.fruitshorts.media.vo.UploadInitRespVO; import com.fruitshorts.media.vo.UploadInitRespVO;
import com.fruitshorts.media.vo.UploadProgressRespVO; import com.fruitshorts.media.vo.UploadProgressRespVO;
import com.fruitshorts.admin.service.TranscodeBackfillAdminService;
import com.fruitshorts.admin.vo.TranscodeBackfillRespVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@@ -19,6 +25,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@@ -35,6 +42,8 @@ import org.springframework.web.multipart.MultipartFile;
public class MediaController { public class MediaController {
private final MediaService mediaService; private final MediaService mediaService;
private final MediaTranscodeProfileService profileService;
private final TranscodeBackfillAdminService backfillAdminService;
@Operation(summary = "初始化分片上传") @Operation(summary = "初始化分片上传")
@PostMapping("/upload/init") @PostMapping("/upload/init")
@@ -78,4 +87,40 @@ public class MediaController {
public Result<MediaAssetRespVO> get(@PathVariable Long id) { public Result<MediaAssetRespVO> get(@PathVariable Long id) {
return Result.ok(mediaService.get(id)); return Result.ok(mediaService.get(id));
} }
@Operation(summary = "手动触发或重转媒资")
@PostMapping("/{id}/transcode")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "触发媒资转码")
public Result<TranscodeTriggerRespVO> transcode(@PathVariable Long id) {
ImpersonationGuard.rejectWrite();
return Result.ok(mediaService.triggerTranscode(id));
}
@Operation(summary = "读取转码档位配置")
@GetMapping("/transcode-profile")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<MediaTranscodeProfile> transcodeProfile() {
return Result.ok(profileService.readConfiguredProfile());
}
@Operation(summary = "保存转码档位配置")
@PutMapping("/transcode-profile")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "修改转码设置")
public Result<MediaTranscodeProfile> saveTranscodeProfile(
@Valid @RequestBody MediaTranscodeProfile profile) {
ImpersonationGuard.rejectWrite();
return Result.ok(profileService.save(profile));
}
@Operation(summary = "手动补齐转码:扫描缺产物/帧图的分集并入队")
@PostMapping("/transcode/backfill")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "补齐转码")
public Result<TranscodeBackfillRespVO> backfill(
@RequestParam(value = "batchSize", required = false) Integer batchSize) {
ImpersonationGuard.rejectWrite();
return Result.ok(backfillAdminService.runOnce(batchSize));
}
} }
@@ -0,0 +1,46 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 后台媒资转码产物只读查询。 */
@Tag(name = "后台-媒资转码产物")
@RestController
@RequestMapping("/admin/media")
@RequiredArgsConstructor
public class MediaTranscodeOutputController {
private final MediaTranscodeOutputService outputService;
@Operation(summary = "查询媒资清晰度产物")
@GetMapping("/{id}/renditions")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<List<MediaRenditionRespVO>> renditions(@PathVariable Long id) {
return Result.ok(outputService.renditions(id));
}
@Operation(summary = "分页查询媒资帧图产物")
@GetMapping("/{id}/thumbnails")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<MediaThumbnailRespVO> thumbnails(
@PathVariable Long id,
@RequestParam(defaultValue = "1") Integer pageIndex,
@RequestParam(defaultValue = "100") Integer pageSize) {
return Result.ok(outputService.thumbnails(id, pageIndex, pageSize));
}
}
@@ -0,0 +1,171 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.commerce.reward.service.RewardCheckinService;
import com.fruitshorts.commerce.reward.service.RewardActivityAdminService;
import com.fruitshorts.commerce.reward.service.RewardGrantService;
import com.fruitshorts.commerce.reward.service.RewardTaskService;
import com.fruitshorts.commerce.reward.vo.RewardActivityQueryReqVO;
import com.fruitshorts.commerce.reward.vo.RewardActivityRespVO;
import com.fruitshorts.commerce.reward.vo.RewardActivitySaveReqVO;
import com.fruitshorts.commerce.reward.vo.RewardCheckinRuleSaveReqVO;
import com.fruitshorts.commerce.reward.vo.RewardGrantQueryReqVO;
import com.fruitshorts.commerce.reward.vo.RewardGrantRespVO;
import com.fruitshorts.commerce.reward.vo.RewardManualGrantReqVO;
import com.fruitshorts.commerce.reward.vo.RewardRuleDayVO;
import com.fruitshorts.commerce.reward.vo.RewardTaskQueryReqVO;
import com.fruitshorts.commerce.reward.vo.RewardTaskRespVO;
import com.fruitshorts.commerce.reward.vo.RewardTaskSaveReqVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.user.dal.mapper.AppUserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 后台奖励任务、签到规则和发放记录管理。 */
@Tag(name = "后台-奖励中心")
@RestController
@RequestMapping("/admin/rewards")
@RequiredArgsConstructor
public class RewardAdminController {
private final RewardTaskService taskService;
private final RewardActivityAdminService activityService;
private final RewardCheckinService checkinService;
private final RewardGrantService grantService;
private final AppUserMapper appUserMapper;
@Operation(summary = "奖励任务分页")
@GetMapping("/tasks/page")
@PreAuthorize("@ss.hasPermission('reward:list')")
public Result<PageResult<RewardTaskRespVO>> page(@Validated RewardTaskQueryReqVO req) {
return Result.ok(taskService.page(req));
}
@Operation(summary = "奖励任务详情")
@GetMapping("/tasks/{id}")
@PreAuthorize("@ss.hasPermission('reward:list')")
public Result<RewardTaskRespVO> detail(@PathVariable Long id) {
return Result.ok(taskService.detail(id));
}
@Operation(summary = "新建奖励任务")
@PostMapping("/tasks")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "新建奖励任务")
public Result<Long> create(@Valid @RequestBody RewardTaskSaveReqVO req) {
return Result.ok(taskService.create(req));
}
@Operation(summary = "编辑奖励任务")
@PutMapping("/tasks/{id}")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "编辑奖励任务")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody RewardTaskSaveReqVO req) {
taskService.update(id, req);
return Result.ok();
}
@Operation(summary = "奖励任务上下线")
@PutMapping("/tasks/{id}/status")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "奖励任务上下线")
public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
taskService.updateStatus(id, status);
return Result.ok();
}
@Operation(summary = "奖励活动分页")
@GetMapping("/activities/page")
@PreAuthorize("@ss.hasPermission('reward:list')")
public Result<PageResult<RewardActivityRespVO>> activityPage(@Validated RewardActivityQueryReqVO req) {
return Result.ok(activityService.page(req));
}
@Operation(summary = "奖励活动详情")
@GetMapping("/activities/{id}")
@PreAuthorize("@ss.hasPermission('reward:list')")
public Result<RewardActivityRespVO> activityDetail(@PathVariable Long id) {
return Result.ok(activityService.detail(id));
}
@Operation(summary = "新建奖励活动")
@PostMapping("/activities")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "新建奖励活动")
public Result<Long> createActivity(@Valid @RequestBody RewardActivitySaveReqVO req) {
return Result.ok(activityService.create(req));
}
@Operation(summary = "编辑奖励活动")
@PutMapping("/activities/{id}")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "编辑奖励活动")
public Result<Void> updateActivity(@PathVariable Long id, @Valid @RequestBody RewardActivitySaveReqVO req) {
activityService.update(id, req);
return Result.ok();
}
@Operation(summary = "奖励活动上下线")
@PutMapping("/activities/{id}/status")
@PreAuthorize("@ss.hasPermission('reward:update')")
@OperationLog(module = "奖励中心", action = "奖励活动上下线")
public Result<Void> updateActivityStatus(@PathVariable Long id, @RequestParam Integer status) {
activityService.updateStatus(id, status);
return Result.ok();
}
@Operation(summary = "签到规则")
@GetMapping("/check-in/rules")
@PreAuthorize("@ss.hasPermission('reward:checkin')")
public Result<List<RewardRuleDayVO>> rules() {
return Result.ok(checkinService.rulesForAdmin());
}
@Operation(summary = "保存签到规则")
@PutMapping("/check-in/rules")
@PreAuthorize("@ss.hasPermission('reward:checkin')")
@OperationLog(module = "奖励中心", action = "保存签到规则")
public Result<Void> saveRules(@Valid @RequestBody RewardCheckinRuleSaveReqVO req) {
checkinService.saveRules(req);
return Result.ok();
}
@Operation(summary = "奖励发放记录分页")
@GetMapping("/grants/page")
@PreAuthorize("@ss.hasPermission('reward:grant')")
public Result<PageResult<RewardGrantRespVO>> grants(@Validated RewardGrantQueryReqVO req) {
return Result.ok(grantService.page(req));
}
@Operation(summary = "人工补发奖励")
@PostMapping("/grants/manual")
@PreAuthorize("@ss.hasPermission('reward:grant')")
@OperationLog(module = "奖励中心", action = "人工补发奖励")
public Result<RewardGrantRespVO> manualGrant(@Valid @RequestBody RewardManualGrantReqVO req) {
if (appUserMapper.selectById(req.getUserId()) == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "用户不存在,无法补发奖励");
}
return Result.ok(grantService.manualGrant(req.getUserId(), req.getTaskId(), req.getAmount(),
req.getIdempotentKey(), SecurityUtils.getUserId()));
}
}
@@ -0,0 +1,33 @@
// Author: fruit.com.cn
// 后台转码通知接口。
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeNoticeService;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台转码通知。 */
@Tag(name = "后台-转码通知")
@RestController
@RequestMapping("/admin/notifications")
@RequiredArgsConstructor
public class TranscodeNoticeController {
private final TranscodeNoticeService transcodeNoticeService;
/** 转码中、成功、失败的角标和最近任务,含短剧与集数。 */
@Operation(summary = "转码通知(角标与最近任务)")
@GetMapping("/transcode")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<TranscodeNoticeRespVO> transcode() {
return Result.ok(transcodeNoticeService.notices());
}
}
@@ -0,0 +1,113 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 按设备画像解析系统,缺画像时回退到用户最近会话。
* 设备画像不依赖登录态,游客行为也能显示系统。
*/
@Service
@RequiredArgsConstructor
public class AppSessionSystemService {
private final AppUserSessionMapper sessionMapper;
private final AppDeviceProfileMapper profileMapper;
/** 按用户分组,组内按最近活跃倒序。 */
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
Map<Long, List<AppUserSession>> grouped = new HashMap<>();
if (userIds == null || userIds.isEmpty()) {
return grouped;
}
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
.select(AppUserSession::getId, AppUserSession::getUserId, AppUserSession::getDeviceId,
AppUserSession::getPlatform, AppUserSession::getOsVersion,
AppUserSession::getRevokedAt, AppUserSession::getLastActiveAt)
.in(AppUserSession::getUserId, userIds)
.orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId));
for (AppUserSession session : sessions) {
grouped.computeIfAbsent(session.getUserId(), key -> new ArrayList<>()).add(session);
}
return grouped;
}
/** 按 device_id 批量取设备画像,未建档的设备不出现在结果里。 */
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
Map<String, AppDeviceProfile> result = new HashMap<>();
if (deviceIds == null || deviceIds.isEmpty()) {
return result;
}
List<String> keys = deviceIds.stream()
.filter(StringUtils::hasText).map(String::trim).distinct().toList();
if (keys.isEmpty()) {
return result;
}
for (AppDeviceProfile profile : profileMapper.selectList(
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))) {
result.put(profile.getDeviceId(), profile);
}
return result;
}
/**
* 平台筛选的命中范围:设备平台直接给 device_id;登录用户的行为行不带 device_id,
* 只能按该用户登录会话的平台判定,两者取并集。
*/
public record PlatformScope(List<String> deviceIds, List<Long> userIds) {
public boolean empty() {
return deviceIds.isEmpty() && userIds.isEmpty();
}
}
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
public PlatformScope platformScope(String platform) {
if (!StringUtils.hasText(platform)) {
return null;
}
String value = platform.trim().toUpperCase(Locale.ROOT);
List<String> deviceIds = profileMapper.selectList(Wrappers.<AppDeviceProfile>lambdaQuery()
.select(AppDeviceProfile::getDeviceId)
.eq(AppDeviceProfile::getPlatform, value))
.stream().map(AppDeviceProfile::getDeviceId).toList();
// 只认「最近一次登录」的平台,与列表里展示的系统保持一致
List<Long> userIds = sessionMapper.selectUserIdsByLatestPlatform(value);
return new PlatformScope(deviceIds, userIds);
}
/** 观看记录优先匹配同一设备,其次取未吊销会话。 */
public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
if (sessions == null || sessions.isEmpty()) {
return null;
}
if (StringUtils.hasText(deviceId)) {
for (AppUserSession session : sessions) {
if (deviceId.equals(session.getDeviceId())) {
return session;
}
}
}
for (AppUserSession session : sessions) {
if (session.getRevokedAt() == null) {
return session;
}
}
return sessions.get(0);
}
}
@@ -3,6 +3,9 @@
package com.fruitshorts.admin.service; package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.admin.vo.DashboardDistributionRespVO;
import com.fruitshorts.admin.vo.DashboardTrendRespVO;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.commerce.dal.entity.CoinLedger; import com.fruitshorts.commerce.dal.entity.CoinLedger;
import com.fruitshorts.commerce.dal.entity.Entitlement; import com.fruitshorts.commerce.dal.entity.Entitlement;
import com.fruitshorts.commerce.dal.entity.Orders; import com.fruitshorts.commerce.dal.entity.Orders;
@@ -21,6 +24,8 @@ import com.fruitshorts.interaction.dal.entity.ContentReport;
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper; import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
import com.fruitshorts.interaction.dal.mapper.ContentReportMapper; import com.fruitshorts.interaction.dal.mapper.ContentReportMapper;
import com.fruitshorts.media.service.TranscodeService; import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import com.fruitshorts.playback.dal.entity.WatchHistory; import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.playback.dal.entity.WatchProgress; import com.fruitshorts.playback.dal.entity.WatchProgress;
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper; import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
@@ -41,6 +46,8 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
/** /**
* 运营大盘(只读聚合)。 * 运营大盘(只读聚合)。
* *
@@ -51,7 +58,11 @@ import java.util.Map;
* <ul> * <ul>
* <li>用户:`total` = app_user 未删除总数;`newToday`/`new7d` = 按 created_at 落在当天 / 近 7 天; * <li>用户:`total` = app_user 未删除总数;`newToday`/`new7d` = 按 created_at 落在当天 / 近 7 天;
* `active7d` = last_login_at 在近 7 天内(**不是 DAU**:真正的日活需要按天留存登录快照, * `active7d` = last_login_at 在近 7 天内(**不是 DAU**:真正的日活需要按天留存登录快照,
* 当前没有逐日快照数据源,见 notes);`banned`/`limited` = 按 status 计数。</li> * 当前没有逐日快照数据源,见 notes);`androidActive7d`/`iosActive7d` =
* `app_user_device` 中状态为 active、近 7 天有心跳的去重设备数;
* `retention1d` = 昨日注册用户中今天仍登录的比例,分母为 0 时返回 null;
* `retention7d` = 8 至 14 天前注册的用户中,近 7 天仍登录的比例,分母为 0 时返回 null;
* `banned`/`limited` = 按 status 计数。</li>
* <li>内容:短剧按 status 计数(`reviewing` 视为待审、`published` 视为已上线); * <li>内容:短剧按 status 计数(`reviewing` 视为待审、`published` 视为已上线);
* 剧集总数与已上线数;`episodeWithMedia` = video_url 非空的剧集数。</li> * 剧集总数与已上线数;`episodeWithMedia` = video_url 非空的剧集数。</li>
* <li>播放:`viewTotal`/`playTotal` = 短剧表上累计计数列的求和(累计口径,不限定时间范围); * <li>播放:`viewTotal`/`playTotal` = 短剧表上累计计数列的求和(累计口径,不限定时间范围);
@@ -69,6 +80,9 @@ import java.util.Map;
public class DashboardService { public class DashboardService {
private static final int ACTIVE_WINDOW_DAYS = 7; private static final int ACTIVE_WINDOW_DAYS = 7;
private static final int RETENTION_WINDOW_DAYS = 7;
private static final String PLATFORM_ANDROID = "ANDROID";
private static final String PLATFORM_IOS = "IOS";
private final AppUserMapper appUserMapper; private final AppUserMapper appUserMapper;
private final AppUserOtpMapper appUserOtpMapper; private final AppUserOtpMapper appUserOtpMapper;
@@ -83,6 +97,7 @@ public class DashboardService {
private final CoinLedgerMapper coinLedgerMapper; private final CoinLedgerMapper coinLedgerMapper;
private final EntitlementMapper entitlementMapper; private final EntitlementMapper entitlementMapper;
private final TranscodeService transcodeService; private final TranscodeService transcodeService;
private final JdbcTemplate jdbcTemplate;
public Map<String, Object> overview() { public Map<String, Object> overview() {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
@@ -101,17 +116,71 @@ public class DashboardService {
} }
/** 转码看板:队列积压与失败明细。 */ /** 转码看板:队列积压与失败明细。 */
public Map<String, Object> transcode() { public TranscodeDashboardRespVO transcode() {
Map<String, Object> data = new LinkedHashMap<>(); TranscodeDashboardRespVO data = new TranscodeDashboardRespVO();
data.put("generatedAt", LocalDateTime.now()); data.setGeneratedAt(LocalDateTime.now());
data.put("queue", transcodeService.stats()); data.setQueue(transcodeService.stats());
data.put("failedTasks", transcodeService.failedTasks(20)); data.setFailedTasks(transcodeService.failedTasks(20).stream()
data.put("notes", List.of( .map(TranscodeTaskRespVO::from)
.toList());
data.setNotes(List.of(
"queue 为累计口径(不限时间),反映当前积压与历史成败分布", "queue 为累计口径(不限时间),反映当前积压与历史成败分布",
"failedTasks 最多返回 20 条,按 id 倒序")); "failedTasks 最多返回 20 条,按 id 倒序"));
return data; return data;
} }
/** 近 7 天每日趋势,给折线图用。 */
public DashboardTrendRespVO trend() {
int days = 7;
LocalDate today = LocalDate.now();
List<String> dates = new ArrayList<>(days);
List<Long> newUsers = new ArrayList<>(days);
List<Long> playEvents = new ArrayList<>(days);
List<Long> newTranscodes = new ArrayList<>(days);
List<Long> transcodeSuccess = new ArrayList<>(days);
for (int i = days - 1; i >= 0; i--) {
LocalDate d = today.minusDays(i);
dates.add(d.toString());
newUsers.add(countForDate("SELECT COUNT(*) FROM app_user WHERE deleted = 0 AND DATE(created_at) = ?", d));
playEvents.add(countForDate("SELECT COUNT(*) FROM watch_history WHERE DATE(watched_at) = ?", d));
newTranscodes.add(countForDate("SELECT COUNT(*) FROM transcode_task WHERE DATE(created_at) = ?", d));
transcodeSuccess.add(countForDate("SELECT COUNT(*) FROM transcode_task WHERE status = 'SUCCESS' AND DATE(created_at) = ?", d));
}
return new DashboardTrendRespVO(dates, newUsers, playEvents, newTranscodes, transcodeSuccess);
}
/** 各域状态分布,给饼图用。 */
public DashboardDistributionRespVO distribution() {
DashboardDistributionRespVO vo = new DashboardDistributionRespVO();
vo.setDramaStatus(groupBy("SELECT status, COUNT(*) FROM drama WHERE deleted = 0 GROUP BY status"));
vo.setTranscodeStatus(groupBy("SELECT status, COUNT(*) FROM transcode_task GROUP BY status"));
vo.setEpisodeMedia(groupBy("""
SELECT CASE WHEN video_url IS NOT NULL AND video_url <> '' THEN '有片源' ELSE '无片源' END AS bucket,
COUNT(*) FROM drama_episode WHERE deleted = 0 GROUP BY bucket"""));
List<DashboardDistributionRespVO.Item> pending = new ArrayList<>();
pending.add(new DashboardDistributionRespVO.Item("评论待审", orZero(commentMapper.selectCount(
Wrappers.<ContentComment>lambdaQuery().eq(ContentComment::getStatus, "pending")))));
pending.add(new DashboardDistributionRespVO.Item("举报待处理", orZero(reportMapper.selectCount(
Wrappers.<ContentReport>lambdaQuery().eq(ContentReport::getStatus, "pending")))));
vo.setPendingModeration(pending);
return vo;
}
/** 按日期查计数,空结果返回 0。 */
private long countForDate(String sql, LocalDate date) {
Long count = jdbcTemplate.queryForObject(sql, Long.class, date);
return count == null ? 0L : count;
}
/** 两列 GROUP BY 查询返回 Map<key, count>。 */
private Map<String, Long> groupBy(String sql) {
Map<String, Long> result = new LinkedHashMap<>();
jdbcTemplate.query(sql, rs -> {
result.put(rs.getString(1), rs.getLong(2));
});
return result;
}
private Map<String, Object> userMetrics(LocalDateTime todayStart, LocalDateTime sevenDaysAgo) { private Map<String, Object> userMetrics(LocalDateTime todayStart, LocalDateTime sevenDaysAgo) {
Map<String, Object> user = new LinkedHashMap<>(); Map<String, Object> user = new LinkedHashMap<>();
user.put("total", countUser(Wrappers.<AppUser>lambdaQuery())); user.put("total", countUser(Wrappers.<AppUser>lambdaQuery()));
@@ -125,9 +194,47 @@ public class DashboardService {
user.put("limited", countUser(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getStatus, "limited"))); user.put("limited", countUser(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getStatus, "limited")));
user.put("deactivated", countUser(Wrappers.<AppUser>lambdaQuery() user.put("deactivated", countUser(Wrappers.<AppUser>lambdaQuery()
.eq(AppUser::getStatus, "deactivated"))); .eq(AppUser::getStatus, "deactivated")));
putActiveDevices(user, sevenDaysAgo);
user.put("retention1d", retentionRate(todayStart.minusDays(1), todayStart, todayStart));
user.put("retention7d", retentionRate(
todayStart.minusDays(RETENTION_WINDOW_DAYS * 2L),
todayStart.minusDays(RETENTION_WINDOW_DAYS),
sevenDaysAgo));
return user; return user;
} }
/** 近 7 天仍活跃的安卓、iOS 设备,按设备号去重。 */
private void putActiveDevices(Map<String, Object> user, LocalDateTime since) {
Map<String, Long> counts = new LinkedHashMap<>();
jdbcTemplate.query("""
SELECT UPPER(platform), COUNT(DISTINCT device_id)
FROM app_user_device
WHERE deleted = 0 AND status = 'active' AND last_seen_at >= ?
GROUP BY UPPER(platform)
""", rs -> {
counts.put(rs.getString(1), rs.getLong(2));
}, since);
user.put("androidActive7d", counts.getOrDefault(PLATFORM_ANDROID, 0L));
user.put("iosActive7d", counts.getOrDefault(PLATFORM_IOS, 0L));
}
/** 队列留存率。注册队列为空时返回 null,避免把没有样本显示成 0%。 */
private Double retentionRate(LocalDateTime cohortStart, LocalDateTime cohortEnd, LocalDateTime returnedSince) {
Long cohort = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM app_user
WHERE deleted = 0 AND created_at >= ? AND created_at < ?
""", Long.class, cohortStart, cohortEnd);
if (cohort == null || cohort == 0L) {
return null;
}
Long returned = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM app_user
WHERE deleted = 0 AND created_at >= ? AND created_at < ? AND last_login_at >= ?
""", Long.class, cohortStart, cohortEnd, returnedSince);
long back = returned == null ? 0L : returned;
return Math.round(back * 1000.0 / cohort) / 1000.0;
}
private Map<String, Object> contentMetrics() { private Map<String, Object> contentMetrics() {
Map<String, Object> content = new LinkedHashMap<>(); Map<String, Object> content = new LinkedHashMap<>();
content.put("dramaTotal", dramaMapper.selectCount(null)); content.put("dramaTotal", dramaMapper.selectCount(null));
@@ -205,12 +312,12 @@ public class DashboardService {
private Map<String, Object> costMetrics(LocalDateTime sevenDaysAgo) { private Map<String, Object> costMetrics(LocalDateTime sevenDaysAgo) {
Map<String, Object> cost = new LinkedHashMap<>(); Map<String, Object> cost = new LinkedHashMap<>();
Map<String, Object> queue = transcodeService.stats(); TranscodeQueueStatsVO queue = transcodeService.stats();
cost.put("transcodeQueued", queue.get("queued")); cost.put("transcodeQueued", queue.getQueued());
cost.put("transcodeRunning", queue.get("running")); cost.put("transcodeRunning", queue.getRunning());
cost.put("transcodeFailed", queue.get("failed")); cost.put("transcodeFailed", queue.getFailed());
cost.put("transcodeSuccess", queue.get("success")); cost.put("transcodeSuccess", queue.getSuccess());
cost.put("renditions", queue.get("renditions")); cost.put("renditions", queue.getRenditions());
cost.put("otpSent7d", appUserOtpMapper.selectCount(Wrappers.<AppUserOtp>lambdaQuery() cost.put("otpSent7d", appUserOtpMapper.selectCount(Wrappers.<AppUserOtp>lambdaQuery()
.ge(AppUserOtp::getCreatedAt, sevenDaysAgo))); .ge(AppUserOtp::getCreatedAt, sevenDaysAgo)));
cost.put("cdnTrafficBytes", null); cost.put("cdnTrafficBytes", null);
@@ -222,6 +329,8 @@ public class DashboardService {
List<String> notes = new ArrayList<>(); List<String> notes = new ArrayList<>();
notes.add("DAU 暂无数据源:需要按天留存登录快照(ops_daily_stat 已建表但当前无产出)," notes.add("DAU 暂无数据源:需要按天留存登录快照(ops_daily_stat 已建表但当前无产出),"
+ "现以 active7d(近 7 天登录过)近似"); + "现以 active7d(近 7 天登录过)近似");
notes.add("androidActive7d / iosActive7d 是近 7 天 last_seen_at 仍活跃的去重设备,不是安装量");
notes.add("retention1d 是昨日注册且今天仍登录的比例;retention7d 是 8 至 14 天前注册、近 7 天仍登录的比例;队列为空时为 null");
notes.add("CDN 流量与带宽成本暂无数据源:需接入 CDN 账单或访问日志,cdnTrafficBytes 恒为 null"); notes.add("CDN 流量与带宽成本暂无数据源:需接入 CDN 账单或访问日志,cdnTrafficBytes 恒为 null");
notes.add("收入金额在商店未接入前恒为 0:订单表无真实商店订单,金币解锁收入请参考 coinConsumed"); notes.add("收入金额在商店未接入前恒为 0:订单表无真实商店订单,金币解锁收入请参考 coinConsumed");
notes.add("viewTotal/playTotal 是短剧表上的累计计数,与 playEvents7d 的流水口径不可相加"); notes.add("viewTotal/playTotal 是短剧表上的累计计数,与 playEvents7d 的流水口径不可相加");
@@ -0,0 +1,147 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.admin.vo.EngagementQueryReqVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUser;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
import com.fruitshorts.user.dal.mapper.AppUserMapper;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/** 后台互动列表的分页、预检索及批量资料读取。 */
@Component
@RequiredArgsConstructor
public class EngagementAdminLookup {
private static final int DEFAULT_PAGE_SIZE = 10;
private static final int MAX_PAGE_SIZE = 100;
/**
* 关键词预检索的 ID 上限:命中过多时 IN 列表会超出数据库参数上限,
* 也说明关键词过于宽泛,直接提示使用者补充条件而不是截断结果。
*/
private static final int MAX_LOOKUP_SIZE = 2000;
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
private final AppUserMapper userMapper;
private final DramaMapper dramaMapper;
private final AppDeviceProfileMapper deviceProfileMapper;
private final AppUserSessionMapper sessionMapper;
private final AppSessionSystemService sessionSystem;
/** 规范化页码和页大小。 */
public <T> Page<T> page(EngagementQueryReqVO req) {
int index = req.getPageIndex() == null ? 1 : Math.max(1, req.getPageIndex());
int size = req.getPageSize() == null || req.getPageSize() < 1
? DEFAULT_PAGE_SIZE : Math.min(MAX_PAGE_SIZE, req.getPageSize());
return new Page<>(index, size);
}
/** 按 uid 或昵称预检索,未传关键词时不限制用户。 */
public List<Long> userIds(String keyword) {
if (!StringUtils.hasText(keyword)) {
return null;
}
String value = keyword.trim();
List<Long> ids = userMapper.selectList(Wrappers.<AppUser>lambdaQuery().select(AppUser::getId)
.and(q -> q.like(AppUser::getUid, value).or().like(AppUser::getNickname, value))
.last("LIMIT " + LOOKUP_PROBE))
.stream().map(AppUser::getId).toList();
return ensureLookupSize(ids, "uid / 昵称");
}
/** 按剧名预检索,未传剧名时不限制短剧。 */
public List<Long> dramaIds(String title) {
if (!StringUtils.hasText(title)) {
return null;
}
List<Long> ids = dramaMapper.selectList(Wrappers.<Drama>lambdaQuery().select(Drama::getId)
.like(Drama::getTitle, title.trim())
.last("LIMIT " + LOOKUP_PROBE)).stream().map(Drama::getId).toList();
return ensureLookupSize(ids, "短剧名称");
}
/** 命中数量超限时给出可操作的提示,避免把整张表拉进 IN 条件。 */
private List<Long> ensureLookupSize(List<Long> ids, String field) {
if (ids.size() > MAX_LOOKUP_SIZE) {
throw new ServiceException(ErrorCode.BAD_REQUEST,
field + "命中超过 " + MAX_LOOKUP_SIZE + " 条,请使用更精确的筛选条件");
}
return ids;
}
/** 区分无筛选和有筛选但无匹配。 */
public boolean noMatch(List<Long> ids) {
return ids != null && ids.isEmpty();
}
/** 按非空去重 ID 批量读取用户,避免游客触发空 IN。 */
public Map<Long, AppUser> users(Collection<Long> ids) {
List<Long> keys = keys(ids);
return keys.isEmpty() ? Map.of() : userMapper.selectBatchIds(keys).stream()
.collect(Collectors.toMap(AppUser::getId, Function.identity()));
}
/** 按非空去重 ID 批量读取短剧。 */
public Map<Long, Drama> dramas(Collection<Long> ids) {
List<Long> keys = keys(ids);
return keys.isEmpty() ? Map.of() : dramaMapper.selectBatchIds(keys).stream()
.collect(Collectors.toMap(Drama::getId, Function.identity()));
}
/** 按 device_id 批量读取设备画像;游客也有记录,没建档的不返回。 */
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
List<String> keys = deviceIds.stream().filter(StringUtils::hasText)
.map(String::trim).distinct().toList();
return keys.isEmpty() ? Map.of() : deviceProfileMapper.selectList(
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))
.stream().collect(Collectors.toMap(AppDeviceProfile::getDeviceId,
Function.identity(), (first, second) -> first));
}
/**
* 每个用户取最近一次登录会话。
* 已登录用户的互动行 device_id 为空(写入时会清空),只能退回会话取系统。
*/
public Map<Long, AppUserSession> latestSessions(Collection<Long> userIds) {
List<Long> keys = keys(userIds);
if (keys.isEmpty()) {
return Map.of();
}
Map<Long, AppUserSession> result = new HashMap<>();
for (AppUserSession session : sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
.select(AppUserSession::getId, AppUserSession::getUserId,
AppUserSession::getPlatform)
.in(AppUserSession::getUserId, keys)
.orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId))) {
result.putIfAbsent(session.getUserId(), session);
}
return result;
}
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
public AppSessionSystemService.PlatformScope platformScope(String platform) {
return sessionSystem.platformScope(platform);
}
private List<Long> keys(Collection<Long> ids) {
return ids.stream().filter(Objects::nonNull).distinct().toList();
}
}
@@ -0,0 +1,103 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Locale;
/** 聚合剧集与媒资转码产物,供后台编辑页一次读取。 */
@Service
@RequiredArgsConstructor
public class EpisodeTranscodeAdminService {
private static final String STATUS_EPISODE_NOT_FOUND = "EPISODE_NOT_FOUND";
private static final String STATUS_NO_VIDEO = "NO_VIDEO";
private static final String STATUS_NO_MEDIA_ASSET = "NO_MEDIA_ASSET";
private static final String STATUS_NO_TASK = "NO_TASK";
private static final String REASON_EPISODE_NOT_FOUND = "分集不存在或已删除";
private static final String REASON_NO_VIDEO = "分集未配置视频";
private static final String REASON_NO_MEDIA_ASSET = "未找到分集视频对应的媒资";
private static final int THUMBNAIL_PAGE_INDEX = 1;
private static final int THUMBNAIL_PAGE_SIZE = 100;
private final DramaEpisodeMapper episodeMapper;
private final MediaTranscodeOutputService outputService;
public EpisodeTranscodeRespVO detail(Long episodeId) {
DramaEpisode episode = episodeId == null ? null : episodeMapper.selectById(episodeId);
if (episode == null) {
return empty(episodeId, STATUS_EPISODE_NOT_FOUND, REASON_EPISODE_NOT_FOUND);
}
boolean hasVideoAsset = episode.getVideoAssetId() != null
&& episode.getVideoAssetId() > 0;
if (!StringUtils.hasText(episode.getVideoUrl()) && !hasVideoAsset) {
return empty(episodeId, STATUS_NO_VIDEO, REASON_NO_VIDEO);
}
Long mediaAssetId = outputService.resolveMediaAssetId(episode.getVideoUrl());
if ((mediaAssetId == null || mediaAssetId <= 0) && hasVideoAsset
&& outputService.mediaAssetExists(episode.getVideoAssetId())) {
mediaAssetId = episode.getVideoAssetId();
}
if (mediaAssetId == null || mediaAssetId <= 0) {
return empty(episodeId, STATUS_NO_MEDIA_ASSET, REASON_NO_MEDIA_ASSET);
}
EpisodeTranscodeRespVO result = new EpisodeTranscodeRespVO();
result.setEpisodeId(idString(episodeId));
result.setMediaAssetId(idString(mediaAssetId));
result.setRenditions(outputService.renditionsForMediaAssetId(mediaAssetId));
result.setThumbnails(outputService.thumbnailForEpisode(
episodeId, mediaAssetId, THUMBNAIL_PAGE_INDEX, THUMBNAIL_PAGE_SIZE));
TranscodeTaskRespVO task = outputService.latestTask(mediaAssetId);
if (task == null) {
result.setStatus(taskStatusOf(episode));
result.setProgress(0);
result.setRetryCount(0);
result.setErrorMsg("");
result.setUpdatedAt(episode.getUpdatedAt());
return result;
}
result.setTaskId(idString(task.getId()));
result.setStatus(task.getStatus());
result.setProgress(task.getProgress());
result.setRetryCount(task.getRetryCount());
result.setErrorMsg(task.getErrorMsg());
result.setUpdatedAt(task.getUpdatedAt());
return result;
}
private EpisodeTranscodeRespVO empty(Long episodeId, String status, String reason) {
EpisodeTranscodeRespVO result = new EpisodeTranscodeRespVO();
result.setEpisodeId(idString(episodeId));
result.setStatus(status);
result.setProgress(0);
result.setRetryCount(0);
result.setErrorMsg(reason);
result.setRenditions(List.of());
result.setThumbnails(MediaThumbnailRespVO.empty(
null, episodeId, MediaThumbnailRespVO.STATUS_EMPTY,
THUMBNAIL_PAGE_INDEX, THUMBNAIL_PAGE_SIZE));
return result;
}
private String idString(Long id) {
return id == null ? null : String.valueOf(id);
}
private String taskStatusOf(DramaEpisode episode) {
return StringUtils.hasText(episode.getTranscodeStatus())
? episode.getTranscodeStatus().toUpperCase(Locale.ROOT)
: STATUS_NO_TASK;
}
}
@@ -0,0 +1,117 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.admin.vo.AdminFavoriteVO;
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.enums.ContentStatus;
import com.fruitshorts.playback.dal.entity.UserFavorite;
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUser;
import com.fruitshorts.user.dal.entity.AppUserSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/** 后台收藏只读分页及跨域资料装配。 */
@Service
@RequiredArgsConstructor
public class FavoriteAdminService {
private final UserFavoriteMapper favoriteMapper;
private final EngagementAdminLookup lookup;
/** 分页查询收藏,预检索无匹配时直接返回空页。 */
public PageResult<AdminFavoriteVO> page(FavoriteQueryReqVO req) {
List<Long> userIds = lookup.userIds(req.getKeyword());
if (lookup.noMatch(userIds)) {
return PageResult.empty();
}
List<Long> dramaIds = lookup.dramaIds(req.getDramaTitle());
if (lookup.noMatch(dramaIds)) {
return PageResult.empty();
}
var scope = lookup.platformScope(req.getPlatform());
if (scope != null && scope.empty()) {
return PageResult.empty();
}
var query = Wrappers.<UserFavorite>lambdaQuery()
.eq(req.getUserId() != null, UserFavorite::getUserId, req.getUserId())
.in(userIds != null, UserFavorite::getUserId, userIds)
.eq(StringUtils.hasText(req.getDeviceId()), UserFavorite::getDeviceId, req.getDeviceId())
.eq(req.getDramaId() != null, UserFavorite::getDramaId, req.getDramaId())
.in(dramaIds != null, UserFavorite::getDramaId, dramaIds)
.ge(req.getStartTime() != null, UserFavorite::getCreatedAt, req.getStartTime())
.le(req.getEndTime() != null, UserFavorite::getCreatedAt, req.getEndTime());
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
if (scope != null) {
query.and(inner -> {
if (!scope.deviceIds().isEmpty()) {
inner.in(UserFavorite::getDeviceId, scope.deviceIds());
}
if (!scope.userIds().isEmpty()) {
if (!scope.deviceIds().isEmpty()) {
inner.or();
}
inner.in(UserFavorite::getUserId, scope.userIds());
}
});
}
query.orderByDesc(UserFavorite::getCreatedAt, UserFavorite::getId);
var result = favoriteMapper.selectPage(lookup.page(req), query);
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
}
private List<AdminFavoriteVO> assemble(List<UserFavorite> rows) {
if (rows.isEmpty()) {
return List.of();
}
Map<Long, AppUser> users = lookup.users(rows.stream().map(UserFavorite::getUserId).toList());
Map<Long, Drama> dramas = lookup.dramas(rows.stream().map(UserFavorite::getDramaId).toList());
Map<String, AppDeviceProfile> profiles =
lookup.deviceProfiles(rows.stream().map(UserFavorite::getDeviceId).toList());
Map<Long, AppUserSession> sessions =
lookup.latestSessions(rows.stream().map(UserFavorite::getUserId).toList());
return rows.stream().map(row -> toVo(row, row.getUserId() == null ? null : users.get(row.getUserId()),
row.getDramaId() == null ? null : dramas.get(row.getDramaId()),
row.getDeviceId() == null ? null : profiles.get(row.getDeviceId()),
row.getUserId() == null ? null : sessions.get(row.getUserId())))
.toList();
}
private AdminFavoriteVO toVo(UserFavorite row, AppUser user, Drama drama,
AppDeviceProfile profile, AppUserSession session) {
AdminFavoriteVO vo = new AdminFavoriteVO();
vo.setId(row.getId());
vo.setUserId(row.getUserId());
vo.setDeviceId(row.getDeviceId());
vo.setAnonymous(row.getUserId() == null);
if (profile != null) {
vo.setPlatform(profile.getPlatform());
}
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
if (!StringUtils.hasText(vo.getPlatform()) && session != null) {
vo.setPlatform(session.getPlatform());
}
vo.setDramaId(row.getDramaId());
vo.setCreatedAt(row.getCreatedAt());
if (user != null) {
vo.setUid(user.getUid());
vo.setNickname(user.getNickname());
}
if (drama != null) {
vo.setDramaTitle(drama.getTitle());
vo.setDramaCover(drama.getCoverUrl());
vo.setDramaStatus(drama.getStatus());
vo.setDramaPublished(ContentStatus.PUBLISHED.getCode().equals(drama.getStatus()));
}
// 短剧读不到(已删除或数据异常)时保持 dramaPublished 为 null,
// 与「未发布」区分开,前端只在明确 false 时才展示未发布标记。
return vo;
}
}
@@ -0,0 +1,210 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.admin.vo.AdminLikeVO;
import com.fruitshorts.admin.vo.LikeQueryReqVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.interaction.dal.entity.ContentComment;
import com.fruitshorts.interaction.dal.entity.ContentLike;
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUser;
import com.fruitshorts.user.dal.entity.AppUserSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
/** 后台点赞只读分页及多态目标批量装配。 */
@Service
@RequiredArgsConstructor
public class LikeAdminService {
private static final String DRAMA = "DRAMA";
private static final String EPISODE = "EPISODE";
private static final String COMMENT = "COMMENT";
private static final int SUMMARY_LENGTH = 30;
/**
* 点赞目标是多态列(target_type + target_id),按短剧/剧集筛选必须跨表回溯,
* 无法用 LambdaQueryWrapper 表达,只能写原生片段。
* 维护约定:表名、逻辑删除列与 {@code drama_episode} / {@code content_comment}
* 实体上的 @TableName / @TableLogic 保持一致,改表结构时需要同步修改这里。
*/
private static final String DRAMA_MATCH =
"(target_type = 'DRAMA' AND target_id = {0}) OR "
+ "(target_type = 'EPISODE' AND EXISTS (SELECT 1 FROM drama_episode e "
+ "WHERE e.id = target_id AND e.deleted = 0 AND e.drama_id = {0})) OR "
+ "(target_type = 'COMMENT' AND EXISTS (SELECT 1 FROM content_comment c "
+ "WHERE c.id = target_id AND c.deleted = 0 AND c.drama_id = {0}))";
private static final String EPISODE_MATCH =
"(target_type = 'EPISODE' AND target_id = {0}) OR "
+ "(target_type = 'COMMENT' AND EXISTS (SELECT 1 FROM content_comment c "
+ "WHERE c.id = target_id AND c.deleted = 0 AND c.episode_id = {0}))";
private final ContentLikeMapper likeMapper;
private final ContentCommentMapper commentMapper;
private final DramaEpisodeMapper episodeMapper;
private final EngagementAdminLookup lookup;
/** 分页查询点赞;短剧及剧集条件在分页之前作用于各类目标。 */
public PageResult<AdminLikeVO> page(LikeQueryReqVO req) {
List<Long> users = lookup.userIds(req.getKeyword());
if (lookup.noMatch(users)) {
return PageResult.empty();
}
List<Long> dramas = lookup.dramaIds(req.getDramaTitle());
if (lookup.noMatch(dramas)) {
return PageResult.empty();
}
var query = buildQuery(req, users);
var scope = lookup.platformScope(req.getPlatform());
if (scope != null && scope.empty()) {
return PageResult.empty();
}
if (scope != null) {
query.and(inner -> {
if (!scope.deviceIds().isEmpty()) {
inner.in(ContentLike::getDeviceId, scope.deviceIds());
}
if (!scope.userIds().isEmpty()) {
if (!scope.deviceIds().isEmpty()) {
inner.or();
}
inner.in(ContentLike::getUserId, scope.userIds());
}
});
}
if (req.getDramaId() != null) {
query.and(q -> q.apply(DRAMA_MATCH, req.getDramaId()));
}
if (dramas != null) {
query.and(q -> {
for (Long id : dramas) {
q.or().apply(DRAMA_MATCH, id);
}
});
}
if (req.getEpisodeId() != null) {
query.and(q -> q.apply(EPISODE_MATCH, req.getEpisodeId()));
}
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
query.orderByDesc(ContentLike::getCreatedAt, ContentLike::getId);
var result = likeMapper.selectPage(lookup.page(req), query);
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
}
private LambdaQueryWrapper<ContentLike> buildQuery(LikeQueryReqVO req, List<Long> users) {
return Wrappers.<ContentLike>lambdaQuery()
.eq(req.getUserId() != null, ContentLike::getUserId, req.getUserId())
.in(users != null, ContentLike::getUserId, users)
.eq(StringUtils.hasText(req.getDeviceId()), ContentLike::getDeviceId, req.getDeviceId())
.eq(StringUtils.hasText(req.getTargetType()), ContentLike::getTargetType, req.getTargetType())
.eq(req.getTargetId() != null, ContentLike::getTargetId, req.getTargetId())
.ge(req.getStartTime() != null, ContentLike::getCreatedAt, req.getStartTime())
.le(req.getEndTime() != null, ContentLike::getCreatedAt, req.getEndTime());
}
private List<AdminLikeVO> assemble(List<ContentLike> rows) {
if (rows.isEmpty()) {
return List.of();
}
Map<Long, AppUser> users = lookup.users(rows.stream().map(ContentLike::getUserId).toList());
Map<Long, ContentComment> comments = comments(targetIds(rows, COMMENT));
List<Long> episodeIds = new ArrayList<>(targetIds(rows, EPISODE));
comments.values().stream().map(ContentComment::getEpisodeId).filter(Objects::nonNull)
.forEach(episodeIds::add);
Map<Long, DramaEpisode> episodes = episodes(episodeIds);
List<Long> dramaIds = new ArrayList<>(targetIds(rows, DRAMA));
comments.values().stream().map(ContentComment::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
episodes.values().stream().map(DramaEpisode::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
Map<Long, Drama> dramas = lookup.dramas(dramaIds);
Map<String, AppDeviceProfile> profiles =
lookup.deviceProfiles(rows.stream().map(ContentLike::getDeviceId).toList());
Map<Long, AppUserSession> sessions =
lookup.latestSessions(rows.stream().map(ContentLike::getUserId).toList());
return rows.stream()
.map(row -> toVo(row, users, comments, episodes, dramas, profiles, sessions))
.toList();
}
private List<Long> targetIds(List<ContentLike> rows, String type) {
return rows.stream().filter(row -> type.equals(row.getTargetType())).map(ContentLike::getTargetId)
.filter(Objects::nonNull).distinct().toList();
}
private Map<Long, ContentComment> comments(Collection<Long> ids) {
return ids.isEmpty() ? Map.of() : commentMapper.selectBatchIds(ids).stream()
.collect(Collectors.toMap(ContentComment::getId, Function.identity()));
}
private Map<Long, DramaEpisode> episodes(Collection<Long> ids) {
List<Long> keys = ids.stream().filter(Objects::nonNull).distinct().toList();
return keys.isEmpty() ? Map.of() : episodeMapper.selectBatchIds(keys).stream()
.collect(Collectors.toMap(DramaEpisode::getId, Function.identity()));
}
private AdminLikeVO toVo(ContentLike row, Map<Long, AppUser> users, Map<Long, ContentComment> comments,
Map<Long, DramaEpisode> episodes, Map<Long, Drama> dramas,
Map<String, AppDeviceProfile> profiles,
Map<Long, AppUserSession> sessions) {
AdminLikeVO vo = new AdminLikeVO();
vo.setId(row.getId());
vo.setUserId(row.getUserId());
vo.setDeviceId(row.getDeviceId());
vo.setAnonymous(row.getUserId() == null);
AppDeviceProfile profile = row.getDeviceId() == null ? null : profiles.get(row.getDeviceId());
if (profile != null) {
vo.setPlatform(profile.getPlatform());
}
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
if (!StringUtils.hasText(vo.getPlatform()) && row.getUserId() != null) {
AppUserSession session = sessions.get(row.getUserId());
if (session != null) {
vo.setPlatform(session.getPlatform());
}
}
vo.setTargetType(row.getTargetType());
vo.setTargetId(row.getTargetId());
vo.setCreatedAt(row.getCreatedAt());
AppUser user = row.getUserId() == null ? null : users.get(row.getUserId());
if (user != null) {
vo.setUid(user.getUid());
vo.setNickname(user.getNickname());
}
ContentComment comment = COMMENT.equals(row.getTargetType()) ? comments.get(row.getTargetId()) : null;
Long episodeId = EPISODE.equals(row.getTargetType()) ? row.getTargetId()
: comment == null ? null : comment.getEpisodeId();
DramaEpisode episode = episodeId == null ? null : episodes.get(episodeId);
Long dramaId = DRAMA.equals(row.getTargetType()) ? row.getTargetId()
: comment != null ? comment.getDramaId() : episode == null ? null : episode.getDramaId();
vo.setEpisodeId(episodeId);
vo.setDramaId(dramaId);
if (comment != null && comment.getContent() != null) {
String content = comment.getContent();
int count = content.codePointCount(0, content.length());
vo.setCommentSummary(content.substring(0, content.offsetByCodePoints(0, Math.min(count, SUMMARY_LENGTH))));
}
if (episode != null) {
vo.setEpisodeNo(episode.getEpNo());
vo.setEpisodeTitle(episode.getTitle());
}
Drama drama = dramaId == null ? null : dramas.get(dramaId);
if (drama != null) {
vo.setDramaTitle(drama.getTitle());
vo.setDramaCover(drama.getCoverUrl());
}
return vo;
}
}
@@ -0,0 +1,112 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.TranscodeBackfillRespVO;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.media.config.MediaTranscodeProfile;
import com.fruitshorts.media.dal.entity.MediaAsset;
import com.fruitshorts.media.dal.entity.TranscodeTask;
import com.fruitshorts.media.dal.mapper.MediaAssetMapper;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.media.vo.TranscodeTriggerRespVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 手动触发一轮转码补齐巡检:找出"有片源但缺少码率产物或缩略图"的分集并入队。
*
* <p>与 worker 的定时巡检(TranscodeBackfillScanner)共用同一条候选 SQL 与 trigger 语义;
* 区别在于手动触发允许重试最近一次 FAILED 的任务——运营点按钮就是要补齐,包括失败重跑。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class TranscodeBackfillAdminService {
private static final int MIN_BATCH_SIZE = 1;
private static final int MAX_BATCH_SIZE = 100;
private static final int DEFAULT_BATCH_SIZE = 20;
private final DramaEpisodeMapper episodeMapper;
private final TranscodeService transcodeService;
private final MediaAssetMapper mediaAssetMapper;
private final MediaTranscodeOutputService outputService;
private final MediaTranscodeProfileService profileService;
/**
* 扫描一批缺产物的分集并入队。
*
* @param requestedBatchSize 单轮上限,超出范围时收敛到默认值
* @return 入队结果与明细
*/
public TranscodeBackfillRespVO runOnce(Integer requestedBatchSize) {
int batchSize = normalizeBatchSize(requestedBatchSize);
List<DramaEpisode> candidates = episodeMapper.selectTranscodeBackfillCandidates(
0L, batchSize, framesRequired());
List<TranscodeBackfillRespVO.Item> items = new ArrayList<>();
if (candidates == null || candidates.isEmpty()) {
return new TranscodeBackfillRespVO(0, items);
}
for (DramaEpisode episode : candidates) {
triggerIfNeeded(episode, items);
}
log.info("后台手动补齐转码:候选 {} 个,实际入队 {} 个",
candidates.size(), items.size());
return new TranscodeBackfillRespVO(items.size(), items);
}
private void triggerIfNeeded(DramaEpisode episode,
List<TranscodeBackfillRespVO.Item> items) {
Long mediaAssetId = resolveMediaAssetId(episode);
if (mediaAssetId == null) {
log.warn("分集 {} 找不到对应媒资,跳过补齐转码", episode.getId());
return;
}
TranscodeTask latest = transcodeService.findLatestTaskByMediaAssetId(mediaAssetId);
if (latest != null && (TranscodeService.STATUS_QUEUED.equals(latest.getStatus())
|| TranscodeService.STATUS_RUNNING.equals(latest.getStatus()))) {
return;
}
MediaAsset asset = mediaAssetMapper.selectById(mediaAssetId);
if (asset == null) {
log.warn("分集 {} 绑定的媒资 {} 不存在,跳过补齐转码",
episode.getId(), mediaAssetId);
return;
}
TranscodeTriggerRespVO result = transcodeService.trigger(
mediaAssetId, asset.getSourceUrl(), episode.getDramaId(), episode.getId());
items.add(new TranscodeBackfillRespVO.Item(
String.valueOf(episode.getId()),
result == null ? "" : String.valueOf(result.getTaskId())));
}
/** 优先用分集已绑定的媒资,老数据没有绑定则按视频地址反查。 */
private Long resolveMediaAssetId(DramaEpisode episode) {
Long videoAssetId = episode.getVideoAssetId();
if (videoAssetId != null && videoAssetId > 0) {
return videoAssetId;
}
return outputService.resolveMediaAssetId(episode.getVideoUrl());
}
/** 关闭雪碧图时不会产出缩略图,此时只看码率产物,避免误判重复转码。 */
private boolean framesRequired() {
MediaTranscodeProfile profile = profileService.currentProfile();
return profile != null && profile.getSprite() != null && profile.getSprite().isEnabled();
}
private int normalizeBatchSize(Integer requestedBatchSize) {
if (requestedBatchSize == null || requestedBatchSize <= 0) {
return DEFAULT_BATCH_SIZE;
}
return Math.min(requestedBatchSize, MAX_BATCH_SIZE);
}
}
@@ -0,0 +1,84 @@
// Author: fruit.com.cn
// 转码通知:按状态计数,并带出短剧与集数。
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 转码通知。
* 转码中、成功、失败分别计数,列表带出短剧名和集数。
*/
@Service
public class TranscodeNoticeService {
private static final int NOTICE_LIMIT = 20;
private static final String STATUS_RUNNING = "RUNNING";
private static final String STATUS_SUCCESS = "SUCCESS";
private static final String STATUS_FAILED = "FAILED";
private static final String UNKNOWN_DRAMA = "未关联短剧";
private final JdbcTemplate jdbcTemplate;
public TranscodeNoticeService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/** 角标数量和最近 20 条转码中、成功、失败任务。 */
public TranscodeNoticeRespVO notices() {
TranscodeNoticeRespVO data = new TranscodeNoticeRespVO();
fillCounts(data);
data.setRunningList(latest(STATUS_RUNNING));
data.setSuccessList(latest(STATUS_SUCCESS));
data.setFailedList(latest(STATUS_FAILED));
return data;
}
private void fillCounts(TranscodeNoticeRespVO data) {
jdbcTemplate.query("""
SELECT status, COUNT(*)
FROM transcode_task
WHERE deleted = 0 AND status IN (?, ?, ?)
GROUP BY status
""", rs -> {
long count = rs.getLong(2);
switch (rs.getString(1)) {
case STATUS_RUNNING -> data.setRunning(count);
case STATUS_SUCCESS -> data.setSuccess(count);
case STATUS_FAILED -> data.setFailed(count);
default -> {
}
}
}, STATUS_RUNNING, STATUS_SUCCESS, STATUS_FAILED);
}
private List<TranscodeNoticeRespVO.Item> latest(String status) {
return jdbcTemplate.query("""
SELECT t.id, t.status, t.progress, t.error_msg, t.updated_at,
COALESCE(NULLIF(d.title, ''), NULLIF(d2.title, ''), ?) AS drama_title,
e.ep_no, e.title
FROM transcode_task t
LEFT JOIN drama_episode e ON e.id = t.episode_id AND e.deleted = 0
LEFT JOIN drama d ON d.id = t.drama_id AND d.deleted = 0
LEFT JOIN drama d2 ON d2.id = e.drama_id AND d2.deleted = 0
WHERE t.deleted = 0 AND t.status = ?
ORDER BY t.updated_at DESC
LIMIT ?
""", (rs, row) -> {
TranscodeNoticeRespVO.Item item = new TranscodeNoticeRespVO.Item();
item.setId(rs.getLong("id"));
item.setStatus(rs.getString("status"));
item.setProgress(rs.getInt("progress"));
item.setErrorMsg(rs.getString("error_msg"));
item.setUpdatedAt(rs.getTimestamp("updated_at").toLocalDateTime());
item.setDramaTitle(rs.getString("drama_title"));
item.setEpisodeNo((Integer) rs.getObject("ep_no"));
item.setEpisodeTitle(rs.getString("title"));
return item;
}, UNKNOWN_DRAMA, status, NOTICE_LIMIT);
}
}
@@ -8,6 +8,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.admin.vo.AdminWatchHistoryVO; import com.fruitshorts.admin.vo.AdminWatchHistoryVO;
import com.fruitshorts.admin.vo.WatchHistoryQueryReqVO; import com.fruitshorts.admin.vo.WatchHistoryQueryReqVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
@@ -16,7 +18,9 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.enums.ContentStatus; import com.fruitshorts.content.enums.ContentStatus;
import com.fruitshorts.playback.dal.entity.WatchHistory; import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper; import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUser; import com.fruitshorts.user.dal.entity.AppUser;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppUserMapper; import com.fruitshorts.user.dal.mapper.AppUserMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -26,6 +30,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* 后台观看记录分页与跨域装配。 * 后台观看记录分页与跨域装配。
@@ -41,11 +46,14 @@ public class WatchHistoryAdminService {
private static final int DEFAULT_PAGE_SIZE = 10; private static final int DEFAULT_PAGE_SIZE = 10;
private static final int MAX_PAGE_SIZE = 100; private static final int MAX_PAGE_SIZE = 100;
private static final long FINISHED_TOLERANCE_MS = 1000L; private static final long FINISHED_TOLERANCE_MS = 1000L;
private static final int MAX_LOOKUP_SIZE = 2000;
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
private final WatchHistoryMapper watchHistoryMapper; private final WatchHistoryMapper watchHistoryMapper;
private final AppUserMapper appUserMapper; private final AppUserMapper appUserMapper;
private final DramaMapper dramaMapper; private final DramaMapper dramaMapper;
private final DramaEpisodeMapper dramaEpisodeMapper; private final DramaEpisodeMapper dramaEpisodeMapper;
private final AppSessionSystemService sessionSystem;
/** 按后台筛选条件分页查询观看记录。 */ /** 按后台筛选条件分页查询观看记录。 */
public PageResult<AdminWatchHistoryVO> page(WatchHistoryQueryReqVO req) { public PageResult<AdminWatchHistoryVO> page(WatchHistoryQueryReqVO req) {
@@ -63,14 +71,19 @@ public class WatchHistoryAdminService {
if (matchedDramaIds != null && matchedDramaIds.isEmpty()) { if (matchedDramaIds != null && matchedDramaIds.isEmpty()) {
return emptyPage(); return emptyPage();
} }
var scope = sessionSystem.platformScope(req.getPlatform());
if (scope != null && scope.empty()) {
return emptyPage();
}
IPage<WatchHistory> result = watchHistoryMapper.selectPage(new Page<>(pageIndex, pageSize), IPage<WatchHistory> result = watchHistoryMapper.selectPage(new Page<>(pageIndex, pageSize),
buildQuery(req, matchedUserIds, matchedDramaIds)); buildQuery(req, matchedUserIds, matchedDramaIds, scope));
return new PageResult<>(result.getTotal(), toVoList(result.getRecords())); return new PageResult<>(result.getTotal(), toVoList(result.getRecords()));
} }
private LambdaQueryWrapper<WatchHistory> buildQuery(WatchHistoryQueryReqVO req, private LambdaQueryWrapper<WatchHistory> buildQuery(WatchHistoryQueryReqVO req,
List<Long> matchedUserIds, List<Long> matchedUserIds,
List<Long> matchedDramaIds) { List<Long> matchedDramaIds,
AppSessionSystemService.PlatformScope scope) {
LambdaQueryWrapper<WatchHistory> wrapper = Wrappers.<WatchHistory>lambdaQuery() LambdaQueryWrapper<WatchHistory> wrapper = Wrappers.<WatchHistory>lambdaQuery()
.eq(req.getUserId() != null, WatchHistory::getUserId, req.getUserId()) .eq(req.getUserId() != null, WatchHistory::getUserId, req.getUserId())
.in(matchedUserIds != null, WatchHistory::getUserId, matchedUserIds) .in(matchedUserIds != null, WatchHistory::getUserId, matchedUserIds)
@@ -80,6 +93,19 @@ public class WatchHistoryAdminService {
.eq(StringUtils.hasText(req.getSource()), WatchHistory::getSource, req.getSource()) .eq(StringUtils.hasText(req.getSource()), WatchHistory::getSource, req.getSource())
.ge(req.getStartTime() != null, WatchHistory::getWatchedAt, req.getStartTime()) .ge(req.getStartTime() != null, WatchHistory::getWatchedAt, req.getStartTime())
.le(req.getEndTime() != null, WatchHistory::getWatchedAt, req.getEndTime()); .le(req.getEndTime() != null, WatchHistory::getWatchedAt, req.getEndTime());
if (scope != null) {
wrapper.and(inner -> {
if (!scope.deviceIds().isEmpty()) {
inner.in(WatchHistory::getDeviceId, scope.deviceIds());
}
if (!scope.userIds().isEmpty()) {
if (!scope.deviceIds().isEmpty()) {
inner.or();
}
inner.in(WatchHistory::getUserId, scope.userIds());
}
});
}
applyFinished(wrapper, req.getFinished()); applyFinished(wrapper, req.getFinished());
return wrapper.orderByDesc(WatchHistory::getWatchedAt) return wrapper.orderByDesc(WatchHistory::getWatchedAt)
.orderByDesc(WatchHistory::getId); .orderByDesc(WatchHistory::getId);
@@ -98,24 +124,37 @@ public class WatchHistoryAdminService {
private List<Long> searchUserIds(String keyword) { private List<Long> searchUserIds(String keyword) {
String value = keyword.trim(); String value = keyword.trim();
return appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery() List<Long> ids = appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
.select(AppUser::getId) .select(AppUser::getId)
.and(query -> query.like(AppUser::getUid, value) .and(query -> query.like(AppUser::getUid, value)
.or() .or()
.like(AppUser::getNickname, value))) .like(AppUser::getNickname, value))
.last("LIMIT " + LOOKUP_PROBE))
.stream() .stream()
.map(AppUser::getId) .map(AppUser::getId)
.toList(); .toList();
return ensureLookupSize(ids, "uid / 昵称");
} }
private List<Long> searchDramaIds(String dramaTitle) { private List<Long> searchDramaIds(String dramaTitle) {
String value = dramaTitle.trim(); String value = dramaTitle.trim();
return dramaMapper.selectList(Wrappers.<Drama>lambdaQuery() List<Long> ids = dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
.select(Drama::getId) .select(Drama::getId)
.like(Drama::getTitle, value)) .like(Drama::getTitle, value)
.last("LIMIT " + LOOKUP_PROBE))
.stream() .stream()
.map(Drama::getId) .map(Drama::getId)
.toList(); .toList();
return ensureLookupSize(ids, "短剧名称");
}
/** 关键词命中过多时直接提示收窄条件,避免把整张表塞进 IN。 */
private List<Long> ensureLookupSize(List<Long> ids, String field) {
if (ids.size() > MAX_LOOKUP_SIZE) {
throw new ServiceException(ErrorCode.BAD_REQUEST,
field + "命中超过 " + MAX_LOOKUP_SIZE + " 条,请使用更精确的筛选条件");
}
return ids;
} }
private List<AdminWatchHistoryVO> toVoList(List<WatchHistory> rows) { private List<AdminWatchHistoryVO> toVoList(List<WatchHistory> rows) {
@@ -125,18 +164,30 @@ public class WatchHistoryAdminService {
Map<Long, AppUser> users = loadUsers(rows); Map<Long, AppUser> users = loadUsers(rows);
Map<Long, Drama> dramas = loadDramas(rows); Map<Long, Drama> dramas = loadDramas(rows);
Map<Long, DramaEpisode> episodes = loadEpisodes(rows); Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
rows.stream().map(WatchHistory::getUserId).distinct().toList());
Map<String, AppDeviceProfile> profiles = sessionSystem.deviceProfiles(
rows.stream().map(WatchHistory::getDeviceId).toList());
List<AdminWatchHistoryVO> list = new ArrayList<>(rows.size()); List<AdminWatchHistoryVO> list = new ArrayList<>(rows.size());
for (WatchHistory row : rows) { for (WatchHistory row : rows) {
list.add(toVo(row, users.get(row.getUserId()), dramas.get(row.getDramaId()), list.add(toVo(row, users.get(row.getUserId()), dramas.get(row.getDramaId()),
episodes.get(row.getEpisodeId()))); episodes.get(row.getEpisodeId()),
sessionSystem.match(sessions.get(row.getUserId()), row.getDeviceId()),
profiles.get(row.getDeviceId())));
} }
return list; return list;
} }
private Map<Long, AppUser> loadUsers(List<WatchHistory> rows) { private Map<Long, AppUser> loadUsers(List<WatchHistory> rows) {
Map<Long, AppUser> result = new HashMap<>(); Map<Long, AppUser> result = new HashMap<>();
List<Long> ids = rows.stream().map(WatchHistory::getUserId).distinct().toList(); List<Long> ids = rows.stream().map(WatchHistory::getUserId).filter(Objects::nonNull).distinct().toList();
for (AppUser user : appUserMapper.selectBatchIds(ids)) { if (ids.isEmpty()) {
return result;
}
// 列表只需要身份展示字段,避免把整行用户资料拉回来
for (AppUser user : appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
.select(AppUser::getId, AppUser::getUid, AppUser::getNickname)
.in(AppUser::getId, ids))) {
result.put(user.getId(), user); result.put(user.getId(), user);
} }
return result; return result;
@@ -144,8 +195,13 @@ public class WatchHistoryAdminService {
private Map<Long, Drama> loadDramas(List<WatchHistory> rows) { private Map<Long, Drama> loadDramas(List<WatchHistory> rows) {
Map<Long, Drama> result = new HashMap<>(); Map<Long, Drama> result = new HashMap<>();
List<Long> ids = rows.stream().map(WatchHistory::getDramaId).distinct().toList(); List<Long> ids = rows.stream().map(WatchHistory::getDramaId).filter(Objects::nonNull).distinct().toList();
for (Drama drama : dramaMapper.selectBatchIds(ids)) { if (ids.isEmpty()) {
return result;
}
for (Drama drama : dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
.select(Drama::getId, Drama::getTitle, Drama::getStatus)
.in(Drama::getId, ids))) {
result.put(drama.getId(), drama); result.put(drama.getId(), drama);
} }
return result; return result;
@@ -153,15 +209,22 @@ public class WatchHistoryAdminService {
private Map<Long, DramaEpisode> loadEpisodes(List<WatchHistory> rows) { private Map<Long, DramaEpisode> loadEpisodes(List<WatchHistory> rows) {
Map<Long, DramaEpisode> result = new HashMap<>(); Map<Long, DramaEpisode> result = new HashMap<>();
List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).distinct().toList(); List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).filter(Objects::nonNull).distinct().toList();
for (DramaEpisode episode : dramaEpisodeMapper.selectBatchIds(ids)) { if (ids.isEmpty()) {
return result;
}
for (DramaEpisode episode : dramaEpisodeMapper.selectList(Wrappers.<DramaEpisode>lambdaQuery()
.select(DramaEpisode::getId, DramaEpisode::getDramaId,
DramaEpisode::getEpNo, DramaEpisode::getTitle)
.in(DramaEpisode::getId, ids))) {
result.put(episode.getId(), episode); result.put(episode.getId(), episode);
} }
return result; return result;
} }
private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama, private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama,
DramaEpisode episode) { DramaEpisode episode, AppUserSession session,
AppDeviceProfile profile) {
AdminWatchHistoryVO vo = new AdminWatchHistoryVO(); AdminWatchHistoryVO vo = new AdminWatchHistoryVO();
vo.setId(row.getId()); vo.setId(row.getId());
vo.setUserId(row.getUserId()); vo.setUserId(row.getUserId());
@@ -172,6 +235,13 @@ public class WatchHistoryAdminService {
vo.setSource(row.getSource()); vo.setSource(row.getSource());
vo.setDeviceId(row.getDeviceId()); vo.setDeviceId(row.getDeviceId());
vo.setWatchedAt(row.getWatchedAt()); vo.setWatchedAt(row.getWatchedAt());
// 设备平台不依赖登录态,优先;没有记录(老数据)再回退到登录会话
if (profile != null && StringUtils.hasText(profile.getPlatform())) {
vo.setPlatform(profile.getPlatform());
} else if (session != null) {
vo.setPlatform(session.getPlatform());
vo.setOsVersion(session.getOsVersion());
}
long position = row.getPositionMs() == null ? 0L : row.getPositionMs(); long position = row.getPositionMs() == null ? 0L : row.getPositionMs();
long duration = row.getDurationMs() == null ? 0L : row.getDurationMs(); long duration = row.getDurationMs() == null ? 0L : row.getDurationMs();
vo.setFinished(duration > 0L && position + FINISHED_TOLERANCE_MS >= duration); vo.setFinished(duration > 0L && position + FINISHED_TOLERANCE_MS >= duration);
@@ -0,0 +1,26 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 后台收藏只读列表行,保留游客设备信息。 */
@Data
public class AdminFavoriteVO {
private Long id;
private Long userId;
private String uid;
private String nickname;
private String deviceId;
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
private String platform;
private Boolean anonymous;
private Long dramaId;
private String dramaTitle;
private String dramaCover;
private String dramaStatus;
/** true=已发布,false=未发布,null=短剧已不存在(不代表未发布)。 */
private Boolean dramaPublished;
private LocalDateTime createdAt;
}
@@ -0,0 +1,29 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.Data;
import java.time.LocalDateTime;
/** 后台点赞只读列表行,保留游客设备信息。 */
@Data
public class AdminLikeVO {
private Long id;
private Long userId;
private String uid;
private String nickname;
private String deviceId;
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
private String platform;
private Boolean anonymous;
private Long dramaId;
private String dramaTitle;
private String dramaCover;
private String targetType;
private Long targetId;
private Long episodeId;
private Integer episodeNo;
private String episodeTitle;
private String commentSummary;
private LocalDateTime createdAt;
}
@@ -29,5 +29,9 @@ public class AdminWatchHistoryVO {
private Boolean finished; private Boolean finished;
private String source; private String source;
private String deviceId; private String deviceId;
/** ANDROID / IOS / WEB,来自该次设备的登录会话。 */
private String platform;
/** 系统版本,例如 Android 16。 */
private String osVersion;
private LocalDateTime watchedAt; private LocalDateTime watchedAt;
} }
@@ -28,5 +28,9 @@ public class AppUserWatchHistoryVO {
private Boolean finished; private Boolean finished;
private String source; private String source;
private String deviceId; private String deviceId;
/** ANDROID / IOS / WEB,来自该次设备的登录会话。 */
private String platform;
/** 系统版本。 */
private String osVersion;
private LocalDateTime watchedAt; private LocalDateTime watchedAt;
} }
@@ -0,0 +1,39 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/** 运营大盘分布(给饼图用)。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DashboardDistributionRespVO {
/** 短剧状态分布:key = 状态码,value = 数量;含 total 汇总。 */
private Map<String, Long> dramaStatus;
/** 转码任务状态分布。 */
private Map<String, Long> transcodeStatus;
/** 有片源 / 无片源剧集分布。 */
private Map<String, Long> episodeMedia;
/** 互动待处理:评论待审、举报待审。 */
private List<Item> pendingModeration;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Item {
private String label;
private Long value;
}
}
@@ -0,0 +1,31 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/** 运营大盘趋势(近 N 天每日数据,给折线图用)。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DashboardTrendRespVO {
/** 日期标签,格式 yyyy-MM-dd,从最早到最新。 */
private List<String> dates;
/** 每日新增用户数(与 dates 对齐)。 */
private List<Long> newUsers;
/** 每日播放事件数(watch_history 行数,与 dates 对齐)。 */
private List<Long> playEvents;
/** 每日新增转码任务数(transcode_task 行数,与 dates 对齐)。 */
private List<Long> newTranscodes;
/** 每日转码成功数(与 dates 对齐)。 */
private List<Long> transcodeSuccess;
}
@@ -0,0 +1,27 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
/** 收藏与点赞列表的公共检索条件。 */
@Data
public class EngagementQueryReqVO {
private static final int DEFAULT_PAGE_SIZE = 10;
private static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private Integer pageIndex = 1;
private Integer pageSize = DEFAULT_PAGE_SIZE;
private String keyword;
private Long userId;
private String deviceId;
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
private String platform;
private String dramaTitle;
private Long dramaId;
@DateTimeFormat(pattern = TIME_PATTERN)
private LocalDateTime startTime;
@DateTimeFormat(pattern = TIME_PATTERN)
private LocalDateTime endTime;
}
@@ -0,0 +1,28 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 后台剧集编辑页一次性获取的转码状态。 */
@Data
@Schema(description = "分集转码聚合信息")
public class EpisodeTranscodeRespVO {
private String episodeId;
private String mediaAssetId;
private String taskId;
private String status;
private Integer progress;
private Integer retryCount;
private String errorMsg;
private LocalDateTime updatedAt;
private List<MediaRenditionRespVO> renditions = List.of();
private MediaThumbnailRespVO thumbnails;
}
@@ -0,0 +1,12 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.Data;
import lombok.EqualsAndHashCode;
/** 后台收藏分页检索条件。 */
@Data
@EqualsAndHashCode(callSuper = true)
public class FavoriteQueryReqVO extends EngagementQueryReqVO {
}
@@ -0,0 +1,17 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import lombok.EqualsAndHashCode;
/** 后台点赞分页检索条件。 */
@Data
@EqualsAndHashCode(callSuper = true)
public class LikeQueryReqVO extends EngagementQueryReqVO {
@Pattern(regexp = "DRAMA|EPISODE|COMMENT", message = "目标类型必须为 DRAMA、EPISODE 或 COMMENT")
private String targetType;
private Long targetId;
private Long episodeId;
}
@@ -0,0 +1,32 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/** 一轮转码补齐巡检的结果。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TranscodeBackfillRespVO {
/** 本轮实际补入队的分集数。 */
private int triggered;
/** 补入队的分集与任务明细。 */
private List<Item> items;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Item {
private String episodeId;
private String taskId;
}
}
@@ -0,0 +1,22 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 后台转码看板强类型响应。 */
@Data
@Schema(description = "转码看板")
public class TranscodeDashboardRespVO {
private LocalDateTime generatedAt;
private TranscodeQueueStatsVO queue;
private List<TranscodeTaskRespVO> failedTasks = List.of();
private List<String> notes = List.of();
}
@@ -0,0 +1,35 @@
// Author: fruit.com.cn
// 转码通知响应:角标数量和最近任务。
package com.fruitshorts.admin.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/** 转码通知:角标数量和最近任务。 */
@Data
public class TranscodeNoticeRespVO {
private long running;
private long success;
private long failed;
private List<Item> runningList = new ArrayList<>();
private List<Item> successList = new ArrayList<>();
private List<Item> failedList = new ArrayList<>();
/** 一条转码通知,带短剧和集数。 */
@Data
public static class Item {
private Long id;
private String status;
private String dramaTitle;
private Integer episodeNo;
private String episodeTitle;
private Integer progress;
private String errorMsg;
private LocalDateTime updatedAt;
}
}
@@ -20,6 +20,8 @@ public class WatchHistoryQueryReqVO {
private String dramaTitle; private String dramaTitle;
private Long dramaId; private Long dramaId;
private Long episodeId; private Long episodeId;
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
private String platform;
private String source; private String source;
private Boolean finished; private Boolean finished;
@@ -14,6 +14,12 @@ spring:
url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts} url: ${DB_URL:jdbc:postgresql://127.0.0.1:5432/fruitshorts}
username: ${DB_USER:fruitshorts} username: ${DB_USER:fruitshorts}
password: ${DB_PASSWORD:fruitshorts} password: ${DB_PASSWORD:fruitshorts}
data:
redis:
# 与 app-api 共用同一个 Redis 实例;容器内必须显式指定 host,
# 否则 Spring Boot 默认连 127.0.0.1(容器内即自身)导致健康检查报 DOWN。
host: ${REDIS_HOST:127.0.0.1}
port: ${REDIS_PORT:6379}
jackson: jackson:
date-format: yyyy-MM-dd HH:mm:ss date-format: yyyy-MM-dd HH:mm:ss
time-zone: Asia/Shanghai time-zone: Asia/Shanghai
@@ -40,20 +46,25 @@ mybatis-plus:
datacenter-id: 1 datacenter-id: 1
fruitshorts: fruitshorts:
web:
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
media: media:
# 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads # 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads
root-dir: ${MEDIA_ROOT_DIR:./data/uploads} root-dir: ${MEDIA_ROOT_DIR:./data/uploads}
public-prefix: /files public-prefix: /files
chunk-size: 5242880 chunk-size: 5242880
max-file-size: 2147483648 max-file-size: 2147483648
signature-secret: ${MEDIA_SIGNATURE_SECRET:fruitshorts-media-dev-secret-change-me-in-production-32b} signature-secret: ${MEDIA_SIGNATURE_SECRET:}
signature-required: ${MEDIA_SIGNATURE_REQUIRED:false} signature-required: ${MEDIA_SIGNATURE_REQUIRED:false}
signature-ttl-minutes: 15 signature-ttl-minutes: 15
jwt: jwt:
# 双密钥都要外置:只配 admin 而漏配 app,生产会静默用 dev 默认值(prod fail-fast 会拦住) # ⚠️ 所有环境必须注入 JWT_ADMIN_SECRET / JWT_APP_SECRET,不设任何代码级默认值
admin-secret: ${JWT_ADMIN_SECRET:fruitshorts-admin-dev-secret-change-me-in-production-32b} admin-secret: ${JWT_ADMIN_SECRET:}
admin-ttl-hours: 12 admin-ttl-hours: 12
app-secret: ${JWT_APP_SECRET:fruitshorts-app-dev-secret-change-me-in-production-32bytes} app-secret: ${JWT_APP_SECRET:}
app-access-ttl-minutes: 120 app-access-ttl-minutes: 120
app-refresh-ttl-days: 30 app-refresh-ttl-days: 30
cors: cors:
@@ -32,6 +32,11 @@ class AdminPermissionAnnotationTest {
assertThat(permissionsOf(NoticeAdminController.class)) assertThat(permissionsOf(NoticeAdminController.class))
.containsExactlyInAnyOrder("notice:list", "notice:list", .containsExactlyInAnyOrder("notice:list", "notice:list",
"notice:update", "notice:update", "notice:update", "notice:update"); "notice:update", "notice:update", "notice:update", "notice:update");
assertThat(permissionsOf(RewardAdminController.class))
.containsExactlyInAnyOrder("reward:list", "reward:list", "reward:update",
"reward:update", "reward:update", "reward:checkin", "reward:checkin",
"reward:grant", "reward:grant", "reward:list", "reward:list",
"reward:update", "reward:update", "reward:update");
} }
/** 收集控制器里所有映射方法的 @PreAuthorize 权限点(缺失则记为 MISSING,便于断言直接看到)。 */ /** 收集控制器里所有映射方法的 @PreAuthorize 权限点(缺失则记为 MISSING,便于断言直接看到)。 */
@@ -0,0 +1,52 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.DashboardService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class DashboardTranscodeContractTest {
private DashboardService dashboardService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
dashboardService = mock(DashboardService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new DashboardAdminController(dashboardService));
}
@Test
void should_return_typed_queue_and_failed_tasks() throws Exception {
TranscodeQueueStatsVO queue = new TranscodeQueueStatsVO(
10L, 2L, 1L, 5L, 1L, 1L, 20L);
TranscodeDashboardRespVO vo = new TranscodeDashboardRespVO();
vo.setQueue(queue);
vo.setFailedTasks(List.of());
vo.setNotes(List.of("queue total"));
given(dashboardService.transcode()).willReturn(vo);
mockMvc.perform(get("/admin/dashboard/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.queue.total").value(10))
.andExpect(jsonPath("$.data.queue.queued").value(2))
.andExpect(jsonPath("$.data.queue.running").value(1))
.andExpect(jsonPath("$.data.queue.success").value(5))
.andExpect(jsonPath("$.data.queue.failed").value(1))
.andExpect(jsonPath("$.data.failedTasks").isArray());
}
}
@@ -0,0 +1,45 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.FavoriteAdminService;
import com.fruitshorts.admin.service.LikeAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.AdminFavoriteVO;
import com.fruitshorts.common.pojo.PageResult;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** 收藏和点赞分页路由及响应契约。 */
class EngagementControllerContractTest {
@Test
void should_return_guest_fields_for_favorites() throws Exception {
FavoriteAdminService service = mock(FavoriteAdminService.class);
AdminFavoriteVO guest = new AdminFavoriteVO();
guest.setId(1L);
guest.setDeviceId("guest");
guest.setAnonymous(true);
when(service.page(any())).thenReturn(new PageResult<>(1L, List.of(guest)));
ControllerContractSupport.mockMvcOf(new FavoriteAdminController(service))
.perform(get("/admin/favorites/page"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(1))
.andExpect(jsonPath("$.data.list[0].deviceId").value("guest"))
.andExpect(jsonPath("$.data.list[0].anonymous").value(true));
}
@Test
void should_return_empty_like_page() throws Exception {
LikeAdminService service = mock(LikeAdminService.class);
when(service.page(any())).thenReturn(PageResult.empty());
ControllerContractSupport.mockMvcOf(new LikeAdminController(service))
.perform(get("/admin/likes/page").param("targetType", "COMMENT"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(0))
.andExpect(jsonPath("$.data.list").isEmpty());
}
}
@@ -3,6 +3,7 @@
package com.fruitshorts.admin.controller; package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.support.ControllerContractSupport; import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
@@ -10,20 +11,30 @@ import com.fruitshorts.content.vo.EpisodeRespVO;
import com.fruitshorts.interaction.service.CommentService; import com.fruitshorts.interaction.service.CommentService;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** K89:后台剧集列表按集回填点赞/评论,并带所属剧收藏/热度。 */ /** 后台剧集列表:互动数量回填 + 分页契约。 */
class EpisodeControllerContractTest { class EpisodeControllerContractTest {
private static final long DRAMA_ID = 5L;
private static final int DEFAULT_PAGE_SIZE = 100;
private EpisodeService episodeService; private EpisodeService episodeService;
private CommentService commentService; private CommentService commentService;
private DramaService dramaService; private DramaService dramaService;
@@ -36,34 +47,108 @@ class EpisodeControllerContractTest {
dramaService = mock(DramaService.class); dramaService = mock(DramaService.class);
mockMvc = ControllerContractSupport.mockMvcOf( mockMvc = ControllerContractSupport.mockMvcOf(
new EpisodeController(episodeService, commentService, dramaService)); new EpisodeController(episodeService, commentService, dramaService));
Drama drama = new Drama();
drama.setFavoriteCount(88L);
drama.setViewCount(1000L);
given(dramaService.getExisting(DRAMA_ID)).willReturn(drama);
} }
@Test @Test
void should_return_episode_and_drama_interaction_counts() throws Exception { void should_return_episode_and_drama_interaction_counts() throws Exception {
given(episodeService.listByDrama(5L, null)).willReturn(List.of( given(episodeService.pageByDrama(eq(DRAMA_ID), isNull(), isNull(), isNull()))
episode(11L, 10L), .willReturn(new PageResult<>(2L, List.of(episode(11L, 10L), episode(12L, 20L))));
episode(12L, 20L)));
given(commentService.countByEpisodes(List.of(11L, 12L))) given(commentService.countByEpisodes(List.of(11L, 12L)))
.willReturn(Map.of(11L, 3L)); .willReturn(Map.of(11L, 3L));
Drama drama = new Drama();
drama.setFavoriteCount(88L);
drama.setViewCount(1000L);
given(dramaService.getExisting(5L)).willReturn(drama);
mockMvc.perform(get("/admin/episodes").param("dramaId", "5")) mockMvc.perform(get("/admin/episodes").param("dramaId", String.valueOf(DRAMA_ID)))
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.data[0].likeCount").value("10")) .andExpect(jsonPath("$.data.total").value(2))
.andExpect(jsonPath("$.data[0].commentCount").value("3")) .andExpect(jsonPath("$.data.list[0].likeCount").value("10"))
.andExpect(jsonPath("$.data[0].favoriteCount").value("88")) .andExpect(jsonPath("$.data.list[0].commentCount").value("3"))
.andExpect(jsonPath("$.data[0].heat").value("1000")) .andExpect(jsonPath("$.data.list[0].favoriteCount").value("88"))
.andExpect(jsonPath("$.data[1].likeCount").value("20")) .andExpect(jsonPath("$.data.list[0].heat").value("1000"))
.andExpect(jsonPath("$.data[1].commentCount").value("0")); .andExpect(jsonPath("$.data.list[1].likeCount").value("20"))
.andExpect(jsonPath("$.data.list[1].commentCount").value("0"));
}
@Test
void should_use_default_page_size_100_when_page_size_omitted() throws Exception {
given(episodeService.pageByDrama(eq(DRAMA_ID), isNull(), isNull(), isNull()))
.willReturn(PageResult.empty());
given(commentService.countByEpisodes(List.of())).willReturn(Map.of());
mockMvc.perform(get("/admin/episodes").param("dramaId", String.valueOf(DRAMA_ID)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(0))
.andExpect(jsonPath("$.data.list").isArray())
.andExpect(jsonPath("$.data.list").isEmpty());
ArgumentCaptor<Integer> pageIndexCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> pageSizeCaptor = ArgumentCaptor.forClass(Integer.class);
verify(episodeService).pageByDrama(
eq(DRAMA_ID), isNull(), pageIndexCaptor.capture(), pageSizeCaptor.capture());
assertThat(pageIndexCaptor.getValue()).isNull();
assertThat(pageSizeCaptor.getValue()).isNull();
assertThat(DEFAULT_PAGE_SIZE).isEqualTo(100);
}
@Test
void should_return_non_overlapping_ids_when_second_page_requested() throws Exception {
List<EpisodeRespVO> page1 = List.of(episode(1L, 1L), episode(2L, 2L));
List<EpisodeRespVO> page2 = List.of(episode(3L, 3L), episode(4L, 4L));
given(episodeService.pageByDrama(DRAMA_ID, null, 1, 2))
.willReturn(new PageResult<>(4L, page1));
given(episodeService.pageByDrama(DRAMA_ID, null, 2, 2))
.willReturn(new PageResult<>(4L, page2));
given(commentService.countByEpisodes(List.of(1L, 2L))).willReturn(Map.of());
given(commentService.countByEpisodes(List.of(3L, 4L))).willReturn(Map.of());
mockMvc.perform(get("/admin/episodes")
.param("dramaId", String.valueOf(DRAMA_ID))
.param("pageIndex", "1")
.param("pageSize", "2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(4))
.andExpect(jsonPath("$.data.list.length()").value(2));
String page2Body = mockMvc.perform(get("/admin/episodes")
.param("dramaId", String.valueOf(DRAMA_ID))
.param("pageIndex", "2")
.param("pageSize", "2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(4))
.andExpect(jsonPath("$.data.list[0].id").value("3"))
.andExpect(jsonPath("$.data.list[1].id").value("4"))
.andReturn()
.getResponse()
.getContentAsString();
Set<Long> page1Ids = page1.stream().map(EpisodeRespVO::getId).collect(Collectors.toSet());
Set<Long> page2Ids = page2.stream().map(EpisodeRespVO::getId).collect(Collectors.toSet());
assertThat(page1Ids).doesNotContainAnyElementsOf(page2Ids);
assertThat(page2Body).contains("\"id\":\"3\"");
}
@Test
void should_return_empty_list_with_correct_total_when_page_out_of_range() throws Exception {
given(episodeService.pageByDrama(DRAMA_ID, null, 99, 100))
.willReturn(new PageResult<>(5L, List.of()));
given(commentService.countByEpisodes(List.of())).willReturn(Map.of());
mockMvc.perform(get("/admin/episodes")
.param("dramaId", String.valueOf(DRAMA_ID))
.param("pageIndex", "99")
.param("pageSize", "100"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value(5))
.andExpect(jsonPath("$.data.list").isArray())
.andExpect(jsonPath("$.data.list").isEmpty());
} }
private EpisodeRespVO episode(Long id, Long likeCount) { private EpisodeRespVO episode(Long id, Long likeCount) {
EpisodeRespVO episode = new EpisodeRespVO(); EpisodeRespVO episode = new EpisodeRespVO();
episode.setId(id); episode.setId(id);
episode.setDramaId(5L); episode.setDramaId(DRAMA_ID);
episode.setLikeCount(likeCount); episode.setLikeCount(likeCount);
return episode; return episode;
} }
@@ -0,0 +1,69 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.EpisodeTranscodeAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class EpisodeTranscodeContractTest {
private EpisodeTranscodeAdminService service;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
service = mock(EpisodeTranscodeAdminService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new EpisodeTranscodeController(service));
}
@Test
void should_return_aggregated_episode_transcode_state() throws Exception {
String episodeId = "2113150431755636737";
String mediaAssetId = "2113150398670966786";
String taskId = "2113150398935207938";
EpisodeTranscodeRespVO vo = new EpisodeTranscodeRespVO();
vo.setEpisodeId(episodeId);
vo.setMediaAssetId(mediaAssetId);
vo.setTaskId(taskId);
vo.setStatus("SUCCESS");
vo.setProgress(100);
vo.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 15, 10));
given(service.detail(Long.parseLong(episodeId))).willReturn(vo);
mockMvc.perform(get("/admin/episodes/" + episodeId + "/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.episodeId").value(episodeId))
.andExpect(jsonPath("$.data.mediaAssetId").value(mediaAssetId))
.andExpect(jsonPath("$.data.taskId").value(taskId))
.andExpect(jsonPath("$.data.status").value("SUCCESS"))
.andExpect(jsonPath("$.data.progress").value(100))
.andExpect(jsonPath("$.data.updatedAt").value("2026-10-22T15:10:00"));
}
@Test
void should_return_explicit_empty_state_when_episode_has_no_video() throws Exception {
EpisodeTranscodeRespVO vo = new EpisodeTranscodeRespVO();
vo.setEpisodeId("31");
vo.setStatus("NO_VIDEO");
given(service.detail(31L)).willReturn(vo);
mockMvc.perform(get("/admin/episodes/31/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("NO_VIDEO"))
.andExpect(jsonPath("$.data.renditions").isEmpty());
}
}
@@ -0,0 +1,90 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class MediaTranscodeOutputContractTest {
private MediaTranscodeOutputService outputService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
outputService = mock(MediaTranscodeOutputService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new MediaTranscodeOutputController(outputService));
}
@Test
void should_return_typed_rendition_list() throws Exception {
MediaRenditionRespVO vo = new MediaRenditionRespVO();
vo.setQuality("1080p");
vo.setQualityName("1080P");
vo.setResolution("1920x1080");
vo.setVideoBitrateKbps(5000);
vo.setVideoCodec("H.264");
vo.setAudioCodec("AAC");
vo.setContainer("HLS");
vo.setHlsUrl("/files/master.m3u8");
vo.setSizeBytes(4096L);
vo.setStatus("ready");
given(outputService.renditions(88L)).willReturn(List.of(vo));
mockMvc.perform(get("/admin/media/88/renditions"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data[0].quality").value("1080p"))
.andExpect(jsonPath("$.data[0].resolution").value("1920x1080"))
.andExpect(jsonPath("$.data[0].videoBitrateKbps").value(5000))
.andExpect(jsonPath("$.data[0].hlsUrl").value("/files/master.m3u8"));
}
@Test
void should_return_not_found_for_missing_media() throws Exception {
given(outputService.renditions(404L))
.willThrow(new ServiceException(ErrorCode.DATA_NOT_FOUND, "媒资不存在"));
mockMvc.perform(get("/admin/media/404/renditions"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode()))
.andExpect(jsonPath("$.message").value("媒资不存在"));
}
@Test
void should_return_empty_thumbnail_status_without_error() throws Exception {
MediaThumbnailRespVO vo = new MediaThumbnailRespVO();
vo.setStatus("EMPTY");
vo.setPageIndex(1);
vo.setPageSize(100);
vo.setFrames(PageResult.empty());
given(outputService.thumbnails(88L, 1, 100)).willReturn(vo);
mockMvc.perform(get("/admin/media/88/thumbnails"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.status").value("EMPTY"))
.andExpect(jsonPath("$.data.frames.total").value(0))
.andExpect(jsonPath("$.data.frames.list").isEmpty());
verify(outputService).thumbnails(88L, 1, 100);
}
}
@@ -0,0 +1,100 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.media.config.MediaTranscodeProfile;
import com.fruitshorts.media.config.TranscodeProperties;
import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.system.service.ConfigService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 后台转码配置接口:默认值、非法拒绝与成功落库。
*/
class MediaTranscodeProfileContractTest {
private ConfigService configService;
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
configService = mock(ConfigService.class);
objectMapper = new ObjectMapper();
MediaTranscodeProfileService profileService = new MediaTranscodeProfileService(
configService, objectMapper, new TranscodeProperties());
MediaController controller = new MediaController(
mock(MediaService.class), profileService,
mock(com.fruitshorts.admin.service.TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller);
given(configService.get(eq(MediaTranscodeProfileService.CONFIG_KEY), anyString()))
.willReturn("");
}
@Test
void should_return_default_profile_when_config_is_missing() throws Exception {
mockMvc.perform(get("/admin/media/transcode-profile"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.segmentSeconds").value(6))
.andExpect(jsonPath("$.data.ladder.length()").value(4))
.andExpect(jsonPath("$.data.ladder[0].quality").value("360p"))
.andExpect(jsonPath("$.data.sprite.columns").value(10));
}
@Test
void should_reject_illegal_profile_without_writing_config() throws Exception {
MediaTranscodeProfile profile = new MediaTranscodeProfile();
profile.getLadder().get(0).setWidth(641);
mockMvc.perform(put("/admin/media/transcode-profile")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(profile)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("宽高必须为正偶数"));
verify(configService, never()).update(any());
}
@Test
void should_persist_profile_when_request_is_valid() throws Exception {
MediaTranscodeProfile profile = new MediaTranscodeProfile();
profile.setSegmentSeconds(4);
mockMvc.perform(put("/admin/media/transcode-profile")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(profile)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.segmentSeconds").value(4));
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
verify(configService).update(captor.capture());
assertThat(captor.getValue().get(MediaTranscodeProfileService.CONFIG_KEY))
.contains("\"segmentSeconds\":4");
}
}
@@ -0,0 +1,65 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeBackfillAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.media.vo.TranscodeTriggerRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 后台手动触发转码的最小契约。
*/
class MediaTranscodeTriggerContractTest {
private MediaService mediaService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mediaService = mock(MediaService.class);
MediaController controller = new MediaController(
mediaService, mock(MediaTranscodeProfileService.class),
mock(TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller);
}
@Test
void should_return_task_id_and_status_when_triggering_transcode() throws Exception {
given(mediaService.triggerTranscode(88L))
.willReturn(new TranscodeTriggerRespVO(100L, TranscodeService.STATUS_QUEUED));
mockMvc.perform(post("/admin/media/88/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.taskId").value("100"))
.andExpect(jsonPath("$.data.status").value(TranscodeService.STATUS_QUEUED));
verify(mediaService).triggerTranscode(88L);
}
@Test
void should_keep_not_found_semantics_when_media_does_not_exist() throws Exception {
given(mediaService.triggerTranscode(404L))
.willThrow(new ServiceException(ErrorCode.DATA_NOT_FOUND, "媒资不存在"));
mockMvc.perform(post("/admin/media/404/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode()))
.andExpect(jsonPath("$.message").value("媒资不存在"));
}
}
@@ -0,0 +1,53 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeNoticeService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class TranscodeNoticeContractTest {
private TranscodeNoticeService transcodeNoticeService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
transcodeNoticeService = mock(TranscodeNoticeService.class);
mockMvc = ControllerContractSupport.mockMvcOf(new TranscodeNoticeController(transcodeNoticeService));
}
@Test
void should_return_drama_and_episode_when_transcode_notice_is_requested() throws Exception {
TranscodeNoticeRespVO data = new TranscodeNoticeRespVO();
data.setRunning(1L);
data.setSuccess(2L);
data.setFailed(3L);
TranscodeNoticeRespVO.Item item = new TranscodeNoticeRespVO.Item();
item.setDramaTitle("重生");
item.setEpisodeNo(4);
item.setEpisodeTitle("第4集");
data.setFailedList(List.of(item));
given(transcodeNoticeService.notices()).willReturn(data);
mockMvc.perform(get("/admin/notifications/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.running").value(1))
.andExpect(jsonPath("$.data.success").value(2))
.andExpect(jsonPath("$.data.failed").value(3))
.andExpect(jsonPath("$.data.failedList[0].dramaTitle").value("重生"))
.andExpect(jsonPath("$.data.failedList[0].episodeNo").value(4))
.andExpect(jsonPath("$.data.failedList[0].episodeTitle").value("第4集"));
}
}
@@ -0,0 +1,48 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.user.dal.entity.AppUserSession;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/** 观看记录匹配登录系统。 */
class AppSessionSystemServiceTest {
private final AppSessionSystemService service = new AppSessionSystemService(null, null);
@Test
void should_use_same_device_session_when_watch_history_has_device() {
AppUserSession older = session("device-1", "ANDROID", "14", null);
AppUserSession newer = session("device-2", "IOS", "18", null);
AppUserSession matched = service.match(List.of(newer, older), "device-1");
assertThat(matched.getPlatform()).isEqualTo("ANDROID");
assertThat(matched.getOsVersion()).isEqualTo("14");
}
@Test
void should_use_active_session_when_device_does_not_match() {
AppUserSession revoked = session("device-9", "WEB", "1", LocalDateTime.now());
AppUserSession active = session("device-2", "IOS", "18", null);
AppUserSession matched = service.match(List.of(revoked, active), "missing");
assertThat(matched.getPlatform()).isEqualTo("IOS");
}
private AppUserSession session(String deviceId, String platform, String osVersion,
LocalDateTime revokedAt) {
AppUserSession session = new AppUserSession();
session.setDeviceId(deviceId);
session.setPlatform(platform);
session.setOsVersion(osVersion);
session.setRevokedAt(revokedAt);
return session;
}
}
@@ -0,0 +1,105 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
import com.fruitshorts.admin.vo.LikeQueryReqVO;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.interaction.dal.entity.ContentLike;
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
import com.fruitshorts.playback.dal.entity.UserFavorite;
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
/** 收藏及点赞分页的游客、空结果和多态目标检验。 */
class EngagementAdminServiceTest {
@BeforeAll
static void initMetadata() {
MybatisConfiguration config = new MybatisConfiguration();
MapperBuilderAssistant assistant = new MapperBuilderAssistant(config, "");
TableInfoHelper.initTableInfo(assistant, UserFavorite.class);
TableInfoHelper.initTableInfo(assistant, ContentLike.class);
}
@Test
void should_enable_logic_delete_for_both_interaction_entities() {
assertThat(TableInfoHelper.getTableInfo(UserFavorite.class).isWithLogicDelete()).isTrue();
assertThat(TableInfoHelper.getTableInfo(ContentLike.class).isWithLogicDelete()).isTrue();
assertThat(TableInfoHelper.getTableInfo(UserFavorite.class).getLogicDeleteSql(true, true))
.contains("deleted").contains("0");
assertThat(TableInfoHelper.getTableInfo(ContentLike.class).getLogicDeleteSql(true, true))
.contains("deleted").contains("0");
}
@Test
void should_return_empty_without_query_when_keyword_has_no_match() {
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
UserFavoriteMapper mapper = mock(UserFavoriteMapper.class);
when(lookup.userIds("missing")).thenReturn(List.of());
when(lookup.noMatch(List.of())).thenReturn(true);
FavoriteQueryReqVO req = new FavoriteQueryReqVO();
req.setKeyword("missing");
var result = new FavoriteAdminService(mapper, lookup).page(req);
assertThat(result.getTotal()).isZero();
assertThat(result.getList()).isEmpty();
verifyNoInteractions(mapper);
}
@Test
void should_keep_drama_published_unknown_when_drama_missing() {
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
UserFavoriteMapper mapper = mock(UserFavoriteMapper.class);
when(lookup.page(any())).thenReturn(new Page<>(1, 10));
UserFavorite row = new UserFavorite();
row.setId(1L);
row.setDeviceId("guest-device");
row.setDramaId(2L);
Page<UserFavorite> page = new Page<>(1, 10);
page.setTotal(1);
page.setRecords(List.of(row));
when(mapper.selectPage(any(Page.class), any(Wrapper.class))).thenReturn(page);
when(lookup.users(any())).thenReturn(Map.of());
when(lookup.dramas(any())).thenReturn(Map.of());
var result = new FavoriteAdminService(mapper, lookup).page(new FavoriteQueryReqVO());
assertThat(result.getList().get(0).getAnonymous()).isTrue();
assertThat(result.getList().get(0).getDeviceId()).isEqualTo("guest-device");
// 短剧已不存在时不能误报成「未发布」
assertThat(result.getList().get(0).getDramaPublished()).isNull();
}
@Test
void should_preserve_guest_drama_like_without_episode() {
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
ContentLikeMapper mapper = mock(ContentLikeMapper.class);
when(lookup.page(any())).thenReturn(new Page<>(1, 10));
ContentLike row = new ContentLike();
row.setId(1L);
row.setTargetType("DRAMA");
row.setTargetId(2L);
row.setDeviceId("guest-device");
Page<ContentLike> page = new Page<>(1, 10);
page.setTotal(1);
page.setRecords(List.of(row));
when(mapper.selectPage(any(Page.class), any(Wrapper.class))).thenReturn(page);
when(lookup.users(any())).thenReturn(Map.of());
when(lookup.dramas(any())).thenReturn(Map.of());
var service = new LikeAdminService(mapper, mock(ContentCommentMapper.class),
mock(DramaEpisodeMapper.class), lookup);
var result = service.page(new LikeQueryReqVO());
assertThat(result.getList().get(0).getAnonymous()).isTrue();
assertThat(result.getList().get(0).getDramaId()).isEqualTo(2L);
assertThat(result.getList().get(0).getEpisodeId()).isNull();
}
}
@@ -0,0 +1,116 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class EpisodeTranscodeAdminServiceTest {
private static final Long EPISODE_ID = 2113150431755636737L;
private static final Long MEDIA_ASSET_ID = 2113150398670966786L;
private static final Long TASK_ID = 2113150398935207938L;
private DramaEpisodeMapper episodeMapper;
private MediaTranscodeOutputService outputService;
private EpisodeTranscodeAdminService service;
@BeforeEach
void setUp() {
episodeMapper = mock(DramaEpisodeMapper.class);
outputService = mock(MediaTranscodeOutputService.class);
service = new EpisodeTranscodeAdminService(episodeMapper, outputService);
}
@Test
void should_return_episode_not_found_state_without_aggregating_media() {
given(episodeMapper.selectById(404L)).willReturn(null);
var result = service.detail(404L);
assertThat(result.getStatus()).isEqualTo("EPISODE_NOT_FOUND");
assertThat(result.getEpisodeId()).isEqualTo("404");
assertThat(result.getRenditions()).isEmpty();
verifyNoInteractions(outputService);
}
@Test
void should_return_no_video_state_when_episode_video_url_is_blank() {
DramaEpisode episode = new DramaEpisode();
episode.setId(31L);
episode.setVideoUrl("");
given(episodeMapper.selectById(31L)).willReturn(episode);
var result = service.detail(31L);
assertThat(result.getStatus()).isEqualTo("NO_VIDEO");
assertThat(result.getRenditions()).isEmpty();
verifyNoInteractions(outputService);
}
@Test
void should_return_exact_snowflake_media_asset_id_as_string() {
DramaEpisode episode = episode(MEDIA_ASSET_ID);
given(episodeMapper.selectById(EPISODE_ID)).willReturn(episode);
given(outputService.resolveMediaAssetId(episode.getVideoUrl())).willReturn(null);
given(outputService.mediaAssetExists(MEDIA_ASSET_ID)).willReturn(true);
given(outputService.renditionsForMediaAssetId(MEDIA_ASSET_ID)).willReturn(List.of());
given(outputService.thumbnailForEpisode(
EPISODE_ID, MEDIA_ASSET_ID, 1, 100))
.willReturn(MediaThumbnailRespVO.empty(
MEDIA_ASSET_ID, EPISODE_ID,
MediaThumbnailRespVO.STATUS_EMPTY, 1, 100));
TranscodeTaskRespVO task = new TranscodeTaskRespVO();
task.setId(TASK_ID);
task.setMediaAssetId(MEDIA_ASSET_ID);
task.setStatus("SUCCESS");
task.setProgress(100);
task.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 15, 10));
given(outputService.latestTask(MEDIA_ASSET_ID)).willReturn(task);
var result = service.detail(EPISODE_ID);
assertThat(result.getEpisodeId()).isEqualTo("2113150431755636737");
assertThat(result.getMediaAssetId()).isEqualTo("2113150398670966786");
assertThat(result.getTaskId()).isEqualTo("2113150398935207938");
assertThat(result.getUpdatedAt()).isEqualTo(task.getUpdatedAt());
}
@Test
void should_return_explicit_empty_state_when_episode_media_is_missing() {
DramaEpisode episode = episode(MEDIA_ASSET_ID);
given(episodeMapper.selectById(EPISODE_ID)).willReturn(episode);
given(outputService.mediaAssetExists(MEDIA_ASSET_ID)).willReturn(false);
given(outputService.resolveMediaAssetId(episode.getVideoUrl())).willReturn(null);
var result = service.detail(EPISODE_ID);
assertThat(result.getMediaAssetId()).isNull();
assertThat(result.getStatus()).isEqualTo("NO_MEDIA_ASSET");
assertThat(result.getErrorMsg()).isNotBlank();
assertThat(result.getRenditions()).isEmpty();
}
private DramaEpisode episode(Long videoAssetId) {
DramaEpisode episode = new DramaEpisode();
episode.setId(EPISODE_ID);
episode.setDramaId(7L);
episode.setDurationSec(120);
episode.setVideoAssetId(videoAssetId);
episode.setVideoUrl("/files/episode/202610/video.mp4");
return episode;
}
}
@@ -0,0 +1,67 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TranscodeNoticeServiceTest {
@Test
void should_attach_drama_and_episode_when_failed_tasks_are_loaded() throws Exception {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
doAnswer(invocation -> {
assertTrue(invocation.getArgument(0, String.class).contains("?"));
return null;
}).when(jdbc).query(anyString(), any(RowCallbackHandler.class), eq("RUNNING"), eq("SUCCESS"), eq("FAILED"));
when(jdbc.query(anyString(), any(RowMapper.class), any(), anyString(), any()))
.thenAnswer(invocation -> {
String sql = invocation.getArgument(0, String.class);
String status = invocation.getArgument(3, String.class);
if (!"FAILED".equals(status)) {
return java.util.List.of();
}
assertTrue(sql.contains("drama_title"));
assertTrue(sql.contains("?"));
RowMapper<?> mapper = invocation.getArgument(1);
ResultSet rs = failedRow();
return java.util.List.of(mapper.mapRow(rs, 0));
});
TranscodeNoticeRespVO data = new TranscodeNoticeService(jdbc).notices();
assertEquals(1, data.getFailedList().size());
assertEquals("重生", data.getFailedList().get(0).getDramaTitle());
assertEquals(4, data.getFailedList().get(0).getEpisodeNo());
assertEquals("第4集", data.getFailedList().get(0).getEpisodeTitle());
}
private ResultSet failedRow() throws Exception {
ResultSet rs = mock(ResultSet.class);
when(rs.getLong("id")).thenReturn(9L);
when(rs.getString("status")).thenReturn("FAILED");
when(rs.getInt("progress")).thenReturn(0);
when(rs.getString("error_msg")).thenReturn("boom");
when(rs.getTimestamp("updated_at")).thenReturn(Timestamp.valueOf(LocalDateTime.of(2026, 10, 24, 12, 0)));
when(rs.getString("drama_title")).thenReturn("重生");
when(rs.getObject("ep_no")).thenReturn(4);
when(rs.getString("title")).thenReturn("第4集");
return rs;
}
}
@@ -58,7 +58,7 @@ class WatchHistoryAdminServiceTest {
dramaMapper = mock(DramaMapper.class); dramaMapper = mock(DramaMapper.class);
dramaEpisodeMapper = mock(DramaEpisodeMapper.class); dramaEpisodeMapper = mock(DramaEpisodeMapper.class);
service = new WatchHistoryAdminService(watchHistoryMapper, appUserMapper, dramaMapper, service = new WatchHistoryAdminService(watchHistoryMapper, appUserMapper, dramaMapper,
dramaEpisodeMapper); dramaEpisodeMapper, mock(AppSessionSystemService.class));
} }
@Test @Test
@@ -199,9 +199,10 @@ class WatchHistoryAdminServiceTest {
} }
private void stubBatchData() { private void stubBatchData() {
given(appUserMapper.selectBatchIds(any())).willReturn(List.of(user(7L, "Alice"))); // 装配阶段按需列查询,而不是 selectBatchIds,桩法要跟着改
given(dramaMapper.selectBatchIds(any())).willReturn(List.of(drama(5L, "Signal"))); given(appUserMapper.selectList(any())).willReturn(List.of(user(7L, "Alice")));
given(dramaEpisodeMapper.selectBatchIds(any())).willReturn(List.of(episode(11L))); given(dramaMapper.selectList(any())).willReturn(List.of(drama(5L, "Signal")));
given(dramaEpisodeMapper.selectList(any())).willReturn(List.of(episode(11L)));
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -30,7 +30,9 @@ public final class ControllerContractSupport {
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */ /** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static MockMvc mockMvcOf(Object controller) { public static MockMvc mockMvcOf(Object controller) {
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class)); AccessDeniedRecorder recorder = new AccessDeniedRecorder(
Mockito.mock(ObjectProvider.class),
Mockito.mock(ObjectProvider.class));
return MockMvcBuilders.standaloneSetup(controller) return MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new GlobalExceptionHandler(recorder)) .setControllerAdvice(new GlobalExceptionHandler(recorder))
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组, // 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
@@ -24,6 +24,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;
/** 客户端账号:验证码、注册、登录、刷新、登出。 */ /** 客户端账号:验证码、注册、登录、刷新、登出。 */
@Tag(name = "客户端-账号") @Tag(name = "客户端-账号")
@@ -34,13 +35,14 @@ public class AppAuthController {
private final AppOtpService otpService; private final AppOtpService otpService;
private final AppAuthService authService; private final AppAuthService authService;
private final WebUtils webUtils;
/** 发送验证码。频控在服务端,客户端不需要自己限流。 */ /** 发送验证码。频控在服务端,客户端不需要自己限流。 */
@Operation(summary = "发送验证码(频控在服务端)") @Operation(summary = "发送验证码(频控在服务端)")
@RateLimit(limit = 20, windowSeconds = 60, key = "otp") @RateLimit(limit = 20, windowSeconds = 60, key = "otp")
@PostMapping("/otp") @PostMapping("/otp")
public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) { public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) {
otpService.send(req, WebUtils.getClientIp(request)); otpService.send(req, webUtils.clientIp(request));
return Result.ok(); return Result.ok();
} }
@@ -48,7 +50,8 @@ public class AppAuthController {
@PostMapping("/register") @PostMapping("/register")
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req, public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
HttpServletRequest request) { HttpServletRequest request) {
return Result.ok(authService.register(req, WebUtils.getClientIp(request))); applyHeaderDeviceId(req, request);
return Result.ok(authService.register(req, webUtils.clientIp(request)));
} }
@Operation(summary = "登录(验证码或密码)") @Operation(summary = "登录(验证码或密码)")
@@ -56,19 +59,25 @@ public class AppAuthController {
@PostMapping("/login") @PostMapping("/login")
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req, public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
HttpServletRequest request) { HttpServletRequest request) {
return Result.ok(authService.login(req, WebUtils.getClientIp(request))); applyHeaderDeviceId(req, request);
return Result.ok(authService.login(req, webUtils.clientIp(request)));
} }
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)") @Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
@PostMapping("/google") @PostMapping("/google")
public Result<TokenRespVO> google(@Valid @RequestBody GoogleLoginReqVO req) { public Result<TokenRespVO> google(@Valid @RequestBody GoogleLoginReqVO req,
return Result.ok(authService.googleLogin(req.getIdToken())); HttpServletRequest request) {
String headerDeviceId = request.getHeader("X-Device-Id");
String deviceId = StringUtils.hasText(headerDeviceId)
? headerDeviceId : req.getDeviceId();
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId,
webUtils.clientIp(request)));
} }
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)") @Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
@PostMapping("/refresh") @PostMapping("/refresh")
public Result<TokenRespVO> refresh(@Valid @RequestBody RefreshReqVO req) { public Result<TokenRespVO> refresh(@Valid @RequestBody RefreshReqVO req) {
return Result.ok(authService.refresh(req.getRefreshToken())); return Result.ok(authService.refresh(req.getRefreshToken(), req.getPlatform(), req.getOsVersion()));
} }
/** 登出:默认只吊销当前设备的会话,allDevices=true 时吊销全部。 */ /** 登出:默认只吊销当前设备的会话,allDevices=true 时吊销全部。 */
@@ -78,4 +87,16 @@ public class AppAuthController {
authService.logout(SecurityUtils.getUserIdOrNull(), req == null ? new LogoutReqVO() : req); authService.logout(SecurityUtils.getUserIdOrNull(), req == null ? new LogoutReqVO() : req);
return Result.ok(); return Result.ok();
} }
private void applyHeaderDeviceId(RegisterReqVO req, HttpServletRequest request) {
if (!StringUtils.hasText(req.getDeviceId())) {
req.setDeviceId(request.getHeader("X-Device-Id"));
}
}
private void applyHeaderDeviceId(LoginReqVO req, HttpServletRequest request) {
if (!StringUtils.hasText(req.getDeviceId())) {
req.setDeviceId(request.getHeader("X-Device-Id"));
}
}
} }
@@ -3,16 +3,24 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.service.AppRankingService;
import com.fruitshorts.app.vo.AppCategoryVO; import com.fruitshorts.app.vo.AppCategoryVO;
import com.fruitshorts.app.vo.AppDramaPageReqVO;
import com.fruitshorts.app.vo.AppFeedVO; import com.fruitshorts.app.vo.AppFeedVO;
import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.app.vo.AppPlaylistDetailVO;
import com.fruitshorts.app.vo.AppRankingVO;
import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.common.pojo.CursorResult;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -27,7 +35,11 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class AppCatalogController { public class AppCatalogController {
private static final int DRAMA_PAGE_INDEX = 1;
private static final int DRAMA_PAGE_SIZE = 20;
private final AppCatalogService appCatalogService; private final AppCatalogService appCatalogService;
private final AppRankingService appRankingService;
@Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页") @Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页")
@GetMapping("/home/feed") @GetMapping("/home/feed")
@@ -56,4 +68,62 @@ public class AppCatalogController {
public Result<List<AppCategoryVO>> categories() { public Result<List<AppCategoryVO>> categories() {
return Result.ok(appCatalogService.categories()); return Result.ok(appCatalogService.categories());
} }
@Operation(summary = "分类频道:按分类 ID 分页查短剧卡片")
@GetMapping("/categories/{id}/dramas")
public Result<PageResult<AppDramaCardVO>> categoryDramas(
@PathVariable Long id,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) {
return Result.ok(appCatalogService.categoryDramas(id, pageIndex, pageSize));
}
@Operation(summary = "推荐榜:按后台配置顺序返回榜单快照")
@GetMapping("/categories/{id}/ranking")
public Result<AppRankingVO> categoryRanking(@PathVariable Long id) {
return Result.ok(appRankingService.ranking(id));
}
@Operation(summary = "已启用类型")
@GetMapping("/drama-categories")
public Result<List<AppCategoryVO>> dramaCategories() {
return Result.ok(appCatalogService.dramaCategories());
}
@Operation(summary = "已启用标签")
@GetMapping("/tags")
public Result<List<AppCategoryVO>> tags() {
return Result.ok(appCatalogService.tags());
}
/**
* 全部短剧分页。类型、分类、标签放在请求体,避免长 id 进入查询串。
* 同一组多选为或,不同组同时传入为且。
*/
@Operation(summary = "全部短剧:类型、分类、标签多选,分页")
@PostMapping("/dramas/page")
public Result<PageResult<AppDramaCardVO>> dramas(@RequestBody(required = false) AppDramaPageReqVO req) {
AppDramaPageReqVO body = req == null ? new AppDramaPageReqVO() : req;
int pageIndex = body.getPageIndex() == null ? DRAMA_PAGE_INDEX : body.getPageIndex();
int pageSize = body.getPageSize() == null ? DRAMA_PAGE_SIZE : body.getPageSize();
return Result.ok(appCatalogService.libraryDramas(
body.getCategoryIds(), body.getClassificationIds(), body.getTagIds(), pageIndex, pageSize));
}
@Operation(summary = "剧单列表:已启用剧单及其已上线短剧卡片,分页")
@GetMapping("/playlists")
public Result<PageResult<AppPlaylistDetailVO>> playlists(
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(appCatalogService.playlists(pageIndex, pageSize));
}
@Operation(summary = "剧单详情:剧单基本信息 + 该页已上线短剧卡片")
@GetMapping("/playlists/{id}")
public Result<AppPlaylistDetailVO> playlistDetail(
@PathVariable Long id,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) {
return Result.ok(appCatalogService.playlistDetail(id, pageIndex, pageSize));
}
} }
@@ -6,6 +6,9 @@ import com.fruitshorts.common.pojo.CursorResult;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.framework.web.WebUtils; import com.fruitshorts.framework.web.WebUtils;
import com.fruitshorts.interaction.service.CommentService; import com.fruitshorts.interaction.service.CommentService;
@@ -33,7 +36,7 @@ import java.util.List;
* *
* <p>列表走游标翻页:`cursor` 传上一页最后一条的 id,返回 `nextCursor` 与 `hasMore`。 * <p>列表走游标翻页:`cursor` 传上一页最后一条的 id,返回 `nextCursor` 与 `hasMore`。
* 不传 `rootId` 时返回顶层评论,传了则返回该楼层的回复。 * 不传 `rootId` 时返回顶层评论,传了则返回该楼层的回复。
* 列表允许匿名浏览;发布与删除需要登录。 * 列表允许匿名浏览;发布与删除支持登录用户或设备身份。
*/ */
@Tag(name = "客户端-评论") @Tag(name = "客户端-评论")
@RestController @RestController
@@ -43,13 +46,21 @@ public class AppCommentController {
private final CommentService commentService; private final CommentService commentService;
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final InteractionIdentityResolver identityResolver;
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
private final WebUtils webUtils;
@Operation(summary = "发布评论") @Operation(summary = "发布评论")
@PostMapping @PostMapping
public Result<CommentRespVO> publish(@Valid @RequestBody CommentPublishReqVO req, public Result<CommentRespVO> publish(@Valid @RequestBody CommentPublishReqVO req,
HttpServletRequest request) { HttpServletRequest request) {
return Result.ok(commentService.publish(SecurityUtils.getAppUserId(), req, InteractionIdentity identity = identityResolver.resolve(
WebUtils.getClientIp(request), request.getHeader("X-Device-Id"))); SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
req.getDeviceId());
anonymousRateLimiter.check(identity, "comment");
return Result.ok(commentService.publish(
identity, req, webUtils.clientIp(request)));
} }
@Operation(summary = "评论列表(游标翻页,可匿名浏览)") @Operation(summary = "评论列表(游标翻页,可匿名浏览)")
@@ -58,14 +69,18 @@ public class AppCommentController {
@RequestParam(required = false) Long episodeId, @RequestParam(required = false) Long episodeId,
@RequestParam(required = false) Long rootId, @RequestParam(required = false) Long rootId,
@RequestParam(required = false) Long cursor, @RequestParam(required = false) Long cursor,
@RequestParam(required = false) Integer size) { @RequestParam(required = false) Integer size,
HttpServletRequest request) {
CommentQueryReqVO query = new CommentQueryReqVO(); CommentQueryReqVO query = new CommentQueryReqVO();
query.setDramaId(dramaId); query.setDramaId(dramaId);
query.setEpisodeId(episodeId); query.setEpisodeId(episodeId);
query.setRootId(rootId); query.setRootId(rootId);
query.setCursor(cursor); query.setCursor(cursor);
query.setSize(size); query.setSize(size);
return Result.ok(commentService.page(SecurityUtils.getUserIdOrNull(), query)); return Result.ok(commentService.page(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
query));
} }
@Operation(summary = "评论总数:传 episodeId 按集统计,仅 dramaId 时全剧统计(可匿名访问)") @Operation(summary = "评论总数:传 episodeId 按集统计,仅 dramaId 时全剧统计(可匿名访问)")
@@ -85,8 +100,13 @@ public class AppCommentController {
@Operation(summary = "删除自己的评论") @Operation(summary = "删除自己的评论")
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) { public Result<Void> delete(@PathVariable Long id, HttpServletRequest request) {
commentService.delete(SecurityUtils.getAppUserId(), id); InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
"");
anonymousRateLimiter.check(identity, "comment");
commentService.delete(identity, id);
return Result.ok(); return Result.ok();
} }
} }
@@ -7,12 +7,14 @@ import com.fruitshorts.commerce.service.OrderService;
import com.fruitshorts.commerce.service.ProductService; import com.fruitshorts.commerce.service.ProductService;
import com.fruitshorts.commerce.service.UnlockService; import com.fruitshorts.commerce.service.UnlockService;
import com.fruitshorts.commerce.service.WalletService; import com.fruitshorts.commerce.service.WalletService;
import com.fruitshorts.commerce.reward.service.RewardTaskService;
import com.fruitshorts.commerce.vo.ProductRespVO; import com.fruitshorts.commerce.vo.ProductRespVO;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -41,6 +43,8 @@ public class AppCommerceController {
private final UnlockService unlockService; private final UnlockService unlockService;
private final OrderService orderService; private final OrderService orderService;
private final ProductService productService; private final ProductService productService;
@Autowired(required = false)
private RewardTaskService rewardTaskService;
/** 我的钱包:余额 + 最近流水,客户端一处渲染。 */ /** 我的钱包:余额 + 最近流水,客户端一处渲染。 */
@Operation(summary = "我的钱包(余额 + 最近流水)") @Operation(summary = "我的钱包(余额 + 最近流水)")
@@ -92,9 +96,14 @@ public class AppCommerceController {
@Operation(summary = "提交商店票据(校验后建单并发权益,重复提交幂等)") @Operation(summary = "提交商店票据(校验后建单并发权益,重复提交幂等)")
@PostMapping("/orders/verify") @PostMapping("/orders/verify")
public Result<Orders> verify(@RequestBody Map<String, String> body) { public Result<Orders> verify(@RequestBody Map<String, String> body) {
return Result.ok(orderService.verifyAndDeliver(SecurityUtils.getAppUserId(), Orders order = orderService.verifyAndDeliver(SecurityUtils.getAppUserId(),
body.getOrDefault("platform", ""), body.getOrDefault("platform", ""),
body.getOrDefault("productId", ""), body.getOrDefault("productId", ""),
body.getOrDefault("receipt", ""))); body.getOrDefault("receipt", ""));
if (rewardTaskService != null && OrderService.STATUS_DELIVERED.equals(order.getStatus())) {
rewardTaskService.recordEvent(order.getUserId(), RewardTaskService.TYPE_FIRST_PURCHASE,
order.getOrderNo(), 1L);
}
return Result.ok(order);
} }
} }
@@ -3,7 +3,9 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.service.AppEpisodeStatsService;
import com.fruitshorts.app.vo.AppDramaDetailVO; import com.fruitshorts.app.vo.AppDramaDetailVO;
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
@@ -34,6 +36,8 @@ public class AppDramaController {
private final PlaybackService playbackService; private final PlaybackService playbackService;
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final CommentService commentService; private final CommentService commentService;
private final AppEpisodeStatsService appEpisodeStatsService;
private final WebUtils webUtils;
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */ /** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)") @Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
@@ -53,10 +57,21 @@ public class AppDramaController {
SecurityUtils.getUserIdOrNull(), SecurityUtils.getUserIdOrNull(),
id, id,
request.getHeader("X-Device-Id"), request.getHeader("X-Device-Id"),
WebUtils.getClientIp(request)); webUtils.clientIp(request));
DramaEpisode episode = episodeService.getExisting(id); DramaEpisode episode = episodeService.getExisting(id);
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount()); vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L)); vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L));
return Result.ok(vo); return Result.ok(vo);
} }
/** 轻量计数快照:只读互动状态,不签发播放地址、不写票据缓存。 */
@Operation(summary = "播放页轻量计数与当前用户互动状态")
@GetMapping("/episodes/{id}/stats")
public Result<AppEpisodeStatsVO> stats(
@PathVariable Long id, HttpServletRequest request) {
return Result.ok(appEpisodeStatsService.get(
id,
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id")));
}
} }
@@ -25,11 +25,12 @@ import org.springframework.web.bind.annotation.RestController;
public class AppEventController { public class AppEventController {
private final AppEventService eventService; private final AppEventService eventService;
private final WebUtils webUtils;
@Operation(summary = "埋点事件批量上报") @Operation(summary = "埋点事件批量上报")
@PostMapping("/events") @PostMapping("/events")
public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) { public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) {
eventService.save(req, SecurityUtils.getUserIdOrNull(), WebUtils.getClientIp(request)); eventService.save(req, SecurityUtils.getUserIdOrNull(), webUtils.clientIp(request));
return Result.ok(); return Result.ok();
} }
} }
@@ -4,13 +4,20 @@ package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.service.FavoriteService; import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.vo.FavoriteRemoveReqVO;
import com.fruitshorts.playback.vo.FavoriteToggleReqVO; import com.fruitshorts.playback.vo.FavoriteToggleReqVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@@ -18,10 +25,9 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 收藏。 */ /** 收藏。 */
@Tag(name = "客户端-收藏") @Tag(name = "客户端-收藏")
@RestController @RestController
@@ -31,26 +37,68 @@ public class AppFavoriteController {
private final FavoriteService favoriteService; private final FavoriteService favoriteService;
private final AppCatalogService appCatalogService; private final AppCatalogService appCatalogService;
private final InteractionIdentityResolver identityResolver;
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
/** 切换收藏,返回切换后的状态:true 为已收藏。 */ /** 切换收藏,返回切换后的状态:true 为已收藏。 */
@Operation(summary = "切换收藏(返回切换后的状态)") @Operation(summary = "切换收藏(返回切换后的状态)")
@PostMapping("/toggle") @PostMapping("/toggle")
public Result<Boolean> toggle(@Valid @RequestBody FavoriteToggleReqVO req) { public Result<Boolean> toggle(
return Result.ok(favoriteService.toggle(SecurityUtils.getAppUserId(), req.getDramaId())); @Valid @RequestBody FavoriteToggleReqVO req,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
req.getDeviceId());
anonymousRateLimiter.check(identity, "favorite");
return Result.ok(favoriteService.toggle(identity, req.getDramaId()));
} }
/** 收藏列表,卡片结构与首页一致。 */ /** 收藏列表,卡片结构与首页一致。 */
@Operation(summary = "我的收藏列表") @Operation(summary = "我的收藏列表")
@GetMapping @GetMapping
public Result<List<AppDramaCardVO>> list() { public Result<PageResult<AppDramaCardVO>> list(
return Result.ok(appCatalogService.toCards( @RequestParam(defaultValue = "1") int pageIndex,
favoriteService.listDramas(SecurityUtils.getAppUserId()))); @RequestParam(defaultValue = "20") int pageSize,
@RequestParam(required = false) String deviceId,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
deviceId);
PageResult<Drama> page = favoriteService.page(
identity, pageIndex, pageSize);
return Result.ok(new PageResult<>(
page.getTotal(), appCatalogService.toCards(page.getList())));
} }
@Operation(summary = "取消收藏") @Operation(summary = "取消收藏")
@DeleteMapping("/{dramaId}") @DeleteMapping("/{dramaId}")
public Result<Void> remove(@PathVariable Long dramaId) { public Result<Void> remove(@PathVariable Long dramaId, HttpServletRequest request) {
favoriteService.remove(SecurityUtils.getAppUserId(), dramaId); InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
"");
anonymousRateLimiter.check(identity, "favorite");
if (identity.authenticated()) {
favoriteService.remove(identity.userId(), dramaId);
} else {
favoriteService.removeDevice(identity.deviceId(), dramaId);
}
return Result.ok(); return Result.ok();
} }
/** 批量取消收藏,返回实际删除的关系数。 */
@Operation(summary = "批量取消收藏")
@PostMapping("/remove")
public Result<Integer> removeBatch(
@Valid @RequestBody FavoriteRemoveReqVO req,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
req.getDeviceId());
anonymousRateLimiter.check(identity, "favorite");
return Result.ok(favoriteService.removeBatch(identity, req.getDramaIds()));
}
} }
@@ -3,7 +3,10 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.interaction.service.LikeService; import com.fruitshorts.interaction.service.LikeService;
import com.fruitshorts.interaction.service.ReportService; import com.fruitshorts.interaction.service.ReportService;
import com.fruitshorts.interaction.vo.LikeToggleReqVO; import com.fruitshorts.interaction.vo.LikeToggleReqVO;
@@ -12,6 +15,7 @@ import com.fruitshorts.interaction.vo.ReportCreateReqVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -27,12 +31,21 @@ public class AppInteractionController {
private final LikeService likeService; private final LikeService likeService;
private final ReportService reportService; private final ReportService reportService;
private final InteractionIdentityResolver identityResolver;
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
/** 点赞/取消点赞,返回切换后的状态与最新计数。 */ /** 点赞/取消点赞,返回切换后的状态与最新计数。 */
@Operation(summary = "点赞 / 取消点赞") @Operation(summary = "点赞 / 取消点赞")
@PostMapping("/likes/toggle") @PostMapping("/likes/toggle")
public Result<LikeToggleRespVO> toggleLike(@Valid @RequestBody LikeToggleReqVO req) { public Result<LikeToggleRespVO> toggleLike(
return Result.ok(likeService.toggle(SecurityUtils.getAppUserId(), req)); @Valid @RequestBody LikeToggleReqVO req,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
req.getDeviceId());
anonymousRateLimiter.check(identity, "like");
return Result.ok(likeService.toggle(identity, req));
} }
/** 提交举报:同一用户对同一目标只保留一条待处理工单。 */ /** 提交举报:同一用户对同一目标只保留一条待处理工单。 */
@@ -9,16 +9,19 @@ import com.fruitshorts.user.service.AppUserService;
import com.fruitshorts.user.vo.AppUserRespVO; import com.fruitshorts.user.vo.AppUserRespVO;
import com.fruitshorts.user.vo.DeactivateReqVO; import com.fruitshorts.user.vo.DeactivateReqVO;
import com.fruitshorts.user.vo.ProfileUpdateReqVO; import com.fruitshorts.user.vo.ProfileUpdateReqVO;
import com.fruitshorts.commerce.reward.service.RewardTaskService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@@ -32,6 +35,8 @@ import java.util.Map;
public class AppMeController { public class AppMeController {
private final AppUserService userService; private final AppUserService userService;
@Autowired(required = false)
private RewardTaskService rewardTaskService;
@Operation(summary = "我的资料") @Operation(summary = "我的资料")
@GetMapping @GetMapping
@@ -42,7 +47,14 @@ public class AppMeController {
@Operation(summary = "修改资料(昵称 / 头像 / 语言等)") @Operation(summary = "修改资料(昵称 / 头像 / 语言等)")
@PutMapping @PutMapping
public Result<AppUserRespVO> update(@Valid @RequestBody ProfileUpdateReqVO req) { public Result<AppUserRespVO> update(@Valid @RequestBody ProfileUpdateReqVO req) {
return Result.ok(userService.updateProfile(SecurityUtils.getAppUserId(), req)); Long userId = SecurityUtils.getAppUserId();
AppUserRespVO profile = userService.updateProfile(userId, req);
if (rewardTaskService != null && StringUtils.hasText(profile.getNickname())
&& StringUtils.hasText(profile.getAvatarUrl())) {
rewardTaskService.recordEvent(userId, RewardTaskService.TYPE_COMPLETE_PROFILE,
userId.toString(), 1L);
}
return Result.ok(profile);
} }
@Operation(summary = "我的登录设备列表") @Operation(summary = "我的登录设备列表")
@@ -0,0 +1,78 @@
// Author: fruit.com.cn
package com.fruitshorts.app.controller;
import com.fruitshorts.commerce.reward.service.RewardCheckinService;
import com.fruitshorts.commerce.reward.service.RewardGrantService;
import com.fruitshorts.commerce.reward.service.RewardTaskService;
import com.fruitshorts.commerce.reward.vo.RewardActivityVO;
import com.fruitshorts.commerce.reward.vo.RewardCheckinRespVO;
import com.fruitshorts.commerce.reward.vo.RewardCheckinVO;
import com.fruitshorts.commerce.reward.vo.RewardClaimRespVO;
import com.fruitshorts.commerce.reward.vo.RewardOverviewVO;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.commerce.service.WalletService;
import com.fruitshorts.framework.security.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 客户端奖励中心:总览、签到、任务领取与活动。 */
@Tag(name = "客户端-奖励中心")
@RestController
@RequestMapping("/app/rewards")
@RequiredArgsConstructor
public class AppRewardController {
private final RewardTaskService taskService;
private final RewardCheckinService checkinService;
private final RewardGrantService grantService;
private final WalletService walletService;
@Operation(summary = "奖励中心总览")
@GetMapping("/overview")
public Result<RewardOverviewVO> overview(@RequestParam(required = false) String locale) {
Long userId = SecurityUtils.getAppUserIdOrNull();
long coinBalance = userId == null ? 0L : walletService.getOrCreate(userId).getCoinBalance();
RewardOverviewVO overview = taskService.overview(
userId, locale, coinBalance);
overview.setCheckin(checkinService.status(userId));
return Result.ok(overview);
}
@Operation(summary = "奖励活动列表")
@GetMapping("/activities")
public Result<List<RewardActivityVO>> activities(@RequestParam(required = false) String locale) {
return Result.ok(taskService.activities(locale));
}
@Operation(summary = "签到状态")
@GetMapping("/check-in")
public Result<RewardCheckinVO> checkInStatus() {
return Result.ok(checkinService.status(SecurityUtils.getAppUserId()));
}
@Operation(summary = "执行签到")
@PostMapping("/check-in")
public Result<RewardCheckinRespVO> checkIn() {
return Result.ok(checkinService.checkIn(SecurityUtils.getAppUserId()));
}
@Operation(summary = "领取已完成任务奖励")
@PostMapping("/tasks/{taskId}/claim")
public Result<RewardClaimRespVO> claim(
@Parameter(description = "奖励任务 ID") @PathVariable Long taskId) {
Long userId = SecurityUtils.getAppUserId();
var task = taskService.getExisting(taskId);
return Result.ok(grantService.claim(userId, task, taskService.currentProgress(userId, task)));
}
}
@@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** 客户端搜索:按标题或简介模糊匹配已上线短剧。 */ /** 客户端搜索:按标题或简介模糊匹配已上线短剧。不需要登录。 */
@Tag(name = "客户端-搜索") @Tag(name = "客户端-搜索")
@RestController @RestController
@RequestMapping("/app") @RequestMapping("/app")
@@ -2,15 +2,22 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.service.WatchProgressService; import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.commerce.reward.service.RewardTaskService;
import com.fruitshorts.playback.vo.ProgressRespVO; import com.fruitshorts.playback.vo.ProgressRespVO;
import com.fruitshorts.playback.vo.ProgressSaveReqVO; import com.fruitshorts.playback.vo.ProgressSaveReqVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@@ -20,8 +27,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 观看进度与观看记录。 */ /** 观看进度与观看记录。 */
@Tag(name = "客户端-观看进度") @Tag(name = "客户端-观看进度")
@RestController @RestController
@@ -30,38 +35,85 @@ import java.util.List;
public class AppWatchController { public class AppWatchController {
private final WatchProgressService progressService; private final WatchProgressService progressService;
@Autowired(required = false)
private RewardTaskService rewardTaskService;
private final InteractionIdentityResolver identityResolver;
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
/** 上报进度:客户端每 10 秒一次,切集时立即上报一次。 */ /** 上报进度:客户端每 10 秒一次,切集时立即上报一次。 */
@Operation(summary = "上报观看进度(客户端每 10 秒一次)") @Operation(summary = "上报观看进度(客户端每 10 秒一次)")
@PostMapping("/progress") @PostMapping("/progress")
public Result<ProgressRespVO> save(@Valid @RequestBody ProgressSaveReqVO req) { public Result<ProgressRespVO> save(@Valid @RequestBody ProgressSaveReqVO req,
return Result.ok(progressService.save(SecurityUtils.getAppUserId(), req)); HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
req.getDeviceId());
anonymousRateLimiter.check(identity, "watch");
ProgressRespVO saved = progressService.save(identity, req);
if (rewardTaskService != null && identity.authenticated()) {
rewardTaskService.recordWatch(identity.userId(), saved.getEpisodeId(),
saved.getPositionMs(), Boolean.TRUE.equals(saved.getFinished()));
}
return Result.ok(saved);
} }
/** 某部剧的续看位置,进详情页时用它决定"续看第 N 集"。 */ /** 某部剧的续看位置,进详情页时用它决定"续看第 N 集"。 */
@Operation(summary = "某部剧的续看位置") @Operation(summary = "某部剧的续看位置")
@GetMapping("/progress") @GetMapping("/progress")
public Result<ProgressRespVO> ofDrama(@RequestParam Long dramaId) { public Result<ProgressRespVO> ofDrama(
return Result.ok(progressService.ofDrama(SecurityUtils.getAppUserId(), dramaId)); @RequestParam Long dramaId,
@RequestParam(required = false) String deviceId,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
deviceId);
return Result.ok(progressService.ofDrama(identity, dramaId));
} }
@Operation(summary = "最近观看列表") /** 最近观看分页,契约与 /app/favorites 一致:pageIndex/pageSize。 */
@Operation(summary = "最近观看分页")
@GetMapping("/recent") @GetMapping("/recent")
public Result<List<ProgressRespVO>> recent(@RequestParam(defaultValue = "20") int limit) { public Result<PageResult<ProgressRespVO>> recent(
return Result.ok(progressService.recent(SecurityUtils.getAppUserId(), limit)); @RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize,
@RequestParam(required = false) String deviceId,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
deviceId);
return Result.ok(progressService.recentPage(
identity, pageIndex, pageSize));
} }
@Operation(summary = "删除某部剧的观看记录") @Operation(summary = "删除某部剧的观看记录")
@DeleteMapping("/progress/{dramaId}") @DeleteMapping("/progress/{dramaId}")
public Result<Void> remove(@PathVariable Long dramaId) { public Result<Void> remove(
progressService.remove(SecurityUtils.getAppUserId(), dramaId); @PathVariable Long dramaId,
@RequestParam(required = false) String deviceId,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
deviceId);
anonymousRateLimiter.check(identity, "watch");
progressService.remove(identity, dramaId);
return Result.ok(); return Result.ok();
} }
@Operation(summary = "清空观看记录") @Operation(summary = "清空观看记录")
@DeleteMapping("/progress") @DeleteMapping("/progress")
public Result<Void> clear() { public Result<Void> clear(
progressService.clear(SecurityUtils.getAppUserId()); @RequestParam(required = false) String deviceId,
HttpServletRequest request) {
InteractionIdentity identity = identityResolver.resolve(
SecurityUtils.getUserIdOrNull(),
request.getHeader("X-Device-Id"),
deviceId);
anonymousRateLimiter.check(identity, "watch");
progressService.clear(identity);
return Result.ok(); return Result.ok();
} }
} }
@@ -0,0 +1,44 @@
// Author: fruit.com.cn
package com.fruitshorts.app.controller;
import com.fruitshorts.system.service.LegalDocumentService;
import com.fruitshorts.system.service.LegalPages;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* 协议公开页。客户端按当前语言打开 /privacy/zh 或 /terms/en,不需要登录。
*/
@RestController
@RequiredArgsConstructor
public class LegalPageController {
private static final MediaType HTML = MediaType.parseMediaType("text/html;charset=UTF-8");
private final LegalDocumentService legalDocumentService;
/** 隐私协议。语言只接受 zh、en、id。 */
@GetMapping("/" + LegalPages.PATH_PRIVACY + "/{lang}")
public ResponseEntity<String> privacy(@PathVariable String lang) {
return page(LegalPages.PATH_PRIVACY, lang);
}
/** 服务条款。语言只接受 zh、en、id。 */
@GetMapping("/" + LegalPages.PATH_TERMS + "/{lang}")
public ResponseEntity<String> terms(@PathVariable String lang) {
return page(LegalPages.PATH_TERMS, lang);
}
private ResponseEntity<String> page(String path, String lang) {
String html = legalDocumentService.render(path, lang);
if (html == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().contentType(HTML).body(html);
}
}
@@ -0,0 +1,36 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.framework.redis.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;
/** 未登录非付费互动的设备级固定窗口限流。 */
@Component
@RequiredArgsConstructor
public class AnonymousInteractionRateLimiter {
private final RedisService redisService;
@Value("${fruitshorts.interaction.anonymous-write-per-minute:30}")
private int writesPerMinute = 30;
public void check(InteractionIdentity identity, String action) {
if (identity.authenticated()) {
return;
}
long count = redisService.increment(
"app:anonymous-interaction:" + action + ":" + identity.deviceId(),
Duration.ofMinutes(1));
if (count > writesPerMinute) {
throw new ServiceException(ErrorCode.TOO_MANY_REQUESTS, "操作过于频繁,请稍后再试");
}
}
}
@@ -8,18 +8,26 @@ import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.app.vo.AppDramaDetailVO; import com.fruitshorts.app.vo.AppDramaDetailVO;
import com.fruitshorts.app.vo.AppEpisodeVO; import com.fruitshorts.app.vo.AppEpisodeVO;
import com.fruitshorts.app.vo.AppFeedVO; import com.fruitshorts.app.vo.AppFeedVO;
import com.fruitshorts.app.vo.AppPlaylistDetailVO;
import com.fruitshorts.app.vo.AppSectionVO; import com.fruitshorts.app.vo.AppSectionVO;
import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.common.pojo.CursorResult;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.ContentBanner; import com.fruitshorts.content.dal.entity.ContentBanner;
import com.fruitshorts.content.dal.entity.ContentTag;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.enums.BannerPosition; import com.fruitshorts.content.enums.BannerPosition;
import com.fruitshorts.content.service.BannerService; import com.fruitshorts.content.service.BannerService;
import com.fruitshorts.content.service.ContentLocaleTexts;
import com.fruitshorts.content.service.ContentTagService;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaClassificationService;
import com.fruitshorts.content.service.DramaPlaylistCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.interaction.service.CommentService; import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.media.service.PlaybackSigner; import com.fruitshorts.media.service.PlaybackSigner;
import com.fruitshorts.media.service.ThumbnailUrlResolver;
import com.fruitshorts.content.vo.DramaCategoryRespVO; import com.fruitshorts.content.vo.DramaCategoryRespVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -43,37 +51,117 @@ public class AppCatalogService {
private static final int MAX_CATEGORY_SECTIONS = 4; private static final int MAX_CATEGORY_SECTIONS = 4;
private static final int DEFAULT_FEED_SIZE = 20; private static final int DEFAULT_FEED_SIZE = 20;
private static final int MAX_FEED_SIZE = 50; private static final int MAX_FEED_SIZE = 50;
private static final int DEFAULT_PLAYLIST_PAGE_SIZE = 10;
private static final int MAX_PLAYLIST_PAGE_SIZE = 20;
private static final int DEFAULT_PLAYLIST_DRAMA_PAGE_SIZE = 20;
private static final int MAX_PLAYLIST_DRAMA_PAGE_SIZE = 50;
private static final int PLAYLIST_DRAMA_PREVIEW_SIZE = 10;
private final DramaService dramaService; private final DramaService dramaService;
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final BannerService bannerService; private final BannerService bannerService;
private final DramaCategoryService dramaCategoryService; private final DramaCategoryService dramaCategoryService;
private final ContentTagService contentTagService;
private final DramaClassificationService dramaClassificationService;
private final DramaPlaylistCategoryService dramaPlaylistCategoryService;
private final PlaybackSigner playbackSigner; private final PlaybackSigner playbackSigner;
private final CommentService commentService; private final CommentService commentService;
private final ThumbnailUrlResolver thumbnailUrlResolver;
public AppFeedVO homeFeed() { public AppFeedVO homeFeed() {
Map<Long, String> categoryNames = categoryNameMap(); Map<Long, Map<String, String>> categoryLocales = categoryLocaleMap();
List<AppSectionVO> sections = new ArrayList<>(); List<AppSectionVO> sections = new ArrayList<>();
addIfNotEmpty(sections, "hot", "热门推荐", addIfNotEmpty(sections, "hot", "热门推荐",
dramaService.listPublishedHot(HOME_SECTION_SIZE), categoryNames); dramaService.listPublishedHot(HOME_SECTION_SIZE), categoryLocales);
addIfNotEmpty(sections, "new", "新剧上线", addIfNotEmpty(sections, "new", "新剧上线",
dramaService.listPublishedLatest(HOME_SECTION_SIZE), categoryNames); dramaService.listPublishedLatest(HOME_SECTION_SIZE), categoryLocales);
sections.addAll(categorySections(HOME_SECTION_SIZE, categoryNames)); sections.addAll(categorySections(HOME_SECTION_SIZE, categoryLocales));
return new AppFeedVO(banners(BannerPosition.HOME_TOP.name()), sections); return new AppFeedVO(banners(BannerPosition.HOME_TOP.name()), sections);
} }
public AppFeedVO discoverFeed() { public AppFeedVO discoverFeed() {
return new AppFeedVO(banners(BannerPosition.DISCOVER.name()), return new AppFeedVO(banners(BannerPosition.DISCOVER.name()),
categorySections(DISCOVER_SECTION_SIZE, categoryNameMap())); categorySections(DISCOVER_SECTION_SIZE, categoryLocaleMap()));
} }
/** 分类频道:运营自定义的精选/新剧/榜单等(drama_classification)。 */
public List<AppCategoryVO> categories() { public List<AppCategoryVO> categories() {
return dramaCategoryService.listBasic().stream() return dramaClassificationService.listEnabled().stream()
.filter(category -> category.getStatus() == null || category.getStatus() == 1) .map(c -> {
.map(category -> new AppCategoryVO(category.getId(), category.getName())) Map<String, String> locales = ContentLocaleTexts.read(
c.getNameLocales(), c.getName(), c.getNameEn(), c.getNameId());
AppCategoryVO vo = new AppCategoryVO(c.getId(), ContentLocaleTexts.value(locales, ContentLocaleTexts.ZH));
vo.setLocales(locales);
vo.setCode(c.getCode());
vo.setLayoutType(c.getLayoutType() == null
? DramaClassificationService.LAYOUT_GRID
: c.getLayoutType());
vo.setRevision(c.getRevision() == null ? 1L : c.getRevision());
return vo;
})
.toList(); .toList();
} }
/** 已启用类型,名称只放 locales。 */
public List<AppCategoryVO> dramaCategories() {
return dramaCategoryService.list().stream()
.filter(item -> item.getStatus() != null && item.getStatus() == 1)
.map(item -> option(item.getId(), item.getName(), item.getLocales()))
.toList();
}
/** 已启用标签,名称只放 locales。 */
public List<AppCategoryVO> tags() {
return contentTagService.listEnabled().stream()
.map(item -> option(item.getId(), item.getName(), item.getLocales()))
.toList();
}
/** 全部短剧分页。同一行多选是或,不同类型之间是且。 */
public PageResult<AppDramaCardVO> libraryDramas(List<Long> categoryIds, List<Long> classificationIds,
List<Long> tagIds, int pageIndex, int pageSize) {
PageResult<Drama> page = dramaService.pagePublishedLibrary(
categoryIds, classificationIds, tagIds, pageIndex, pageSize);
return new PageResult<>(page.getTotal(), toCards(page.getList()));
}
private AppCategoryVO option(Long id, String name, Map<String, String> locales) {
AppCategoryVO vo = new AppCategoryVO(id, name);
if (locales != null && !locales.isEmpty()) {
vo.setLocales(locales);
}
return vo;
}
/** 分类频道:按分类分页查已上线短剧卡片(通过分类关联表过滤)。 */
public PageResult<AppDramaCardVO> categoryDramas(Long classificationId,
int pageIndex, int pageSize) {
dramaClassificationService.getEnabledById(classificationId); // 校验存在/启用
List<Long> allIds = dramaClassificationService.listDramaIdsByClassification(classificationId);
if (allIds.isEmpty()) {
return PageResult.empty();
}
// 只取已上线的,再按关联表原始顺序排
Map<Long, Integer> orderMap = new HashMap<>();
for (int i = 0; i < allIds.size(); i++) orderMap.put(allIds.get(i), i);
List<Drama> published = dramaService.listPublishedByIds(allIds);
List<Drama> ordered = published.stream()
.sorted((a, b) -> Integer.compare(
orderMap.getOrDefault(a.getId(), Integer.MAX_VALUE),
orderMap.getOrDefault(b.getId(), Integer.MAX_VALUE)))
.toList();
int safeIndex = Math.max(1, pageIndex);
int safeSize = Math.max(1, Math.min(pageSize, 50));
long total = ordered.size();
int fromIndex = (safeIndex - 1) * safeSize;
if (fromIndex >= ordered.size()) {
return new PageResult<>(total, List.of());
}
int toIndex = Math.min(fromIndex + safeSize, ordered.size());
List<Drama> pageRows = ordered.subList(fromIndex, toIndex);
return new PageResult<>(total, cards(pageRows, categoryLocaleMap()));
}
public CursorResult<AppDramaCardVO> feed( public CursorResult<AppDramaCardVO> feed(
String types, Long categoryId, Long cursor, Integer size) { String types, Long categoryId, Long cursor, Integer size) {
int pageSize = size == null ? DEFAULT_FEED_SIZE : Math.max(1, Math.min(size, MAX_FEED_SIZE)); int pageSize = size == null ? DEFAULT_FEED_SIZE : Math.max(1, Math.min(size, MAX_FEED_SIZE));
@@ -91,7 +179,7 @@ public class AppCatalogService {
boolean hasMore = rows.size() > pageSize; boolean hasMore = rows.size() > pageSize;
List<Drama> pageRows = hasMore ? rows.subList(0, pageSize) : rows; List<Drama> pageRows = hasMore ? rows.subList(0, pageSize) : rows;
Long nextCursor = hasMore ? pageRows.get(pageRows.size() - 1).getId() : null; Long nextCursor = hasMore ? pageRows.get(pageRows.size() - 1).getId() : null;
return new CursorResult<>(cards(pageRows, categoryNameMap()), nextCursor, hasMore); return new CursorResult<>(cards(pageRows, categoryLocaleMap()), nextCursor, hasMore);
} }
/** /**
@@ -102,7 +190,7 @@ public class AppCatalogService {
if (dramas == null || dramas.isEmpty()) { if (dramas == null || dramas.isEmpty()) {
return List.of(); return List.of();
} }
return cards(dramas, categoryNameMap()); return cards(dramas, categoryLocaleMap());
} }
public AppDramaDetailVO dramaDetail(Long dramaId) { public AppDramaDetailVO dramaDetail(Long dramaId) {
@@ -110,15 +198,21 @@ public class AppCatalogService {
List<DramaEpisode> episodes = episodeService.listPublishedByDrama(dramaId); List<DramaEpisode> episodes = episodeService.listPublishedByDrama(dramaId);
Map<Long, Long> episodeCommentCounts = commentService.countByEpisodes( Map<Long, Long> episodeCommentCounts = commentService.countByEpisodes(
episodes.stream().map(DramaEpisode::getId).sorted().toList()); episodes.stream().map(DramaEpisode::getId).sorted().toList());
String categoryName = categoryNameMap().getOrDefault(drama.getCategoryId(), ""); Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll(
episodes.stream().map(DramaEpisode::getId).sorted().toList());
List<Map<String, String>> types = dramaCategoryService.localesForDrama(drama, categoryLocaleMap());
AppDramaDetailVO detail = new AppDramaDetailVO(); AppDramaDetailVO detail = new AppDramaDetailVO();
detail.setId(drama.getId()); detail.setId(drama.getId());
detail.setTitle(drama.getTitle()); Map<String, String> titles = ContentLocaleTexts.read(drama.getTitleLocales(), drama.getTitle(), null, null);
detail.setSynopsis(drama.getSynopsis()); Map<String, String> synopses = ContentLocaleTexts.read(
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
detail.setTitleLocales(titles);
detail.setSynopsisLocales(synopses);
detail.setCover(drama.getCoverUrl()); detail.setCover(drama.getCoverUrl());
detail.setGenre(drama.getGenre()); detail.setCoverLandscape(drama.getHorizontalCoverUrl());
detail.setCategory(categoryName); detail.setTypes(types);
fillDetailTag(detail, drama);
detail.setTotalEpisodes(drama.getTotalEpisodes()); detail.setTotalEpisodes(drama.getTotalEpisodes());
detail.setFreeEpisodes(drama.getFreeEpisodes()); detail.setFreeEpisodes(drama.getFreeEpisodes());
detail.setUnlockCoin(drama.getUnlockCoin()); detail.setUnlockCoin(drama.getUnlockCoin());
@@ -128,16 +222,77 @@ public class AppCatalogService {
detail.setFavoriteCount(drama.getFavoriteCount()); detail.setFavoriteCount(drama.getFavoriteCount());
detail.setCommentCount(commentService.countByDrama(dramaId)); detail.setCommentCount(commentService.countByDrama(dramaId));
detail.setEpisodes(episodes.stream() detail.setEpisodes(episodes.stream()
.map(episode -> toEpisode(episode, episodeCommentCounts)) .map(episode -> toEpisode(episode, episodeCommentCounts, thumbnailUrls))
.toList()); .toList());
return detail; return detail;
} }
/** C 端剧单列表:按页返回已启用剧单,每条只含该页剧单的已上线短剧。 */
public PageResult<AppPlaylistDetailVO> playlists(int pageIndex, int pageSize) {
var all = dramaPlaylistCategoryService.listEnabled();
int safeIndex = Math.max(1, pageIndex);
int safeSize = pageSize <= 0
? DEFAULT_PLAYLIST_PAGE_SIZE
: Math.min(pageSize, MAX_PLAYLIST_PAGE_SIZE);
int fromIndex = (safeIndex - 1) * safeSize;
if (fromIndex >= all.size()) {
return new PageResult<>(all.size(), List.of());
}
int toIndex = Math.min(fromIndex + safeSize, all.size());
List<AppPlaylistDetailVO> page = new ArrayList<>();
for (var category : all.subList(fromIndex, toIndex)) {
page.add(playlistDetail(category.getId(), 1, PLAYLIST_DRAMA_PREVIEW_SIZE));
}
return new PageResult<>(all.size(), page);
}
/** C 端剧单详情:剧单基本信息 + 该页已上线短剧卡片。 */
public AppPlaylistDetailVO playlistDetail(Long playlistId, int pageIndex, int pageSize) {
var category = dramaPlaylistCategoryService.getEnabledById(playlistId);
List<Long> allIds = dramaPlaylistCategoryService.listDramaIdsByCategory(playlistId);
List<Drama> published = dramaService.listPublishedByIds(allIds);
// 保留关联表原始顺序:按 allIds 位置重新排序
Map<Long, Integer> orderMap = new HashMap<>();
for (int i = 0; i < allIds.size(); i++) {
orderMap.put(allIds.get(i), i);
}
List<Drama> ordered = published.stream()
.sorted((a, b) -> {
Integer ia = orderMap.getOrDefault(a.getId(), Integer.MAX_VALUE);
Integer ib = orderMap.getOrDefault(b.getId(), Integer.MAX_VALUE);
return Integer.compare(ia, ib);
})
.toList();
int safeIndex = Math.max(1, pageIndex);
int safeSize = pageSize <= 0
? DEFAULT_PLAYLIST_DRAMA_PAGE_SIZE
: Math.min(pageSize, MAX_PLAYLIST_DRAMA_PAGE_SIZE);
int from = (safeIndex - 1) * safeSize;
List<Drama> pageRows = from >= ordered.size()
? List.of()
: ordered.subList(from, Math.min(from + safeSize, ordered.size()));
Map<String, String> locales = ContentLocaleTexts.read(
category.getNameLocales(), category.getName(), category.getNameEn(), category.getNameId());
Map<String, String> descriptions = ContentLocaleTexts.read(
category.getDescriptionLocales(), category.getDescription(),
category.getDescriptionEn(), category.getDescriptionId());
AppPlaylistDetailVO vo = new AppPlaylistDetailVO();
vo.setId(category.getId());
vo.setLocales(locales);
vo.setDescriptionLocales(descriptions);
vo.setDramaCount(ordered.size());
vo.setPageIndex(safeIndex);
vo.setPageSize(safeSize);
vo.setList(cards(pageRows, categoryLocaleMap()));
return vo;
}
private List<AppBannerVO> banners(String position) { private List<AppBannerVO> banners(String position) {
return bannerService.listActive(position).stream().map(this::toBanner).toList(); return bannerService.listActive(position).stream().map(this::toBanner).toList();
} }
private List<AppSectionVO> categorySections(int size, Map<Long, String> categoryNames) { private List<AppSectionVO> categorySections(int size, Map<Long, Map<String, String>> categoryLocales) {
List<AppSectionVO> sections = new ArrayList<>(); List<AppSectionVO> sections = new ArrayList<>();
for (DramaCategoryRespVO category : dramaCategoryService.listBasic()) { for (DramaCategoryRespVO category : dramaCategoryService.listBasic()) {
if (sections.size() >= MAX_CATEGORY_SECTIONS) { if (sections.size() >= MAX_CATEGORY_SECTIONS) {
@@ -147,17 +302,17 @@ public class AppCatalogService {
if (!dramas.isEmpty()) { if (!dramas.isEmpty()) {
sections.add(new AppSectionVO( sections.add(new AppSectionVO(
"category-" + category.getId(), "category-" + category.getId(),
category.getName(), category.getLocales(),
cards(dramas, categoryNames))); cards(dramas, categoryLocales)));
} }
} }
return sections; return sections;
} }
private void addIfNotEmpty(List<AppSectionVO> sections, String code, String title, private void addIfNotEmpty(List<AppSectionVO> sections, String code, String title,
List<Drama> dramas, Map<Long, String> categoryNames) { List<Drama> dramas, Map<Long, Map<String, String>> categoryLocales) {
if (!dramas.isEmpty()) { if (!dramas.isEmpty()) {
sections.add(new AppSectionVO(code, title, cards(dramas, categoryNames))); sections.add(new AppSectionVO(code, title, cards(dramas, categoryLocales)));
} }
} }
@@ -171,26 +326,37 @@ public class AppCatalogService {
} }
/** 整屏卡片共用一次剧集查询,取每部剧的首个可播免费集作为预览。 */ /** 整屏卡片共用一次剧集查询,取每部剧的首个可播免费集作为预览。 */
private List<AppDramaCardVO> cards(List<Drama> dramas, Map<Long, String> categoryNames) { private List<AppDramaCardVO> cards(List<Drama> dramas, Map<Long, Map<String, String>> categoryLocales) {
List<Long> ids = dramas.stream().map(Drama::getId).toList(); List<Long> ids = dramas.stream().map(Drama::getId).toList();
Map<Long, DramaEpisode> previews = episodeService.firstPlayableByDramas(ids); Map<Long, DramaEpisode> previews = episodeService.firstPlayableByDramas(ids);
Map<Long, Long> commentCounts = commentService.countByEpisodes( Map<Long, Long> commentCounts = commentService.countByEpisodes(
previews.values().stream().map(DramaEpisode::getId).sorted().toList()); previews.values().stream().map(DramaEpisode::getId).sorted().toList());
Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll(
previews.values().stream().map(DramaEpisode::getId).sorted().toList());
Map<Long, ContentTag> tags = loadTags(dramas);
return dramas.stream() return dramas.stream()
.map(drama -> toCard( .map(drama -> toCard(
drama, categoryNames, previews.get(drama.getId()), commentCounts)) drama, categoryLocales, tags, previews.get(drama.getId()), commentCounts,
thumbnailUrls))
.toList(); .toList();
} }
private AppDramaCardVO toCard(Drama drama, Map<Long, String> categoryNames, private AppDramaCardVO toCard(Drama drama, Map<Long, Map<String, String>> categoryLocales,
DramaEpisode preview, Map<Long, Long> commentCounts) { Map<Long, ContentTag> tags,
DramaEpisode preview, Map<Long, Long> commentCounts,
Map<Long, String> thumbnailUrls) {
List<Map<String, String>> types = dramaCategoryService.localesForDrama(drama, categoryLocales);
AppDramaCardVO card = new AppDramaCardVO(); AppDramaCardVO card = new AppDramaCardVO();
card.setId(drama.getId()); card.setId(drama.getId());
card.setTitle(drama.getTitle()); Map<String, String> titles = ContentLocaleTexts.read(drama.getTitleLocales(), drama.getTitle(), null, null);
Map<String, String> synopses = ContentLocaleTexts.read(
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
card.setTitleLocales(titles);
card.setCover(drama.getCoverUrl()); card.setCover(drama.getCoverUrl());
card.setSynopsis(shortSynopsis(drama.getSynopsis())); card.setCoverLandscape(drama.getHorizontalCoverUrl());
card.setGenre(drama.getGenre()); card.setSynopsisLocales(synopses);
card.setCategory(categoryNames.getOrDefault(drama.getCategoryId(), "")); card.setTypes(types);
fillTag(card, drama, tags);
card.setTotalEpisodes(drama.getTotalEpisodes()); card.setTotalEpisodes(drama.getTotalEpisodes());
card.setIsHot(drama.getIsHot() != null && drama.getIsHot() == 1); card.setIsHot(drama.getIsHot() != null && drama.getIsHot() == 1);
card.setViewCount(drama.getViewCount()); card.setViewCount(drama.getViewCount());
@@ -201,11 +367,13 @@ public class AppCatalogService {
? 0L : commentCounts.getOrDefault(preview.getId(), 0L)); ? 0L : commentCounts.getOrDefault(preview.getId(), 0L));
card.setLanguage(drama.getLanguage()); card.setLanguage(drama.getLanguage());
card.setDramaType(drama.getDramaType()); card.setDramaType(drama.getDramaType());
card.setPreview(preview == null ? null : toEpisode(preview, commentCounts)); card.setPreview(preview == null
? null : toEpisode(preview, commentCounts, thumbnailUrls));
return card; return card;
} }
private AppEpisodeVO toEpisode(DramaEpisode episode, Map<Long, Long> commentCounts) { private AppEpisodeVO toEpisode(DramaEpisode episode, Map<Long, Long> commentCounts,
Map<Long, String> thumbnailUrls) {
AppEpisodeVO vo = new AppEpisodeVO(); AppEpisodeVO vo = new AppEpisodeVO();
vo.setId(episode.getId()); vo.setId(episode.getId());
vo.setNumber(episode.getEpNo()); vo.setNumber(episode.getEpNo());
@@ -219,6 +387,7 @@ public class AppCatalogService {
vo.setUnlockCoin(episode.getUnlockCoin()); vo.setUnlockCoin(episode.getUnlockCoin());
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount()); vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L)); vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L));
vo.setThumbnailsUrl(thumbnailUrls.get(episode.getId()));
if (free) { if (free) {
// 播放地址统一在这里签名:客户端拿不到可长期复用的裸地址 // 播放地址统一在这里签名:客户端拿不到可长期复用的裸地址
vo.setPlayUrl(playbackSigner.sign(playableSource(episode))); vo.setPlayUrl(playbackSigner.sign(playableSource(episode)));
@@ -234,17 +403,56 @@ public class AppCatalogService {
return episode.getVideoUrl() == null ? "" : episode.getVideoUrl(); return episode.getVideoUrl() == null ? "" : episode.getVideoUrl();
} }
private Map<Long, String> categoryNameMap() { private Map<Long, ContentTag> loadTags(List<Drama> dramas) {
Map<Long, String> names = new HashMap<>(); List<Long> ids = dramas.stream()
dramaCategoryService.listBasic().forEach(category -> names.put(category.getId(), category.getName())); .map(Drama::getTagId)
return names; .filter(id -> id != null && id > 0L)
.distinct()
.toList();
Map<Long, ContentTag> tags = contentTagService.findByIds(ids);
return tags == null ? Map.of() : tags;
} }
/** 卡片只带一句简介,避免列表响应体过大 */ private void fillTag(AppDramaCardVO card, Drama drama, Map<Long, ContentTag> tags) {
private String shortSynopsis(String synopsis) { ContentTag tag = tagOf(drama, tags);
if (synopsis == null) { Map<String, String> locales = tagLocales(tag);
card.setTagLocales(locales);
card.setTagCode(tagCode(tag));
card.setTagColor(tag == null ? "" : tag.getBgColor());
}
private void fillDetailTag(AppDramaDetailVO detail, Drama drama) {
ContentTag tag = tagOf(drama, loadTags(List.of(drama)));
Map<String, String> locales = tagLocales(tag);
detail.setTagLocales(locales);
detail.setTagCode(tagCode(tag));
detail.setTagColor(tag == null ? "" : tag.getBgColor());
}
/** 语义码直接下发,客户端据此判断板块;未配置时给空串,由客户端按文案兜底。 */
private String tagCode(ContentTag tag) {
if (tag == null || tag.getCode() == null) {
return ""; return "";
} }
return synopsis.length() <= 60 ? synopsis : synopsis.substring(0, 60); return tag.getCode().trim();
} }
private ContentTag tagOf(Drama drama, Map<Long, ContentTag> tags) {
if (drama.getTagId() == null || drama.getTagId() <= 0L) {
return null;
}
return tags.get(drama.getTagId());
}
private Map<String, String> tagLocales(ContentTag tag) {
if (tag == null) {
return Map.of();
}
return ContentLocaleTexts.read(tag.getNameLocales(), tag.getName(), tag.getNameEn(), tag.getNameId());
}
private Map<Long, Map<String, String>> categoryLocaleMap() {
return dramaCategoryService.localeMap();
}
} }
@@ -35,6 +35,7 @@ public class AppConfigService {
KEYS.put("noticeEnabled", new KeySpec("app.notice.enabled", "true")); KEYS.put("noticeEnabled", new KeySpec("app.notice.enabled", "true"));
KEYS.put("coinUnlockEnabled", new KeySpec("app.coin.unlock.enabled", "true")); KEYS.put("coinUnlockEnabled", new KeySpec("app.coin.unlock.enabled", "true"));
KEYS.put("downloadEnabled", new KeySpec("app.download.enabled", "true")); KEYS.put("downloadEnabled", new KeySpec("app.download.enabled", "true"));
KEYS.put("loginBackgroundUrl", new KeySpec("app.login.background.url", ""));
} }
private final SysConfigMapper sysConfigMapper; private final SysConfigMapper sysConfigMapper;
@@ -0,0 +1,92 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.interaction.service.LikeService;
import com.fruitshorts.playback.service.FavoriteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** 播放页只读计数快照;固定维度批量查询,不签发播放地址或票据。 */
@Service
@RequiredArgsConstructor
public class AppEpisodeStatsService {
private final EpisodeService episodeService;
private final DramaService dramaService;
private final CommentService commentService;
private final LikeService likeService;
private final FavoriteService favoriteService;
public AppEpisodeStatsVO get(Long episodeId, Long userId, String deviceId) {
Map<Long, AppEpisodeStatsVO> stats = batch(List.of(episodeId), userId, deviceId);
AppEpisodeStatsVO result = stats.get(episodeId);
if (result == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "剧集不存在或未上线");
}
return result;
}
public AppEpisodeStatsVO get(Long episodeId, Long userId) {
return get(episodeId, userId, "");
}
/** 每类数据只查一次,供后续多集统计复用。 */
public Map<Long, AppEpisodeStatsVO> batch(Collection<Long> episodeIds, Long userId) {
return batch(episodeIds, userId, "");
}
public Map<Long, AppEpisodeStatsVO> batch(
Collection<Long> episodeIds, Long userId, String deviceId) {
if (episodeIds == null || episodeIds.isEmpty()) {
return Map.of();
}
List<DramaEpisode> episodes = episodeService.listPublishedByIds(episodeIds);
if (episodes.isEmpty()) {
return Map.of();
}
List<Long> normalizedIds = episodes.stream().map(DramaEpisode::getId).toList();
List<Long> dramaIds = episodes.stream().map(DramaEpisode::getDramaId).distinct().toList();
Map<Long, Long> commentCounts = commentService.countByEpisodes(normalizedIds);
Map<Long, Drama> dramas = new HashMap<>();
for (Drama drama : dramaService.listPublishedByIds(dramaIds)) {
dramas.put(drama.getId(), drama);
}
Set<Long> likedIds = likeService.likedTargetIds(
userId, deviceId, LikeService.TYPE_EPISODE, normalizedIds);
Set<Long> favoriteDramaIds = favoriteService.favoriteDramaIds(
userId, deviceId, dramaIds);
Map<Long, AppEpisodeStatsVO> result = new HashMap<>();
for (DramaEpisode episode : episodes) {
Drama drama = dramas.get(episode.getDramaId());
if (drama == null) {
continue;
}
AppEpisodeStatsVO vo = new AppEpisodeStatsVO();
vo.setEpisodeId(episode.getId());
vo.setDramaId(episode.getDramaId());
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L));
vo.setFavoriteCount(drama.getFavoriteCount() == null ? 0L : drama.getFavoriteCount());
vo.setLiked(likedIds.contains(episode.getId()));
vo.setFavorited(favoriteDramaIds.contains(episode.getDramaId()));
result.put(episode.getId(), vo);
}
return result;
}
}
@@ -0,0 +1,79 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.app.vo.AppRankingEntryVO;
import com.fruitshorts.app.vo.AppRankingVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.service.ContentLocaleTexts;
import com.fruitshorts.content.service.DramaClassificationService;
import com.fruitshorts.content.service.DramaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** C 端推荐榜快照组装。 */
@Service
@RequiredArgsConstructor
public class AppRankingService {
private static final int MAX_RANKING_ITEMS = 50;
private final DramaClassificationService classificationService;
private final DramaService dramaService;
private final AppCatalogService catalogService;
/** 过滤未上线短剧后保持后台位置,排名连续补齐。 */
public AppRankingVO ranking(Long classificationId) {
var classification = classificationService.getEnabledById(classificationId);
if (!DramaClassificationService.LAYOUT_RANKING.equals(classification.getLayoutType())) {
throw new ServiceException(ErrorCode.OPERATION_NOT_ALLOWED, "该分类不是推荐榜");
}
List<Long> ids = classificationService.listDramaIdsByClassification(classificationId);
List<Drama> ordered = orderedPublished(ids).stream().limit(MAX_RANKING_ITEMS).toList();
List<AppDramaCardVO> cards = catalogService.toCards(ordered);
List<AppRankingEntryVO> entries = entries(cards);
Map<String, String> locales = ContentLocaleTexts.read(
classification.getNameLocales(), classification.getName(),
classification.getNameEn(), classification.getNameId());
AppRankingVO ranking = new AppRankingVO();
ranking.setId(classification.getId());
ranking.setCode(classification.getCode());
ranking.setLocales(locales);
ranking.setRevision(classification.getRevision() == null ? 1L : classification.getRevision());
ranking.setGeneratedAt(classification.getUpdatedAt());
ranking.setTotal(entries.size());
ranking.setList(entries);
return ranking;
}
private List<AppRankingEntryVO> entries(List<AppDramaCardVO> cards) {
List<AppRankingEntryVO> entries = new ArrayList<>();
for (int index = 0; index < cards.size(); index++) {
entries.add(new AppRankingEntryVO(index + 1, cards.get(index)));
}
return entries;
}
private List<Drama> orderedPublished(List<Long> ids) {
if (ids.isEmpty()) {
return List.of();
}
Map<Long, Integer> positions = new HashMap<>();
for (int index = 0; index < ids.size(); index++) {
positions.put(ids.get(index), index);
}
return dramaService.listPublishedByIds(ids).stream()
.sorted((left, right) -> Integer.compare(
positions.getOrDefault(left.getId(), Integer.MAX_VALUE),
positions.getOrDefault(right.getId(), Integer.MAX_VALUE)))
.toList();
}
}
@@ -35,7 +35,9 @@ public class AppSearchService {
Page<Drama> page = new Page<>(safeIndex, safeSize); Page<Drama> page = new Page<>(safeIndex, safeSize);
Page<Drama> result = dramaMapper.selectPage(page, Wrappers.<Drama>lambdaQuery() Page<Drama> result = dramaMapper.selectPage(page, Wrappers.<Drama>lambdaQuery()
.eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode()) .eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode())
.and(w -> w.like(Drama::getTitle, keyword.trim()) .and(w -> w.like(Drama::getTitleLocales, keyword.trim())
.or().like(Drama::getSynopsisLocales, keyword.trim())
.or().like(Drama::getTitle, keyword.trim())
.or().like(Drama::getSynopsis, keyword.trim())) .or().like(Drama::getSynopsis, keyword.trim()))
.orderByDesc(Drama::getSort) .orderByDesc(Drama::getSort)
.orderByDesc(Drama::getId)); .orderByDesc(Drama::getId));
@@ -0,0 +1,24 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.user.event.AppInteractionMergeRequested;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;
/** 在登录事务提交前执行合并,任一步失败都会整体回滚登录。 */
@Component
@RequiredArgsConstructor
public class InteractionAccountMergeListener {
private final InteractionAccountMergeService mergeService;
@TransactionalEventListener(
phase = TransactionPhase.BEFORE_COMMIT,
fallbackExecution = false)
public void onMergeRequested(AppInteractionMergeRequested event) {
mergeService.merge(event.userId(), event.deviceId());
}
}
Loaded 100 of 394 files, more files were not shown because too many files have changed in this diff. Show more