Author SHA1 Message Date
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
181 changed files with 7502 additions and 329 deletions

No files matched your search

+1
View File
@@ -19,3 +19,4 @@ data/uploads/*
# 部署用的真实环境变量(含密钥),只提交 .env.example # 部署用的真实环境变量(含密钥),只提交 .env.example
.env .env
dump.rdb
+11
View File
@@ -73,6 +73,9 @@ services:
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}} DB_URL: ${DB_URL:-jdbc:postgresql://db:5432/${DB_NAME:-fruitshorts}}
# 限流/缓存用 Redis;容器内 127.0.0.1 是容器自身,必须指向编排里的 redis
REDIS_HOST: ${REDIS_HOST:-redis}
REDIS_PORT: ${REDIS_PORT:-6379}
ports: ports:
- "8081:8081" - "8081:8081"
volumes: volumes:
@@ -81,6 +84,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
@@ -106,6 +111,8 @@ services:
# 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名), # 管理端仅内网,页面上直接播放/下载裸媒资地址(不签播放签名),
# 因此这里不启用 /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 +141,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"]
+173 -23
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,10 +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` | 已启用首页分类。`name` 为中文,`locales` 为 `{zh,en,id}` |
| GET | `/app/categories/{id}/dramas?pageIndex=&pageSize=` | 分类下已上线短剧,分页。`pageIndex` 默认 1,`pageSize` 默认 20、最大 50 |
| 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 +202,21 @@ 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`。
>
> 卡片新增 `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/feed`) #### 推荐类型流(`GET /app/feed`)
@@ -254,7 +288,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
{ {
@@ -278,8 +313,10 @@ 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。
@@ -288,23 +325,86 @@ app.register.max-per-device-per-day
`sprite_XXX.jpg#xywh=x,y,w,h`。有 READY `media_thumbnail` 时返回签名地址, `sprite_XXX.jpg#xywh=x,y,w,h`。有 READY `media_thumbnail` 时返回签名地址,
无产物时为 `null`;该字段不影响 `playUrl`、`qualities` 和 HLS/原文件回落。 无产物时为 `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` | 最近观看分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 | | 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` | 收藏分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 | | GET | `/app/favorites` | 可选登录 | 收藏分页;匿名按设备读取,`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
| DELETE | `/app/favorites/{dramaId}` | 取消收藏 | | DELETE | `/app/favorites/{dramaId}` | 可选登录 | 取消收藏;匿名按 `X-Device-Id` |
| POST | `/app/favorites/remove` | 批量取消收藏,请求体 `{ "dramaIds": ["12", "15"] }` | | 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<Long> | 是 | 待取消的短剧 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` `GET /app/favorites?pageIndex=1&pageSize=20`
@@ -356,6 +456,11 @@ app.register.max-per-device-per-day
"dramaId": "12", "dramaId": "12",
"episodeId": "88", "episodeId": "88",
"dramaTitle": "替嫁新娘:总裁的掌心宠", "dramaTitle": "替嫁新娘:总裁的掌心宠",
"titleLocales": {
"zh": "替嫁新娘:总裁的掌心宠",
"en": "The Stand-in Bride: The CEO's Beloved",
"id": "Pengantin Pengganti: Kesayangan Presiden Direktur"
},
"dramaCover": "/files/drama_cover/12.jpg", "dramaCover": "/files/drama_cover/12.jpg",
"episodeNumber": 6, "episodeNumber": 6,
"totalEpisodes": 68, "totalEpisodes": 68,
@@ -377,7 +482,8 @@ app.register.max-per-device-per-day
| 字段 | 类型 | 说明 | | 字段 | 类型 | 说明 |
| --- | --- | --- | | --- | --- | --- |
| `dramaTitle` | string / null | 短剧标题 | | `dramaTitle` | string / null | 短剧中文标题,旧客户端回退用 |
| `titleLocales` | object / null | 短剧标题语言表,key 为 `zh` / `en` / `id`。客户端按当前语言取,没有对应语言时回退 `zh` |
| `dramaCover` | string / null | 短剧封面 | | `dramaCover` | string / null | 短剧封面 |
| `episodeNumber` | int / null | 当前续看集号 `ep_no` | | `episodeNumber` | int / null | 当前续看集号 `ep_no` |
| `totalEpisodes` | int / null | 短剧总集数 | | `totalEpisodes` | int / null | 短剧总集数 |
@@ -408,13 +514,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`(全部先审后发,生产建议)。
@@ -656,6 +771,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` | 删除,并清空已选该标签的短剧 |
**剧集** **剧集**
@@ -740,15 +865,36 @@ GET /app/notices?pageIndex=1&pageSize=20
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| 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 下载管理(已实现)
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
@@ -827,6 +973,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 可直接复用)**
@@ -834,6 +981,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` 非空数(均排除逻辑删除) |
@@ -950,8 +1099,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` 会被忽略(只作用于自己剧的分集)。
+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`。
@@ -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));
}
}
@@ -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();
}
}
@@ -3,6 +3,8 @@
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.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;
@@ -44,4 +46,20 @@ public class DashboardAdminController {
public Result<TranscodeDashboardRespVO> 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());
}
} }
@@ -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,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));
}
}
@@ -15,6 +15,8 @@ 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;
@@ -41,6 +43,7 @@ public class MediaController {
private final MediaService mediaService; private final MediaService mediaService;
private final MediaTranscodeProfileService profileService; private final MediaTranscodeProfileService profileService;
private final TranscodeBackfillAdminService backfillAdminService;
@Operation(summary = "初始化分片上传") @Operation(summary = "初始化分片上传")
@PostMapping("/upload/init") @PostMapping("/upload/init")
@@ -110,4 +113,14 @@ public class MediaController {
ImpersonationGuard.rejectWrite(); ImpersonationGuard.rejectWrite();
return Result.ok(profileService.save(profile)); 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,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());
}
}
@@ -3,7 +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.user.dal.entity.AppDeviceProfile;
import com.fruitshorts.user.dal.entity.AppUserSession; import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper; import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -13,16 +15,19 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
* 按用户最近会话解析系统。同一设备优先,否则用仍有效的最近一次登录。 * 按设备画像解析系统,缺画像时回退到用户最近会话。
* 设备画像不依赖登录态,游客行为也能显示系统。
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class AppSessionSystemService { public class AppSessionSystemService {
private final AppUserSessionMapper sessionMapper; private final AppUserSessionMapper sessionMapper;
private final AppDeviceProfileMapper profileMapper;
/** 按用户分组,组内按最近活跃倒序。 */ /** 按用户分组,组内按最近活跃倒序。 */
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) { public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
@@ -31,6 +36,9 @@ public class AppSessionSystemService {
return grouped; return grouped;
} }
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery() 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) .in(AppUserSession::getUserId, userIds)
.orderByDesc(AppUserSession::getLastActiveAt) .orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId)); .orderByDesc(AppUserSession::getId));
@@ -40,6 +48,49 @@ public class AppSessionSystemService {
return grouped; 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) { public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
if (sessions == null || sessions.isEmpty()) { if (sessions == null || sessions.isEmpty()) {
@@ -3,6 +3,8 @@
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.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;
@@ -44,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;
/** /**
* 运营大盘(只读聚合)。 * 运营大盘(只读聚合)。
* *
@@ -54,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` = 短剧表上累计计数列的求和(累计口径,不限定时间范围);
@@ -72,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;
@@ -86,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();
@@ -117,6 +129,58 @@ public class DashboardService {
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()));
@@ -130,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));
@@ -227,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,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,6 +18,7 @@ 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.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppUserMapper; import com.fruitshorts.user.dal.mapper.AppUserMapper;
@@ -27,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;
/** /**
* 后台观看记录分页与跨域装配。 * 后台观看记录分页与跨域装配。
@@ -42,6 +46,8 @@ 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;
@@ -65,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)
@@ -82,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);
@@ -100,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) {
@@ -129,19 +166,28 @@ public class WatchHistoryAdminService {
Map<Long, DramaEpisode> episodes = loadEpisodes(rows); Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser( Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
rows.stream().map(WatchHistory::getUserId).distinct().toList()); 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()))); 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;
@@ -149,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;
@@ -158,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, AppUserSession session) { 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());
@@ -177,7 +235,10 @@ 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 (session != null) { // 设备平台不依赖登录态,优先;没有记录(老数据)再回退到登录会话
if (profile != null && StringUtils.hasText(profile.getPlatform())) {
vo.setPlatform(profile.getPlatform());
} else if (session != null) {
vo.setPlatform(session.getPlatform()); vo.setPlatform(session.getPlatform());
vo.setOsVersion(session.getOsVersion()); vo.setOsVersion(session.getOsVersion());
} }
@@ -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;
}
@@ -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,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,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;
@@ -40,6 +40,11 @@ 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}
@@ -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());
}
}
@@ -45,7 +45,9 @@ class MediaTranscodeProfileContractTest {
objectMapper = new ObjectMapper(); objectMapper = new ObjectMapper();
MediaTranscodeProfileService profileService = new MediaTranscodeProfileService( MediaTranscodeProfileService profileService = new MediaTranscodeProfileService(
configService, objectMapper, new TranscodeProperties()); configService, objectMapper, new TranscodeProperties());
MediaController controller = new MediaController(mock(MediaService.class), profileService); MediaController controller = new MediaController(
mock(MediaService.class), profileService,
mock(com.fruitshorts.admin.service.TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller); mockMvc = ControllerContractSupport.mockMvcOf(controller);
given(configService.get(eq(MediaTranscodeProfileService.CONFIG_KEY), anyString())) given(configService.get(eq(MediaTranscodeProfileService.CONFIG_KEY), anyString()))
.willReturn(""); .willReturn("");
@@ -2,6 +2,7 @@
package com.fruitshorts.admin.controller; package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeBackfillAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport; import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode; import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException; import com.fruitshorts.common.exception.ServiceException;
@@ -32,7 +33,8 @@ class MediaTranscodeTriggerContractTest {
void setUp() { void setUp() {
mediaService = mock(MediaService.class); mediaService = mock(MediaService.class);
MediaController controller = new MediaController( MediaController controller = new MediaController(
mediaService, mock(MediaTranscodeProfileService.class)); mediaService, mock(MediaTranscodeProfileService.class),
mock(TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller); mockMvc = ControllerContractSupport.mockMvcOf(controller);
} }
@@ -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集"));
}
}
@@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat;
/** 观看记录匹配登录系统。 */ /** 观看记录匹配登录系统。 */
class AppSessionSystemServiceTest { class AppSessionSystemServiceTest {
private final AppSessionSystemService service = new AppSessionSystemService(null); private final AppSessionSystemService service = new AppSessionSystemService(null, null);
@Test @Test
void should_use_same_device_session_when_watch_history_has_device() { void should_use_same_device_session_when_watch_history_has_device() {
@@ -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,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;
}
}
@@ -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,13 +59,19 @@ 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 立即失效)")
@@ -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"));
}
}
} }
@@ -4,15 +4,21 @@ package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
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.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,6 +33,9 @@ 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;
@Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页") @Operation(summary = "首页聚合:轮播 + 分区,一次请求渲染整页")
@@ -56,4 +65,56 @@ 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("/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();
} }
} }
@@ -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();
} }
} }
@@ -6,6 +6,9 @@ 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.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.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;
@@ -14,6 +17,7 @@ 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;
@@ -33,12 +37,21 @@ 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()));
} }
/** 收藏列表,卡片结构与首页一致。 */ /** 收藏列表,卡片结构与首页一致。 */
@@ -46,17 +59,46 @@ public class AppFavoriteController {
@GetMapping @GetMapping
public Result<PageResult<AppDramaCardVO>> list( public Result<PageResult<AppDramaCardVO>> list(
@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) { @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( PageResult<Drama> page = favoriteService.page(
SecurityUtils.getAppUserId(), pageIndex, pageSize); identity, pageIndex, pageSize);
return Result.ok(new PageResult<>( return Result.ok(new PageResult<>(
page.getTotal(), appCatalogService.toCards(page.getList()))); 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));
} }
/** 提交举报:同一用户对同一目标只保留一条待处理工单。 */ /** 提交举报:同一用户对同一目标只保留一条待处理工单。 */
@@ -4,6 +4,9 @@ package com.fruitshorts.app.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.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.playback.vo.ProgressRespVO; import com.fruitshorts.playback.vo.ProgressRespVO;
@@ -11,6 +14,7 @@ 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.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;
@@ -29,19 +33,34 @@ import org.springframework.web.bind.annotation.RestController;
public class AppWatchController { public class AppWatchController {
private final WatchProgressService progressService; private final WatchProgressService progressService;
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");
return Result.ok(progressService.save(identity, req));
} }
/** 某部剧的续看位置,进详情页时用它决定"续看第 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));
} }
/** 最近观看分页,契约与 /app/favorites 一致:pageIndex/pageSize。 */ /** 最近观看分页,契约与 /app/favorites 一致:pageIndex/pageSize。 */
@@ -49,22 +68,43 @@ public class AppWatchController {
@GetMapping("/recent") @GetMapping("/recent")
public Result<PageResult<ProgressRespVO>> recent( public Result<PageResult<ProgressRespVO>> recent(
@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) { @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( return Result.ok(progressService.recentPage(
SecurityUtils.getAppUserId(), pageIndex, pageSize)); 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,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,14 +8,21 @@ 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;
@@ -27,6 +34,7 @@ import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Arrays; import java.util.Arrays;
@@ -44,38 +52,112 @@ 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; 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);
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));
@@ -93,7 +175,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);
} }
/** /**
@@ -104,7 +186,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) {
@@ -114,15 +196,18 @@ public class AppCatalogService {
episodes.stream().map(DramaEpisode::getId).sorted().toList()); episodes.stream().map(DramaEpisode::getId).sorted().toList());
Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll( Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll(
episodes.stream().map(DramaEpisode::getId).sorted().toList()); episodes.stream().map(DramaEpisode::getId).sorted().toList());
String categoryName = categoryNameMap().getOrDefault(drama.getCategoryId(), ""); 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.setTypes(types);
detail.setCategory(categoryName); 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());
@@ -137,11 +222,72 @@ public class AppCatalogService {
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) {
@@ -151,17 +297,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)));
} }
} }
@@ -175,30 +321,36 @@ 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( Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll(
previews.values().stream().map(DramaEpisode::getId).sorted().toList()); 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)) thumbnailUrls))
.toList(); .toList();
} }
private AppDramaCardVO toCard(Drama drama, Map<Long, String> categoryNames, private AppDramaCardVO toCard(Drama drama, Map<Long, Map<String, String>> categoryLocales,
Map<Long, ContentTag> tags,
DramaEpisode preview, Map<Long, Long> commentCounts, DramaEpisode preview, Map<Long, Long> commentCounts,
Map<Long, String> thumbnailUrls) { 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.setSynopsisLocales(shortLocales(synopses));
card.setGenre(drama.getGenre()); card.setTypes(types);
card.setCategory(categoryNames.getOrDefault(drama.getCategoryId(), "")); 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());
@@ -245,13 +397,58 @@ 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) {
ContentTag tag = tagOf(drama, tags);
Map<String, String> locales = tagLocales(tag);
card.setTagLocales(locales);
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.setTagColor(tag == null ? "" : tag.getBgColor());
}
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();
} }
/** 卡片只带一句简介,避免列表响应体过大 */ /** 卡片只带一句简介,避免列表响应体过大 */
private Map<String, String> shortLocales(Map<String, String> locales) {
Map<String, String> result = new LinkedHashMap<>();
if (locales == null) {
return result;
}
locales.forEach((code, text) -> result.put(code, shortSynopsis(text)));
return result;
}
private String shortSynopsis(String synopsis) { private String shortSynopsis(String synopsis) {
if (synopsis == null) { if (synopsis == null) {
return ""; return "";
@@ -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,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());
}
}
@@ -0,0 +1,54 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.interaction.service.LikeService;
import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.service.WatchProgressService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** 登录后的设备互动归并;三项迁移共享一个数据库事务。 */
@Slf4j
@Service
@RequiredArgsConstructor
public class InteractionAccountMergeService {
private final LikeService likeService;
private final FavoriteService favoriteService;
private final CommentService commentService;
private final WatchProgressService watchProgressService;
@Transactional(rollbackFor = Exception.class)
public void merge(Long userId, String deviceId) {
LikeService.MergeResult likes = likeService.mergeDeviceIntoUser(userId, deviceId);
FavoriteService.MergeResult favorites =
favoriteService.mergeDeviceIntoUser(userId, deviceId);
CommentService.MergeResult comments =
commentService.mergeDeviceIntoUser(userId, deviceId);
WatchProgressService.MergeResult watch =
watchProgressService.mergeDeviceIntoUser(userId, deviceId);
log.info(
"interaction-merge userId={} deviceId={} "
+ "likeMigrated={} likeDuplicates={} "
+ "favoriteMigrated={} favoriteDuplicates={} "
+ "commentMigrated={} commentDuplicates={} "
+ "watchProgressMigrated={} watchProgressIgnored={} "
+ "watchHistoryMigrated={} watchHistoryIgnored={}",
userId,
deviceId,
likes.migrated(),
likes.duplicates(),
favorites.migrated(),
favorites.duplicates(),
comments.migrated(),
comments.duplicates(),
watch.progressMigrated(),
watch.progressIgnored(),
watch.historyMigrated(),
watch.historyIgnored());
}
}
@@ -2,13 +2,19 @@
package com.fruitshorts.app.vo; package com.fruitshorts.app.vo;
import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import java.util.Map;
/** 首页分类。名称只放在 locales。 */
@Data @Data
@AllArgsConstructor
public class AppCategoryVO { public class AppCategoryVO {
private Long id; private Long id;
private String name; private Map<String, String> locales;
public AppCategoryVO(Long id, String name) {
this.id = id;
this.locales = name == null || name.isBlank() ? Map.of() : Map.of("zh", name);
}
} }
@@ -5,20 +5,26 @@ package com.fruitshorts.app.vo;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data; import lombok.Data;
import java.util.List;
import java.util.Map;
/** 列表卡片,用于首页/发现页/分类分区 */ /** 列表卡片,用于首页/发现页/分类分区 */
@Data @Data
public class AppDramaCardVO { public class AppDramaCardVO {
private Long id; private Long id;
private String title; private Map<String, String> titleLocales;
private String cover; private String cover;
private String synopsis; private Map<String, String> synopsisLocales;
private String genre; /** 短剧选中的全部类型,每项是一份语言表。 */
private String category; private List<Map<String, String>> types;
/** 标签语言表,key 为 zh / en / id。 */
private Map<String, String> tagLocales;
/** 标签角标背景色,#RRGGBB。 */
private String tagColor;
private Integer totalEpisodes; private Integer totalEpisodes;
private Boolean isHot; private Boolean isHot;
private Long viewCount; private Long viewCount;
/** 短剧累计点赞数:drama.like_count */
private Long likeCount; private Long likeCount;
/** 短剧累计收藏数:drama.favorite_count */ /** 短剧累计收藏数:drama.favorite_count */
private Long favoriteCount; private Long favoriteCount;
@@ -5,16 +5,18 @@ package com.fruitshorts.app.vo;
import lombok.Data; import lombok.Data;
import java.util.List; import java.util.List;
import java.util.Map;
@Data @Data
public class AppDramaDetailVO { public class AppDramaDetailVO {
private Long id; private Long id;
private String title; private Map<String, String> titleLocales;
private String synopsis; private Map<String, String> synopsisLocales;
private String cover; private String cover;
private String genre; private List<Map<String, String>> types;
private String category; private Map<String, String> tagLocales;
private String tagColor;
private Integer totalEpisodes; private Integer totalEpisodes;
private Integer freeEpisodes; private Integer freeEpisodes;
private Integer unlockCoin; private Integer unlockCoin;
@@ -0,0 +1,21 @@
// Author: fruit.com.cn
package com.fruitshorts.app.vo;
import lombok.Data;
import java.util.List;
/** 全部短剧分页筛选。多选 id 放在请求体里,避免查询串过长。 */
@Data
public class AppDramaPageReqVO {
private Integer pageIndex;
private Integer pageSize;
/** 类型 id,多选为或。 */
private List<Long> categoryIds;
/** 分类 id,多选为或。 */
private List<Long> classificationIds;
/** 标签 id,多选为或。 */
private List<Long> tagIds;
}
@@ -0,0 +1,18 @@
// Author: fruit.com.cn
package com.fruitshorts.app.vo;
import lombok.Data;
/** 播放页轻量计数快照,不触发票据签发。 */
@Data
public class AppEpisodeStatsVO {
private Long episodeId;
private Long dramaId;
private Long likeCount;
private Long commentCount;
private Long favoriteCount;
private Boolean liked;
private Boolean favorited;
}
@@ -0,0 +1,24 @@
// Author: fruit.com.cn
package com.fruitshorts.app.vo;
import lombok.Data;
import java.util.List;
import java.util.Map;
/** C 端剧单详情:基本信息 + 该剧单下已上线的短剧卡片。 */
@Data
public class AppPlaylistDetailVO {
private Long id;
private Map<String, String> locales;
private Map<String, String> descriptionLocales;
/** 该剧单下已上线短剧的实际条数(被下架/下线的不计入) */
private Integer dramaCount;
/** 当前短剧页码,从 1 开始 */
private Integer pageIndex;
/** 当前短剧页大小 */
private Integer pageSize;
private List<AppDramaCardVO> list;
}
@@ -2,18 +2,28 @@
package com.fruitshorts.app.vo; package com.fruitshorts.app.vo;
import lombok.AllArgsConstructor; import com.fruitshorts.content.service.ContentLocaleTexts;
import lombok.Data; import lombok.Data;
import java.util.List; import java.util.List;
import java.util.Map;
/** 首页/发现页的一个横滑分区 */ /** 首页/发现页的一个横滑分区 */
@Data @Data
@AllArgsConstructor
public class AppSectionVO { public class AppSectionVO {
/** 分区标识:hot / new / category-{id},客户端可据此做埋点与样式 */ /** 分区标识:hot / new / category-{id},客户端可据此做埋点与样式 */
private String code; private String code;
private String title; private Map<String, String> titleLocales;
private List<AppDramaCardVO> dramas; private List<AppDramaCardVO> dramas;
public AppSectionVO(String code, String title, List<AppDramaCardVO> dramas) {
this(code, Map.of(ContentLocaleTexts.ZH, title == null ? "" : title), dramas);
}
public AppSectionVO(String code, Map<String, String> titleLocales, List<AppDramaCardVO> dramas) {
this.code = code;
this.titleLocales = titleLocales;
this.dramas = dramas;
}
} }
@@ -11,4 +11,7 @@ public class GoogleLoginReqVO {
@NotBlank(message = "缺少 Google idToken") @NotBlank(message = "缺少 Google idToken")
private String idToken; private String idToken;
/** 旧客户端未统一发送请求头时,仍可用于合并设备互动。 */
private String deviceId;
} }
@@ -0,0 +1,66 @@
// Author: fruit.com.cn
package com.fruitshorts.app.web;
import com.fruitshorts.user.service.DeviceProfileService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 收集客户端上报的平台(iOS / Android)。
*
* <p>客户端在请求头带 `X-Client-Platform`,这里按 device_id 建档,
* 后台列表据此区分两端;游客请求同样入库,这是与旧会话方案的关键差异。
* 同一设备 60 秒内只写一次,避免每个请求都打库。
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceProfileFilter extends OncePerRequestFilter {
private static final long THROTTLE_MS = 60_000L;
private static final int MAX_TRACKED_DEVICES = 20_000;
private final DeviceProfileService deviceProfileService;
private final Map<String, Long> lastWriteAt = new ConcurrentHashMap<>();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
try {
collect(request);
} catch (RuntimeException ex) {
// 画像只服务于后台展示,任何异常都不能影响业务请求
log.warn("device-profile collect failed reason={}", ex.getMessage());
}
filterChain.doFilter(request, response);
}
private void collect(HttpServletRequest request) {
String deviceId = request.getHeader("X-Device-Id");
if (!StringUtils.hasText(deviceId)) {
return;
}
long now = System.currentTimeMillis();
Long last = lastWriteAt.get(deviceId);
if (last != null && now - last < THROTTLE_MS) {
return;
}
if (lastWriteAt.size() > MAX_TRACKED_DEVICES) {
lastWriteAt.clear();
}
lastWriteAt.put(deviceId, now);
deviceProfileService.touch(deviceId, request.getHeader("X-Client-Platform"));
}
}
@@ -47,6 +47,11 @@ springdoc:
path: /v3/api-docs path: /v3/api-docs
fruitshorts: fruitshorts:
web:
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
auth: auth:
# 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」 # 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」
register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5} register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5}
@@ -4,6 +4,7 @@ package com.fruitshorts.app.controller;
import com.fruitshorts.app.support.ControllerContractSupport; import com.fruitshorts.app.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode; import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException; import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.framework.web.WebUtils;
import com.fruitshorts.user.service.AppAuthService; import com.fruitshorts.user.service.AppAuthService;
import com.fruitshorts.user.service.AppOtpService; import com.fruitshorts.user.service.AppOtpService;
import com.fruitshorts.user.vo.TokenRespVO; import com.fruitshorts.user.vo.TokenRespVO;
@@ -32,13 +33,15 @@ class AppAuthControllerContractTest {
private AppOtpService otpService; private AppOtpService otpService;
private AppAuthService authService; private AppAuthService authService;
private WebUtils webUtils;
private MockMvc mockMvc; private MockMvc mockMvc;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
otpService = mock(AppOtpService.class); otpService = mock(AppOtpService.class);
authService = mock(AppAuthService.class); authService = mock(AppAuthService.class);
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService)); webUtils = mock(WebUtils.class);
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService, webUtils));
} }
@Test @Test
@@ -2,6 +2,7 @@
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.support.ControllerContractSupport; import com.fruitshorts.app.support.ControllerContractSupport;
import com.fruitshorts.app.vo.AppBannerVO; import com.fruitshorts.app.vo.AppBannerVO;
import com.fruitshorts.app.vo.AppCategoryVO; import com.fruitshorts.app.vo.AppCategoryVO;
@@ -17,15 +18,18 @@ import com.fruitshorts.playback.service.PlaybackService;
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.springframework.http.MediaType;
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 static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.nullValue;
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.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.request.MockMvcRequestBuilders.post;
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;
@@ -46,7 +50,9 @@ class AppCatalogControllerContractTest {
catalogMvc = ControllerContractSupport.mockMvcOf(new AppCatalogController(catalogService)); catalogMvc = ControllerContractSupport.mockMvcOf(new AppCatalogController(catalogService));
dramaMvc = ControllerContractSupport.mockMvcOf( dramaMvc = ControllerContractSupport.mockMvcOf(
new AppDramaController(catalogService, mock(PlaybackService.class), new AppDramaController(catalogService, mock(PlaybackService.class),
mock(EpisodeService.class), mock(CommentService.class))); mock(EpisodeService.class), mock(CommentService.class),
mock(AppEpisodeStatsService.class),
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -58,7 +64,7 @@ class AppCatalogControllerContractTest {
banner.setLinkValue("12"); banner.setLinkValue("12");
AppDramaCardVO card = new AppDramaCardVO(); AppDramaCardVO card = new AppDramaCardVO();
card.setId(12L); card.setId(12L);
card.setTitle("命运的相遇"); card.setTitleLocales(Map.of("zh", "命运的相遇"));
card.setViewCount(12400L); card.setViewCount(12400L);
card.setLikeCount(3200L); card.setLikeCount(3200L);
card.setFavoriteCount(1800L); card.setFavoriteCount(1800L);
@@ -94,7 +100,7 @@ class AppCatalogControllerContractTest {
void should_return_typed_cursor_feed() throws Exception { void should_return_typed_cursor_feed() throws Exception {
AppDramaCardVO card = new AppDramaCardVO(); AppDramaCardVO card = new AppDramaCardVO();
card.setId(12L); card.setId(12L);
card.setTitle("漫剧卡片"); card.setTitleLocales(Map.of("zh", "漫剧卡片"));
card.setDramaType("ANIME"); card.setDramaType("ANIME");
given(catalogService.feed("ANIME", 7L, null, 20)) given(catalogService.feed("ANIME", 7L, null, 20))
.willReturn(new CursorResult<>(List.of(card), 12L, true)); .willReturn(new CursorResult<>(List.of(card), 12L, true));
@@ -122,14 +128,14 @@ class AppCatalogControllerContractTest {
.andExpect(status().isOk()) .andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0)) .andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data[0].id").value(3)) .andExpect(jsonPath("$.data[0].id").value(3))
.andExpect(jsonPath("$.data[0].name").value("都市")); .andExpect(jsonPath("$.data[0].locales.zh").value("都市"));
} }
@Test @Test
void should_bind_path_variable_when_drama_detail_is_requested() throws Exception { void should_bind_path_variable_when_drama_detail_is_requested() throws Exception {
AppDramaDetailVO detail = new AppDramaDetailVO(); AppDramaDetailVO detail = new AppDramaDetailVO();
detail.setId(42L); detail.setId(42L);
detail.setTitle("命运的相遇"); detail.setTitleLocales(Map.of("zh", "命运的相遇"));
detail.setViewCount(12400L); detail.setViewCount(12400L);
detail.setLikeCount(3200L); detail.setLikeCount(3200L);
detail.setFavoriteCount(1800L); detail.setFavoriteCount(1800L);
@@ -142,7 +148,7 @@ class AppCatalogControllerContractTest {
.andExpect(jsonPath("$.code").value(0)) .andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.id").value("42")) .andExpect(jsonPath("$.data.id").value("42"))
.andExpect(jsonPath("$.data.id").isString()) .andExpect(jsonPath("$.data.id").isString())
.andExpect(jsonPath("$.data.title").value("命运的相遇")) .andExpect(jsonPath("$.data.titleLocales.zh").value("命运的相遇"))
.andExpect(jsonPath("$.data.viewCount").value("12400")) .andExpect(jsonPath("$.data.viewCount").value("12400"))
.andExpect(jsonPath("$.data.likeCount").value("3200")) .andExpect(jsonPath("$.data.likeCount").value("3200"))
.andExpect(jsonPath("$.data.favoriteCount").value("1800")) .andExpect(jsonPath("$.data.favoriteCount").value("1800"))
@@ -161,4 +167,23 @@ class AppCatalogControllerContractTest {
.andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode())) .andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode()))
.andExpect(jsonPath("$.data").value(nullValue())); .andExpect(jsonPath("$.data").value(nullValue()));
} }
@Test
void should_bind_filter_ids_from_body_when_drama_page_is_posted() throws Exception {
AppDramaCardVO card = new AppDramaCardVO();
card.setId(9L);
card.setTitleLocales(Map.of("zh", "重生"));
given(catalogService.libraryDramas(List.of(2L), List.of(3L), List.of(4L), 1, 20))
.willReturn(new com.fruitshorts.common.pojo.PageResult<>(1L, List.of(card)));
catalogMvc.perform(post("/app/dramas/page")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"pageIndex\":1,\"pageSize\":20,"
+ "\"categoryIds\":[\"2\"],\"classificationIds\":[\"3\"],\"tagIds\":[\"4\"]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.total").value("1"))
.andExpect(jsonPath("$.data.list[0].titleLocales.zh").value("重生"));
verify(catalogService).libraryDramas(List.of(2L), List.of(3L), List.of(4L), 1, 20);
}
} }
@@ -6,6 +6,8 @@ import com.fruitshorts.app.support.ControllerContractSupport;
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.interaction.service.CommentService; import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
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.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
@@ -32,7 +34,12 @@ class AppCommentControllerContractTest {
commentService = mock(CommentService.class); commentService = mock(CommentService.class);
episodeService = mock(EpisodeService.class); episodeService = mock(EpisodeService.class);
mockMvc = ControllerContractSupport.mockMvcOf( mockMvc = ControllerContractSupport.mockMvcOf(
new AppCommentController(commentService, episodeService)); new AppCommentController(
commentService,
episodeService,
mock(InteractionIdentityResolver.class),
mock(AnonymousInteractionRateLimiter.class),
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -3,9 +3,21 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruitshorts.app.service.AppEpisodeStatsService;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.common.pojo.CursorResult;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.interaction.service.LikeService;
import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.service.PlaybackService;
import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.playback.vo.ProgressRespVO;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.framework.log.AccessDeniedRecorder; import com.fruitshorts.framework.log.AccessDeniedRecorder;
import com.fruitshorts.framework.security.JwtAuthenticationFilter; import com.fruitshorts.framework.security.JwtAuthenticationFilter;
import com.fruitshorts.framework.security.JwtTokenProvider; import com.fruitshorts.framework.security.JwtTokenProvider;
@@ -34,8 +46,12 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import java.util.List; import java.util.List;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
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.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
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;
@@ -52,12 +68,39 @@ class AppCommentCountAnonymousSecurityTest {
private CommentService commentService; private CommentService commentService;
@Autowired @Autowired
private AppCatalogService catalogService; private AppCatalogService catalogService;
@Autowired
private AppEpisodeStatsService episodeStatsService;
@Autowired
private FavoriteService favoriteService;
@Autowired
private WatchProgressService watchProgressService;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
given(commentService.countByDrama(7L)).willReturn(9L); given(commentService.countByDrama(7L)).willReturn(9L);
given(catalogService.feed("ANIME", null, null, 20)) given(catalogService.feed("ANIME", null, null, 20))
.willReturn(new CursorResult<>(List.of(), null, false)); .willReturn(new CursorResult<>(List.of(), null, false));
AppEpisodeStatsVO stats = new AppEpisodeStatsVO();
stats.setEpisodeId(11L);
stats.setDramaId(7L);
stats.setLikeCount(12L);
stats.setCommentCount(3L);
stats.setFavoriteCount(8L);
stats.setLiked(true);
stats.setFavorited(false);
given(episodeStatsService.get(11L, null, "device-a")).willReturn(stats);
given(favoriteService.page(any(InteractionIdentity.class), any(Integer.class), any(Integer.class)))
.willReturn(new PageResult<>(0L, List.of()));
given(favoriteService.removeBatch(any(InteractionIdentity.class), anyList()))
.willReturn(1);
given(catalogService.toCards(List.of())).willReturn(List.of());
given(watchProgressService.recentPage(
any(InteractionIdentity.class), any(Integer.class), any(Integer.class)))
.willReturn(new PageResult<>(0L, List.of()));
given(watchProgressService.ofDrama(any(InteractionIdentity.class), any(Long.class)))
.willReturn(null);
given(watchProgressService.save(any(InteractionIdentity.class), any()))
.willReturn(new ProgressRespVO());
} }
@Test @Test
@@ -78,6 +121,93 @@ class AppCommentCountAnonymousSecurityTest {
.andExpect(jsonPath("$.data.list").isArray()); .andExpect(jsonPath("$.data.list").isArray());
} }
@Test
void should_allow_anonymous_non_paid_interactions_through_security_chain() throws Exception {
mockMvc.perform(post("/app/likes/toggle")
.header("X-Device-Id", "device-a")
.contentType("application/json")
.content("{\"targetType\":\"EPISODE\",\"targetId\":\"11\"}"))
.andExpect(status().isOk());
mockMvc.perform(post("/app/favorites/toggle")
.header("X-Device-Id", "device-a")
.contentType("application/json")
.content("{\"dramaId\":\"7\"}"))
.andExpect(status().isOk());
mockMvc.perform(post("/app/comments")
.header("X-Device-Id", "device-a")
.contentType("application/json")
.content("{\"dramaId\":\"7\",\"content\":\"hello\"}"))
.andExpect(status().isOk());
}
@Test
void should_allow_anonymous_episode_stats_through_security_chain() throws Exception {
mockMvc.perform(get("/app/episodes/11/stats")
.header("X-Device-Id", "device-a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.episodeId").value(11))
.andExpect(jsonPath("$.data.liked").value(true))
.andExpect(jsonPath("$.data.favoriteCount").value(8));
}
@Test
void should_allow_anonymous_library_and_watch_operations() throws Exception {
mockMvc.perform(get("/app/favorites").header("X-Device-Id", "device-a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
mockMvc.perform(get("/app/watch/recent").header("X-Device-Id", "device-a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
mockMvc.perform(get("/app/watch/progress")
.header("X-Device-Id", "device-a")
.param("dramaId", "7"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
mockMvc.perform(post("/app/watch/progress")
.header("X-Device-Id", "device-a")
.contentType("application/json")
.content("{\"episodeId\":11,\"positionMs\":1000}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
mockMvc.perform(delete("/app/watch/progress/7")
.header("X-Device-Id", "device-a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
mockMvc.perform(delete("/app/watch/progress")
.header("X-Device-Id", "device-a"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0));
}
@Test
void should_allow_anonymous_favorite_batch_removal_through_security_chain()
throws Exception {
mockMvc.perform(post("/app/favorites/remove")
.header("X-Device-Id", "device-a")
.contentType("application/json")
.content("{\"dramaIds\":[\"7\"]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data").value(1));
}
@Test
void should_keep_paid_and_entitlement_operations_login_required() throws Exception {
mockMvc.perform(post("/app/episodes/11/unlock"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
mockMvc.perform(get("/app/wallet"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
mockMvc.perform(post("/app/orders"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
mockMvc.perform(get("/app/orders"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
}
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
@EnableWebSecurity @EnableWebSecurity
@@ -90,8 +220,105 @@ class AppCommentCountAnonymousSecurityTest {
} }
@Bean @Bean
AppCommentController appCommentController(CommentService commentService) { EpisodeService episodeService() {
return new AppCommentController(commentService, mock(EpisodeService.class)); return mock(EpisodeService.class);
}
@Bean
AppCommentController appCommentController(
CommentService commentService,
EpisodeService episodeService,
InteractionIdentityResolver identityResolver,
AnonymousInteractionRateLimiter rateLimiter) {
return new AppCommentController(
commentService,
episodeService,
identityResolver,
rateLimiter,
mock(com.fruitshorts.framework.web.WebUtils.class));
}
@Bean
LikeService likeService() {
return mock(LikeService.class);
}
@Bean
FavoriteService favoriteService() {
return mock(FavoriteService.class);
}
@Bean
WatchProgressService watchProgressService() {
return mock(WatchProgressService.class);
}
@Bean
AppInteractionController appInteractionController(
LikeService likeService,
InteractionIdentityResolver identityResolver,
AnonymousInteractionRateLimiter rateLimiter) {
return new AppInteractionController(
likeService,
mock(com.fruitshorts.interaction.service.ReportService.class),
identityResolver,
rateLimiter);
}
@Bean
AppFavoriteController appFavoriteController(
FavoriteService favoriteService,
InteractionIdentityResolver identityResolver,
AnonymousInteractionRateLimiter rateLimiter) {
return new AppFavoriteController(
favoriteService,
mock(AppCatalogService.class),
identityResolver,
rateLimiter);
}
@Bean
AppWatchController appWatchController(
WatchProgressService watchProgressService,
InteractionIdentityResolver identityResolver,
AnonymousInteractionRateLimiter rateLimiter) {
return new AppWatchController(
watchProgressService,
identityResolver,
rateLimiter);
}
@Bean
AppEpisodeStatsService appEpisodeStatsService() {
return mock(AppEpisodeStatsService.class);
}
@Bean
AppDramaController appDramaController(
AppCatalogService appCatalogService,
EpisodeService episodeService,
CommentService commentService,
AppEpisodeStatsService appEpisodeStatsService) {
return new AppDramaController(
appCatalogService,
mock(PlaybackService.class),
episodeService,
commentService,
appEpisodeStatsService,
mock(com.fruitshorts.framework.web.WebUtils.class));
}
@Bean
InteractionIdentityResolver identityResolver() {
return new InteractionIdentityResolver();
}
@Bean
AnonymousInteractionRateLimiter anonymousInteractionRateLimiter() {
AnonymousInteractionRateLimiter limiter =
mock(AnonymousInteractionRateLimiter.class);
Mockito.doNothing().when(limiter).check(Mockito.any(), Mockito.anyString());
return limiter;
} }
@Bean @Bean
@@ -115,7 +342,7 @@ class AppCommentCountAnonymousSecurityTest {
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) { RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
return new RestAuthEntryPoint( return new RestAuthEntryPoint(
objectMapper, objectMapper,
new AccessDeniedRecorder(mock(ObjectProvider.class))); new AccessDeniedRecorder(mock(ObjectProvider.class), mock(ObjectProvider.class)));
} }
@Bean @Bean
@@ -132,4 +359,5 @@ class AppCommentCountAnonymousSecurityTest {
.build(); .build();
} }
} }
} }
@@ -6,8 +6,11 @@ import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.support.ControllerContractSupport; import com.fruitshorts.app.support.ControllerContractSupport;
import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.framework.security.LoginUser; import com.fruitshorts.framework.security.LoginUser;
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
import com.fruitshorts.playback.service.FavoriteService; import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.service.WatchProgressService; import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.playback.vo.ProgressRespVO; import com.fruitshorts.playback.vo.ProgressRespVO;
@@ -19,12 +22,16 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List; import java.util.List;
import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.given;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; 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.request.MockMvcRequestBuilders.post;
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;
@@ -44,10 +51,17 @@ class AppLibraryPagingContractTest {
favoriteService = mock(FavoriteService.class); favoriteService = mock(FavoriteService.class);
catalogService = mock(AppCatalogService.class); catalogService = mock(AppCatalogService.class);
progressService = mock(WatchProgressService.class); progressService = mock(WatchProgressService.class);
InteractionIdentityResolver identityResolver = new InteractionIdentityResolver();
AnonymousInteractionRateLimiter rateLimiter =
mock(AnonymousInteractionRateLimiter.class);
favoriteMvc = ControllerContractSupport.mockMvcOf( favoriteMvc = ControllerContractSupport.mockMvcOf(
new AppFavoriteController(favoriteService, catalogService)); new AppFavoriteController(
favoriteService,
catalogService,
identityResolver,
rateLimiter));
watchMvc = ControllerContractSupport.mockMvcOf( watchMvc = ControllerContractSupport.mockMvcOf(
new AppWatchController(progressService)); new AppWatchController(progressService, identityResolver, rateLimiter));
SecurityContextHolder.getContext().setAuthentication( SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken( new UsernamePasswordAuthenticationToken(
new LoginUser(USER_ID, "app-user", "APP_USER", List.of()), new LoginUser(USER_ID, "app-user", "APP_USER", List.of()),
@@ -66,9 +80,9 @@ class AppLibraryPagingContractTest {
Drama first = drama(101L, "收藏一"); Drama first = drama(101L, "收藏一");
Drama second = drama(102L, "收藏二"); Drama second = drama(102L, "收藏二");
Drama third = drama(103L, "收藏三"); Drama third = drama(103L, "收藏三");
given(favoriteService.page(USER_ID, 1, 20)) given(favoriteService.page(any(InteractionIdentity.class), eq(1), eq(20)))
.willReturn(new PageResult<>(21L, List.of(first, second))); .willReturn(new PageResult<>(21L, List.of(first, second)));
given(favoriteService.page(USER_ID, 2, 20)) given(favoriteService.page(any(InteractionIdentity.class), eq(2), eq(20)))
.willReturn(new PageResult<>(21L, List.of(third))); .willReturn(new PageResult<>(21L, List.of(third)));
given(catalogService.toCards(List.of(first, second))) given(catalogService.toCards(List.of(first, second)))
.willReturn(List.of(card(101L), card(102L))); .willReturn(List.of(card(101L), card(102L)));
@@ -89,8 +103,8 @@ class AppLibraryPagingContractTest {
.andExpect(jsonPath("$.data.list.length()").value(1)) .andExpect(jsonPath("$.data.list.length()").value(1))
.andExpect(jsonPath("$.data.list[0].id").value("103")); .andExpect(jsonPath("$.data.list[0].id").value("103"));
verify(favoriteService).page(USER_ID, 1, 20); verify(favoriteService).page(any(InteractionIdentity.class), eq(1), eq(20));
verify(favoriteService).page(USER_ID, 2, 20); verify(favoriteService).page(any(InteractionIdentity.class), eq(2), eq(20));
} }
@Test @Test
@@ -98,9 +112,9 @@ class AppLibraryPagingContractTest {
ProgressRespVO first = progress(12L, 88L, 6, "剧名一", 68); ProgressRespVO first = progress(12L, 88L, 6, "剧名一", 68);
ProgressRespVO second = progress(13L, 99L, 2, "剧名二", 20); ProgressRespVO second = progress(13L, 99L, 2, "剧名二", 20);
ProgressRespVO third = progress(14L, 100L, 1, "剧名三", 16); ProgressRespVO third = progress(14L, 100L, 1, "剧名三", 16);
given(progressService.recentPage(USER_ID, 1, 20)) given(progressService.recentPage(any(InteractionIdentity.class), eq(1), eq(20)))
.willReturn(new PageResult<>(23L, List.of(first, second))); .willReturn(new PageResult<>(23L, List.of(first, second)));
given(progressService.recentPage(USER_ID, 2, 20)) given(progressService.recentPage(any(InteractionIdentity.class), eq(2), eq(20)))
.willReturn(new PageResult<>(23L, List.of(third))); .willReturn(new PageResult<>(23L, List.of(third)));
watchMvc.perform(get("/app/watch/recent")) watchMvc.perform(get("/app/watch/recent"))
@@ -120,14 +134,51 @@ class AppLibraryPagingContractTest {
.andExpect(jsonPath("$.data.list[0].dramaId").value("14")) .andExpect(jsonPath("$.data.list[0].dramaId").value("14"))
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名三")); .andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名三"));
verify(progressService).recentPage(USER_ID, 1, 20); verify(progressService).recentPage(any(InteractionIdentity.class), eq(1), eq(20));
verify(progressService).recentPage(USER_ID, 2, 20); verify(progressService).recentPage(any(InteractionIdentity.class), eq(2), eq(20));
}
@Test
void should_remove_favorite_batch_for_signed_in_user() throws Exception {
given(favoriteService.removeBatch(any(InteractionIdentity.class), eq(List.of(7L, 8L))))
.willReturn(2);
favoriteMvc.perform(post("/app/favorites/remove")
.contentType("application/json")
.content("{\"dramaIds\":[\"7\",\"8\"]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data").value(2));
verify(favoriteService).removeBatch(any(InteractionIdentity.class), eq(List.of(7L, 8L)));
}
@Test
void should_reject_empty_favorite_batch() throws Exception {
favoriteMvc.perform(post("/app/favorites/remove")
.contentType("application/json")
.content("{\"dramaIds\":[]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("dramaIds 不能为空"));
}
@Test
void should_reject_favorite_batch_over_limit() throws Exception {
String dramaIds = String.join(",", Collections.nCopies(201, "\"7\""));
favoriteMvc.perform(post("/app/favorites/remove")
.contentType("application/json")
.content("{\"dramaIds\":[" + dramaIds + "]}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("dramaIds 最多 200 条"));
} }
@Test @Test
void should_keep_total_and_return_empty_list_when_watch_page_is_out_of_range() void should_keep_total_and_return_empty_list_when_watch_page_is_out_of_range()
throws Exception { throws Exception {
given(progressService.recentPage(USER_ID, 9, 20)) given(progressService.recentPage(any(InteractionIdentity.class), eq(9), eq(20)))
.willReturn(new PageResult<>(23L, List.of())); .willReturn(new PageResult<>(23L, List.of()));
watchMvc.perform(get("/app/watch/recent").param("pageIndex", "9")) watchMvc.perform(get("/app/watch/recent").param("pageIndex", "9"))
@@ -140,7 +191,7 @@ class AppLibraryPagingContractTest {
@Test @Test
void should_ignore_removed_limit_and_still_return_page_result() throws Exception { void should_ignore_removed_limit_and_still_return_page_result() throws Exception {
// limit 已从契约移除:即使客户端误传,也应走分页并返回 PageResult。 // limit 已从契约移除:即使客户端误传,也应走分页并返回 PageResult。
given(progressService.recentPage(USER_ID, 1, 20)) given(progressService.recentPage(any(InteractionIdentity.class), eq(1), eq(20)))
.willReturn(new PageResult<>(3L, List.of(progress(12L, 88L, 6, "剧名一", 68)))); .willReturn(new PageResult<>(3L, List.of(progress(12L, 88L, 6, "剧名一", 68))));
watchMvc.perform(get("/app/watch/recent").param("limit", "5")) watchMvc.perform(get("/app/watch/recent").param("limit", "5"))
@@ -150,7 +201,7 @@ class AppLibraryPagingContractTest {
.andExpect(jsonPath("$.data.list.length()").value(1)) .andExpect(jsonPath("$.data.list.length()").value(1))
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名一")); .andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名一"));
verify(progressService).recentPage(USER_ID, 1, 20); verify(progressService).recentPage(any(InteractionIdentity.class), eq(1), eq(20));
} }
private Drama drama(Long id, String title) { private Drama drama(Long id, String title) {
@@ -2,6 +2,8 @@
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.AppEpisodeStatsVO;
import com.fruitshorts.app.support.ControllerContractSupport; import com.fruitshorts.app.support.ControllerContractSupport;
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;
@@ -37,6 +39,7 @@ class AppPlaybackContractTest {
private PlaybackService playbackService; private PlaybackService playbackService;
private EpisodeService episodeService; private EpisodeService episodeService;
private CommentService commentService; private CommentService commentService;
private AppEpisodeStatsService episodeStatsService;
private MockMvc mockMvc; private MockMvc mockMvc;
@BeforeEach @BeforeEach
@@ -44,13 +47,15 @@ class AppPlaybackContractTest {
playbackService = mock(PlaybackService.class); playbackService = mock(PlaybackService.class);
episodeService = mock(EpisodeService.class); episodeService = mock(EpisodeService.class);
commentService = mock(CommentService.class); commentService = mock(CommentService.class);
episodeStatsService = mock(AppEpisodeStatsService.class);
DramaEpisode episode = new DramaEpisode(); DramaEpisode episode = new DramaEpisode();
episode.setLikeCount(88L); episode.setLikeCount(88L);
given(episodeService.getExisting(any())).willReturn(episode); given(episodeService.getExisting(any())).willReturn(episode);
given(commentService.countByEpisodes(any())).willReturn(Map.of()); given(commentService.countByEpisodes(any())).willReturn(Map.of());
mockMvc = ControllerContractSupport.mockMvcOf( mockMvc = ControllerContractSupport.mockMvcOf(
new AppDramaController(mock(AppCatalogService.class), playbackService, new AppDramaController(mock(AppCatalogService.class), playbackService,
episodeService, commentService)); episodeService, commentService, episodeStatsService,
mock(com.fruitshorts.framework.web.WebUtils.class)));
} }
@Test @Test
@@ -102,6 +107,32 @@ class AppPlaybackContractTest {
verify(playbackService).play(isNull(), eq(13L), eq("device-9"), any()); verify(playbackService).play(isNull(), eq(13L), eq("device-9"), any());
} }
@Test
void should_return_episode_stats_without_play_ticket() throws Exception {
AppEpisodeStatsVO stats = new AppEpisodeStatsVO();
stats.setEpisodeId(11L);
stats.setDramaId(7L);
stats.setLikeCount(88L);
stats.setCommentCount(8L);
stats.setFavoriteCount(1800L);
stats.setLiked(true);
stats.setFavorited(false);
given(episodeStatsService.get(11L, null, null)).willReturn(stats);
mockMvc.perform(get("/app/episodes/11/stats"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.episodeId").value("11"))
.andExpect(jsonPath("$.data.dramaId").value("7"))
.andExpect(jsonPath("$.data.likeCount").value("88"))
.andExpect(jsonPath("$.data.commentCount").value("8"))
.andExpect(jsonPath("$.data.favoriteCount").value("1800"))
.andExpect(jsonPath("$.data.liked").value(true))
.andExpect(jsonPath("$.data.favorited").value(false));
verify(episodeStatsService).get(11L, null, null);
verify(playbackService, org.mockito.Mockito.never()).play(any(), any(), any(), any());
}
private PlayRespVO ticket(Long episodeId, boolean accessible, String accessType, private PlayRespVO ticket(Long episodeId, boolean accessible, String accessType,
String playUrl, String thumbnailsUrl) { String playUrl, String thumbnailsUrl) {
PlayRespVO vo = new PlayRespVO(); PlayRespVO vo = new PlayRespVO();
@@ -0,0 +1,48 @@
// 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 org.junit.jupiter.api.Test;
import org.springframework.test.util.ReflectionTestUtils;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
class AnonymousInteractionRateLimiterTest {
@Test
void should_reject_anonymous_device_after_per_minute_limit() {
RedisService redisService = mock(RedisService.class);
given(redisService.increment(anyString(), any())).willReturn(31L);
AnonymousInteractionRateLimiter limiter =
new AnonymousInteractionRateLimiter(redisService);
ReflectionTestUtils.setField(limiter, "writesPerMinute", 30);
assertThatThrownBy(() -> limiter.check(
new InteractionIdentity(null, "device-a"),
"like"))
.isInstanceOfSatisfying(ServiceException.class, error ->
org.assertj.core.api.Assertions.assertThat(error.getCode())
.isEqualTo(ErrorCode.TOO_MANY_REQUESTS.getCode()));
}
@Test
void should_not_rate_limit_authenticated_user() {
RedisService redisService = mock(RedisService.class);
AnonymousInteractionRateLimiter limiter =
new AnonymousInteractionRateLimiter(redisService);
limiter.check(new InteractionIdentity(9L, ""), "comment");
verify(redisService, never()).increment(anyString(), any());
}
}
@@ -16,18 +16,22 @@ import com.fruitshorts.user.dal.mapper.AppUserMapper;
import com.fruitshorts.user.dal.mapper.AppUserOtpMapper; import com.fruitshorts.user.dal.mapper.AppUserOtpMapper;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper; import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import com.fruitshorts.user.enums.AppUserStatus; import com.fruitshorts.user.enums.AppUserStatus;
import com.fruitshorts.user.event.AppInteractionMergeRequested;
import com.fruitshorts.user.service.AppAuthService; import com.fruitshorts.user.service.AppAuthService;
import com.fruitshorts.user.service.AppOtpService; import com.fruitshorts.user.service.AppOtpService;
import com.fruitshorts.user.service.CredentialHasher; import com.fruitshorts.user.service.CredentialHasher;
import com.fruitshorts.user.service.GoogleIdTokenVerifier; import com.fruitshorts.user.service.GoogleIdTokenVerifier;
import com.fruitshorts.user.service.GoogleUser; import com.fruitshorts.user.service.GoogleUser;
import com.fruitshorts.user.service.IpRegionService;
import com.fruitshorts.user.service.OtpSender; import com.fruitshorts.user.service.OtpSender;
import com.fruitshorts.user.vo.LoginReqVO; import com.fruitshorts.user.vo.LoginReqVO;
import com.fruitshorts.user.vo.RegisterReqVO; import com.fruitshorts.user.vo.RegisterReqVO;
import com.fruitshorts.user.vo.TokenRespVO; import com.fruitshorts.user.vo.TokenRespVO;
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.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import java.time.Duration; import java.time.Duration;
@@ -63,6 +67,8 @@ class AppAuthServiceTest {
private PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
private ConfigService configService; private ConfigService configService;
private GoogleIdTokenVerifier googleVerifier; private GoogleIdTokenVerifier googleVerifier;
private ApplicationEventPublisher eventPublisher;
private IpRegionService ipRegionService;
private AppAuthService authService; private AppAuthService authService;
@BeforeEach @BeforeEach
@@ -78,11 +84,15 @@ class AppAuthServiceTest {
passwordEncoder = mock(PasswordEncoder.class); passwordEncoder = mock(PasswordEncoder.class);
configService = mock(ConfigService.class); configService = mock(ConfigService.class);
googleVerifier = mock(GoogleIdTokenVerifier.class); googleVerifier = mock(GoogleIdTokenVerifier.class);
eventPublisher = mock(ApplicationEventPublisher.class);
ipRegionService = mock(IpRegionService.class);
given(configService.get(anyString(), anyString())) given(configService.get(anyString(), anyString()))
.willAnswer(invocation -> invocation.getArgument(1)); .willAnswer(invocation -> invocation.getArgument(1));
// 单测里默认解析不出国家,走客户端区域 / 印尼兜底
given(ipRegionService.resolveCountry(any())).willReturn("");
authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper, authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService, deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService,
googleVerifier); googleVerifier, eventPublisher, ipRegionService);
} }
@Test @Test
@@ -98,6 +108,9 @@ class AppAuthServiceTest {
// 免码注册不等于"已验证":邮箱可达性没验证过,所以先记 0,等日后点验证链接再置 1 // 免码注册不等于"已验证":邮箱可达性没验证过,所以先记 0,等日后点验证链接再置 1
assertThat(saved.get().getVerified()).isZero(); assertThat(saved.get().getVerified()).isZero();
verify(otpService, never()).consume(anyString(), anyString(), anyString(), any()); verify(otpService, never()).consume(anyString(), anyString(), anyString(), any());
AppInteractionMergeRequested event = capturedMergeEvent();
assertThat(event.userId()).isEqualTo(1001L);
assertThat(event.deviceId()).isEqualTo("device-9");
} }
@Test @Test
@@ -251,6 +264,44 @@ class AppAuthServiceTest {
assertThat(resp.getAccessToken()).isEqualTo("access-1"); assertThat(resp.getAccessToken()).isEqualTo("access-1");
assertThat(resp.getUser().getUid()).isEqualTo("UAB12CD"); assertThat(resp.getUser().getUid()).isEqualTo("UAB12CD");
verify(sessionMapper).insert(any(AppUserSession.class)); verify(sessionMapper).insert(any(AppUserSession.class));
AppInteractionMergeRequested event = capturedMergeEvent();
assertThat(event.userId()).isEqualTo(1001L);
assertThat(event.deviceId()).isEqualTo("device-9");
}
@Test
void should_sync_country_from_ip_on_login() {
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
given(ipRegionService.resolveCountry(any())).willReturn("TH");
authService.login(emailLogin("abcd1234"), "49.237.8.1");
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
verify(userMapper).updateById(captor.capture());
AppUser saved = captor.getValue();
assertThat(saved.getCountryCode()).isEqualTo("TH");
assertThat(saved.getRegionCode()).isEqualTo("TH");
assertThat(saved.getLanguage()).isEqualTo("en-US");
assertThat(saved.getTimezone()).isEqualTo("Asia/Bangkok");
assertThat(saved.getCurrency()).isEqualTo("THB");
}
@Test
void should_keep_user_customized_language_when_syncing_country() {
AppUser user = user(AppUserStatus.NORMAL);
user.setLanguage("zh-CN");
stubLogin(credential("bcrypt-hash"), user);
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
given(ipRegionService.resolveCountry(any())).willReturn("TH");
authService.login(emailLogin("abcd1234"), "49.237.8.1");
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
verify(userMapper).updateById(captor.capture());
assertThat(captor.getValue().getCountryCode()).isEqualTo("TH");
// 用户自己改过的语言不被 IP 覆盖
assertThat(captor.getValue().getLanguage()).isEqualTo("zh-CN");
} }
@Test @Test
@@ -307,11 +358,14 @@ class AppAuthServiceTest {
}); });
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get()); given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
TokenRespVO resp = authService.googleLogin("google-id-token"); TokenRespVO resp = authService.googleLogin("google-id-token", "device-9", "203.0.113.9");
assertThat(resp.getAccessToken()).isEqualTo("access-1"); assertThat(resp.getAccessToken()).isEqualTo("access-1");
assertThat(resp.isNewUser()).isTrue(); assertThat(resp.isNewUser()).isTrue();
verify(sessionMapper).insert(any(AppUserSession.class)); verify(sessionMapper).insert(any(AppUserSession.class));
AppInteractionMergeRequested event = capturedMergeEvent();
assertThat(event.userId()).isEqualTo(1001L);
assertThat(event.deviceId()).isEqualTo("device-9");
} }
@Test @Test
@@ -319,7 +373,7 @@ class AppAuthServiceTest {
given(googleVerifier.verify(anyString())) given(googleVerifier.verify(anyString()))
.willReturn(new GoogleUser("sub-1", "", "Alice", "")); .willReturn(new GoogleUser("sub-1", "", "Alice", ""));
assertThatThrownBy(() -> authService.googleLogin("google-id-token")) assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9", "203.0.113.9"))
.isInstanceOf(ServiceException.class) .isInstanceOf(ServiceException.class)
.hasMessage("Google 账号未返回邮箱,无法登录"); .hasMessage("Google 账号未返回邮箱,无法登录");
} }
@@ -353,6 +407,13 @@ class AppAuthServiceTest {
return saved; return saved;
} }
private AppInteractionMergeRequested capturedMergeEvent() {
ArgumentCaptor<AppInteractionMergeRequested> event =
ArgumentCaptor.forClass(AppInteractionMergeRequested.class);
verify(eventPublisher).publishEvent(event.capture());
return event.getValue();
}
private void stubLogin(AppUserCredential credential, AppUser user) { private void stubLogin(AppUserCredential credential, AppUser user) {
given(credentialMapper.selectOne(any())).willReturn(credential); given(credentialMapper.selectOne(any())).willReturn(credential);
given(userMapper.selectById(any())).willReturn(user); given(userMapper.selectById(any())).willReturn(user);
@@ -371,7 +432,7 @@ class AppAuthServiceTest {
AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher); AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher);
return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper, return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService, deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService,
googleVerifier); googleVerifier, eventPublisher, ipRegionService);
} }
private void setRegisterLimits(int perIp, int perDevice) { private void setRegisterLimits(int perIp, int perDevice) {
@@ -7,7 +7,10 @@ import com.fruitshorts.common.pojo.CursorResult;
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.service.BannerService; import com.fruitshorts.content.service.BannerService;
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;
@@ -45,12 +48,15 @@ class AppCatalogServiceTest {
episodeService = mock(EpisodeService.class); episodeService = mock(EpisodeService.class);
BannerService bannerService = mock(BannerService.class); BannerService bannerService = mock(BannerService.class);
dramaCategoryService = mock(DramaCategoryService.class); dramaCategoryService = mock(DramaCategoryService.class);
DramaClassificationService dramaClassificationService = mock(DramaClassificationService.class);
DramaPlaylistCategoryService dramaPlaylistCategoryService = mock(DramaPlaylistCategoryService.class);
PlaybackSigner playbackSigner = mock(PlaybackSigner.class); PlaybackSigner playbackSigner = mock(PlaybackSigner.class);
thumbnailUrlResolver = mock(ThumbnailUrlResolver.class); thumbnailUrlResolver = mock(ThumbnailUrlResolver.class);
given(thumbnailUrlResolver.resolveAll(any())).willReturn(Map.of()); given(thumbnailUrlResolver.resolveAll(any())).willReturn(Map.of());
commentService = mock(CommentService.class); commentService = mock(CommentService.class);
catalogService = new AppCatalogService(dramaService, episodeService, bannerService, catalogService = new AppCatalogService(dramaService, episodeService, bannerService,
dramaCategoryService, playbackSigner, commentService, thumbnailUrlResolver); dramaCategoryService, mock(ContentTagService.class), dramaClassificationService, dramaPlaylistCategoryService,
playbackSigner, commentService, thumbnailUrlResolver);
} }
@Test @Test
@@ -0,0 +1,67 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
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 org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.verify;
class AppEpisodeStatsServiceTest {
@Test
void should_batch_single_episode_stats_without_ticket_side_effects() {
EpisodeService episodeService = mock(EpisodeService.class);
DramaService dramaService = mock(DramaService.class);
CommentService commentService = mock(CommentService.class);
LikeService likeService = mock(LikeService.class);
FavoriteService favoriteService = mock(FavoriteService.class);
DramaEpisode episode = new DramaEpisode();
episode.setId(11L);
episode.setDramaId(7L);
episode.setLikeCount(88L);
Drama drama = new Drama();
drama.setId(7L);
drama.setFavoriteCount(1800L);
given(episodeService.listPublishedByIds(List.of(11L))).willReturn(List.of(episode));
given(dramaService.listPublishedByIds(List.of(7L))).willReturn(List.of(drama));
given(commentService.countByEpisodes(List.of(11L))).willReturn(Map.of(11L, 8L));
given(likeService.likedTargetIds(
100L, "device-1", LikeService.TYPE_EPISODE, List.of(11L)))
.willReturn(Set.of(11L));
given(favoriteService.favoriteDramaIds(100L, "device-1", List.of(7L)))
.willReturn(Set.of());
AppEpisodeStatsService service = new AppEpisodeStatsService(
episodeService, dramaService, commentService, likeService, favoriteService);
AppEpisodeStatsVO result = service.get(11L, 100L, "device-1");
assertThat(result.getEpisodeId()).isEqualTo(11L);
assertThat(result.getDramaId()).isEqualTo(7L);
assertThat(result.getLikeCount()).isEqualTo(88L);
assertThat(result.getCommentCount()).isEqualTo(8L);
assertThat(result.getFavoriteCount()).isEqualTo(1800L);
assertThat(result.getLiked()).isTrue();
assertThat(result.getFavorited()).isFalse();
verify(episodeService).listPublishedByIds(List.of(11L));
verify(commentService).countByEpisodes(List.of(11L));
verify(likeService).likedTargetIds(
100L, "device-1", LikeService.TYPE_EPISODE, List.of(11L));
verify(favoriteService).favoriteDramaIds(100L, "device-1", List.of(7L));
}
}
@@ -0,0 +1,42 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.user.enums.CountryProfile;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** 国家解析与映射:IP 库文本 → ISO-2,再据此选语言/时区/币种。 */
class CountryProfileTest {
@Test
void should_map_ip_region_text_to_iso_code() {
assertThat(CountryProfile.fromIpRegion("中国|0|广东省|深圳市|电信")).isEqualTo("CN");
assertThat(CountryProfile.fromIpRegion("中国|0|台湾省|0|中华电信")).isEqualTo("TW");
assertThat(CountryProfile.fromIpRegion("中国|0|香港|0|0")).isEqualTo("HK");
assertThat(CountryProfile.fromIpRegion("中国|0|澳门|0|澳门电讯")).isEqualTo("MO");
assertThat(CountryProfile.fromIpRegion("美国|0|0|0|Level3")).isEqualTo("US");
assertThat(CountryProfile.fromIpRegion("印度尼西亚|0|大雅加达|雅加达|0")).isEqualTo("ID");
}
@Test
void should_return_empty_for_private_ip_and_unknown_country() {
assertThat(CountryProfile.fromIpRegion("0|0|0|内网IP|内网IP")).isEmpty();
assertThat(CountryProfile.fromIpRegion("")).isEmpty();
// 未收录的国家交给上层回退到客户端区域
assertThat(CountryProfile.fromIpRegion("津巴布韦|0|0|0|0")).isEmpty();
}
@Test
void should_normalize_client_region_and_fallback_to_default() {
assertThat(CountryProfile.normalizeClientCode(" id ")).isEqualTo("ID");
assertThat(CountryProfile.normalizeClientCode("us")).isEqualTo("US");
assertThat(CountryProfile.normalizeClientCode("XX")).isEmpty();
assertThat(CountryProfile.normalizeClientCode("")).isEmpty();
assertThat(CountryProfile.of("US").currency()).isEqualTo("USD");
assertThat(CountryProfile.of("US").language()).isEqualTo("en-US");
assertThat(CountryProfile.of("").code()).isEqualTo("ID");
assertThat(CountryProfile.of("").currency()).isEqualTo("IDR");
}
}
@@ -43,6 +43,8 @@ class DramaServiceFavoriteCountTest {
mock(DramaEpisodeMapper.class), mock(DramaEpisodeMapper.class),
mock(DramaReviewRecordMapper.class), mock(DramaReviewRecordMapper.class),
mock(DramaCategoryService.class), mock(DramaCategoryService.class),
mock(com.fruitshorts.content.dal.mapper.ContentTagMapper.class),
mock(com.fruitshorts.content.service.ContentTagService.class),
mock(EpisodePriceSync.class)); mock(EpisodePriceSync.class));
given(dramaMapper.update(isNull(), any())).willReturn(1); given(dramaMapper.update(isNull(), any())).willReturn(1);
ArgumentCaptor<Wrapper<Drama>> captor = ArgumentCaptor.forClass(Wrapper.class); ArgumentCaptor<Wrapper<Drama>> captor = ArgumentCaptor.forClass(Wrapper.class);
@@ -47,6 +47,8 @@ class DramaServiceFeedTest {
mock(DramaEpisodeMapper.class), mock(DramaEpisodeMapper.class),
mock(DramaReviewRecordMapper.class), mock(DramaReviewRecordMapper.class),
mock(DramaCategoryService.class), mock(DramaCategoryService.class),
mock(com.fruitshorts.content.dal.mapper.ContentTagMapper.class),
mock(com.fruitshorts.content.service.ContentTagService.class),
mock(EpisodePriceSync.class)); mock(EpisodePriceSync.class));
} }
@@ -48,6 +48,8 @@ class DramaServiceK88Test {
mock(DramaEpisodeMapper.class), mock(DramaEpisodeMapper.class),
mock(DramaReviewRecordMapper.class), mock(DramaReviewRecordMapper.class),
mock(DramaCategoryService.class), mock(DramaCategoryService.class),
mock(com.fruitshorts.content.dal.mapper.ContentTagMapper.class),
mock(com.fruitshorts.content.service.ContentTagService.class),
mock(EpisodePriceSync.class)); mock(EpisodePriceSync.class));
} }
@@ -56,6 +56,8 @@ class DramaServiceMultiTagTest {
mock(DramaEpisodeMapper.class), mock(DramaEpisodeMapper.class),
mock(DramaReviewRecordMapper.class), mock(DramaReviewRecordMapper.class),
categoryService, categoryService,
mock(com.fruitshorts.content.dal.mapper.ContentTagMapper.class),
mock(com.fruitshorts.content.service.ContentTagService.class),
mock(EpisodePriceSync.class)); mock(EpisodePriceSync.class));
} }
@@ -0,0 +1,41 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.interaction.service.LikeService;
import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.service.WatchProgressService;
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class InteractionAccountMergeServiceTest {
@Test
void should_merge_all_device_interactions_and_watch_data() {
LikeService likeService = mock(LikeService.class);
FavoriteService favoriteService = mock(FavoriteService.class);
CommentService commentService = mock(CommentService.class);
WatchProgressService watchService = mock(WatchProgressService.class);
given(likeService.mergeDeviceIntoUser(9L, "device-a"))
.willReturn(new LikeService.MergeResult(1, 0));
given(favoriteService.mergeDeviceIntoUser(9L, "device-a"))
.willReturn(new FavoriteService.MergeResult(1, 0));
given(commentService.mergeDeviceIntoUser(9L, "device-a"))
.willReturn(new CommentService.MergeResult(1, 0));
given(watchService.mergeDeviceIntoUser(9L, "device-a"))
.willReturn(new WatchProgressService.MergeResult(2, 1, 3, 2));
InteractionAccountMergeService service = new InteractionAccountMergeService(
likeService, favoriteService, commentService, watchService);
service.merge(9L, "device-a");
verify(likeService).mergeDeviceIntoUser(9L, "device-a");
verify(favoriteService).mergeDeviceIntoUser(9L, "device-a");
verify(commentService).mergeDeviceIntoUser(9L, "device-a");
verify(watchService).mergeDeviceIntoUser(9L, "device-a");
}
}
@@ -0,0 +1,49 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.user.service.IpRegionService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* IpRegionService 集成测试:真实 xdb 文件 + 真实 resolve。
*
* <p>xdb 在 fruitshorts-module-user 的 resources/ip2region/ip2region.xdb 下(11MB),
* 打包后会进 app-api 的 classpath。这个测试验证 Service 层调 ip2region 库的行为——
* 合法公网 IP → ISO-2 国家码,内网/保留地址/空 → 空串。
*/
class IpRegionServiceTest {
private IpRegionService service;
@BeforeEach
void setUp() {
service = new IpRegionService();
}
@Test
void should_resolve_known_public_ips() {
assertThat(service.resolveCountry("8.8.8.8")).isEqualTo("US");
assertThat(service.resolveCountry("114.114.114.114")).isEqualTo("CN");
}
@Test
void should_return_empty_for_private_loopback_and_reserved() {
assertThat(service.resolveCountry("127.0.0.1")).isEmpty();
assertThat(service.resolveCountry("0.0.0.0")).isEmpty();
assertThat(service.resolveCountry("10.0.0.1")).isEmpty();
assertThat(service.resolveCountry("192.168.1.1")).isEmpty();
assertThat(service.resolveCountry("172.16.0.1")).isEmpty();
assertThat(service.resolveCountry("169.254.1.1")).isEmpty();
}
@Test
void should_return_empty_for_invalid_inputs() {
assertThat(service.resolveCountry("")).isEmpty();
assertThat(service.resolveCountry(null)).isEmpty();
assertThat(service.resolveCountry("not-an-ip")).isEmpty();
assertThat(service.resolveCountry("999.999.999.999")).isEmpty();
}
}
@@ -1,6 +1,8 @@
// Author: fruit.com.cn // Author: fruit.com.cn
package com.fruitshorts.app.service; package com.fruitshorts.app.service;
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.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
@@ -20,6 +22,7 @@ import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@@ -112,6 +115,30 @@ class PlaybackServiceTest {
verify(ticketMapper, never()).insert(any(PlaybackTicket.class)); verify(ticketMapper, never()).insert(any(PlaybackTicket.class));
} }
@Test
void should_reject_locked_episode_ticket_for_anonymous_device() {
given(episodeService.getPublished(12L)).willReturn(episode(12L, 0, 60, "/files/episode/2.mp4"));
assertThatThrownBy(() ->
playbackService.play(null, 12L, "device-9", "203.0.113.8"))
.isInstanceOf(ServiceException.class)
.extracting(error -> ((ServiceException) error).getCode())
.isEqualTo(ErrorCode.UNAUTHORIZED.getCode());
verify(signer, never()).sign(anyString());
}
@Test
void should_reject_locked_episode_ticket_before_no_media_for_anonymous_device() {
given(episodeService.getPublished(17L)).willReturn(episode(17L, 0, 60, ""));
assertThatThrownBy(() ->
playbackService.play(null, 17L, "device-9", "203.0.113.8"))
.isInstanceOf(ServiceException.class)
.extracting(error -> ((ServiceException) error).getCode())
.isEqualTo(ErrorCode.UNAUTHORIZED.getCode());
verify(signer, never()).sign(anyString());
}
@Test @Test
void should_return_entitled_access_when_entitlement_port_confirms_unlock() { void should_return_entitled_access_when_entitlement_port_confirms_unlock() {
given(episodeService.getPublished(13L)).willReturn(episode(13L, 0, 60, "/files/episode/3.mp4")); given(episodeService.getPublished(13L)).willReturn(episode(13L, 0, 60, "/files/episode/3.mp4"));
@@ -2,6 +2,7 @@
package com.fruitshorts.app.support; package com.fruitshorts.app.support;
import com.fruitshorts.framework.log.AccessDeniedRecorder; import com.fruitshorts.framework.log.AccessDeniedRecorder;
import com.fruitshorts.framework.web.WebUtils;
import com.fruitshorts.framework.web.JacksonLongToStringConfig; import com.fruitshorts.framework.web.JacksonLongToStringConfig;
import com.fruitshorts.framework.web.GlobalExceptionHandler; import com.fruitshorts.framework.web.GlobalExceptionHandler;
import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializationFeature;
@@ -30,7 +31,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 字符串输出而不是数组,
@@ -0,0 +1,133 @@
// Author: fruit.com.cn
package com.fruitshorts.interaction.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fruitshorts.common.interaction.InteractionIdentity;
import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.interaction.config.InteractionProperties;
import com.fruitshorts.interaction.dal.entity.ContentComment;
import com.fruitshorts.interaction.dal.mapper.ContentAuditRecordMapper;
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
import com.fruitshorts.interaction.vo.CommentPublishReqVO;
import com.fruitshorts.interaction.vo.CommentRespVO;
import com.fruitshorts.user.dal.mapper.AppUserMapper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class AnonymousCommentServiceTest {
private ContentCommentMapper commentMapper;
private SensitiveWordService sensitiveWordService;
private CommentService commentService;
@BeforeAll
static void initTableInfo() {
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
ContentComment.class);
}
@BeforeEach
void setUp() {
commentMapper = mock(ContentCommentMapper.class);
sensitiveWordService = mock(SensitiveWordService.class);
AuditRecorder auditRecorder = mock(AuditRecorder.class);
commentService = new CommentService(
commentMapper,
mock(ContentLikeMapper.class),
mock(ContentAuditRecordMapper.class),
mock(AppUserMapper.class),
mock(DramaService.class),
mock(EpisodeService.class),
sensitiveWordService,
auditRecorder,
new InteractionProperties());
}
@Test
void should_publish_anonymous_comment_with_guest_name_and_device_owner() {
given(commentMapper.selectCount(any())).willReturn(0L);
given(commentMapper.insert(any(ContentComment.class))).willReturn(1);
given(sensitiveWordService.check("hello")).willReturn(
SensitiveWordCheck.pass("hello"));
CommentRespVO result = commentService.publish(
new InteractionIdentity(null, "device-a"),
request("hello"),
"127.0.0.1");
ArgumentCaptor<ContentComment> captor =
ArgumentCaptor.forClass(ContentComment.class);
verify(commentMapper).insert(captor.capture());
assertThat(captor.getValue().getUserId()).isNull();
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
assertThat(result.getNickname()).isEqualTo("游客");
assertThat(result.getMine()).isTrue();
}
@Test
void should_reject_duplicate_anonymous_content_within_one_minute() {
given(commentMapper.selectCount(any())).willReturn(0L, 1L);
given(sensitiveWordService.check("hello")).willReturn(
SensitiveWordCheck.pass("hello"));
assertThatThrownBy(() -> commentService.publish(
new InteractionIdentity(null, "device-a"),
request("hello"),
"127.0.0.1"))
.hasMessageContaining("重复");
}
@Test
void should_merge_device_comments_and_remove_duplicate() {
ContentComment duplicate = comment(1L, "same");
ContentComment unique = comment(2L, "new");
given(commentMapper.selectList(any())).willReturn(List.of(duplicate, unique));
given(commentMapper.selectOne(any())).willReturn(comment(3L, "same"), null);
given(commentMapper.physicalDeleteById(1L)).willReturn(1);
CommentService.MergeResult result =
commentService.mergeDeviceIntoUser(9L, "device-a");
assertThat(result.migrated()).isEqualTo(1);
assertThat(result.duplicates()).isEqualTo(1);
verify(commentMapper).physicalDeleteById(1L);
verify(commentMapper).updateById(unique);
assertThat(unique.getUserId()).isEqualTo(9L);
}
private CommentPublishReqVO request(String content) {
CommentPublishReqVO req = new CommentPublishReqVO();
req.setDramaId(7L);
req.setContent(content);
return req;
}
private ContentComment comment(Long id, String content) {
ContentComment comment = new ContentComment();
comment.setId(id);
comment.setDramaId(7L);
comment.setEpisodeId(0L);
comment.setParentId(0L);
comment.setContent(content);
comment.setStatus(CommentService.STATUS_PUBLISHED);
comment.setDeviceId("device-a");
return comment;
}
}
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fruitshorts.common.exception.ErrorCode; import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException; import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.interaction.InteractionIdentity;
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.service.DramaService; import com.fruitshorts.content.service.DramaService;
@@ -19,6 +20,9 @@ import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
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 java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -95,6 +99,44 @@ class LikeServiceEpisodeTest {
verify(likeMapper, never()).insert(any(ContentLike.class)); verify(likeMapper, never()).insert(any(ContentLike.class));
} }
@Test
void should_store_anonymous_episode_like_by_device() {
DramaEpisode published = episode(1L);
given(episodeService.getPublished(11L)).willReturn(published);
given(dramaService.getPublished(5L)).willReturn(new Drama());
given(likeMapper.selectOne(any())).willReturn(null);
given(episodeService.getExisting(11L)).willReturn(published);
likeService.toggle(new InteractionIdentity(null, "device-a"), request(11L));
ArgumentCaptor<ContentLike> captor = ArgumentCaptor.forClass(ContentLike.class);
verify(likeMapper).insert(captor.capture());
assertThat(captor.getValue().getUserId()).isNull();
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
}
@Test
void should_merge_device_likes_and_decrement_duplicate_count_once() {
DramaEpisode published = episode(2L);
ContentLike duplicate = like(1L, LikeService.TYPE_EPISODE, 11L);
ContentLike unique = like(2L, LikeService.TYPE_EPISODE, 12L);
given(likeMapper.selectList(any())).willReturn(List.of(duplicate, unique));
given(likeMapper.selectOne(any())).willReturn(
like(3L, LikeService.TYPE_EPISODE, 11L),
null);
given(likeMapper.physicalDeleteById(1L)).willReturn(1);
given(episodeService.getExisting(11L)).willReturn(published);
given(episodeService.getExisting(12L)).willReturn(published);
LikeService.MergeResult result = likeService.mergeDeviceIntoUser(9L, "device-a");
assertThat(result.migrated()).isEqualTo(1);
assertThat(result.duplicates()).isEqualTo(1);
verify(episodeService).adjustLikeCount(11L, -1);
verify(likeMapper).updateById(unique);
assertThat(unique.getUserId()).isEqualTo(9L);
}
private DramaEpisode episode(Long likeCount) { private DramaEpisode episode(Long likeCount) {
DramaEpisode episode = new DramaEpisode(); DramaEpisode episode = new DramaEpisode();
episode.setId(11L); episode.setId(11L);
@@ -109,4 +151,12 @@ class LikeServiceEpisodeTest {
req.setTargetId(episodeId); req.setTargetId(episodeId);
return req; return req;
} }
private ContentLike like(Long id, String type, Long targetId) {
ContentLike like = new ContentLike();
like.setId(id);
like.setTargetType(type);
like.setTargetId(targetId);
return like;
}
} }
@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.interaction.InteractionIdentity;
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.playback.dal.entity.UserFavorite; import com.fruitshorts.playback.dal.entity.UserFavorite;
@@ -58,6 +59,38 @@ class FavoriteServiceTest {
verify(dramaService).adjustFavoriteCount(7L, 1); verify(dramaService).adjustFavoriteCount(7L, 1);
} }
@Test
void should_store_anonymous_favorite_by_device() {
given(favoriteMapper.selectOne(any())).willReturn(null);
given(favoriteMapper.insert(any(UserFavorite.class))).willReturn(1);
favoriteService.toggle(new InteractionIdentity(null, "device-a"), 7L);
ArgumentCaptor<UserFavorite> captor = ArgumentCaptor.forClass(UserFavorite.class);
verify(favoriteMapper).insert(captor.capture());
assertThat(captor.getValue().getUserId()).isNull();
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
verify(dramaService).adjustFavoriteCount(7L, 1);
}
@Test
void should_merge_device_favorites_and_decrement_duplicate_count_once() {
UserFavorite duplicate = favorite(7L);
UserFavorite unique = favorite(8L);
given(favoriteMapper.selectList(any())).willReturn(List.of(duplicate, unique));
given(favoriteMapper.selectOne(any())).willReturn(favorite(9L), null);
given(favoriteMapper.physicalDeleteById(duplicate.getId())).willReturn(1);
FavoriteService.MergeResult result =
favoriteService.mergeDeviceIntoUser(1L, "device-a");
assertThat(result.migrated()).isEqualTo(1);
assertThat(result.duplicates()).isEqualTo(1);
verify(dramaService).adjustFavoriteCount(7L, -1);
verify(favoriteMapper).updateById(unique);
assertThat(unique.getUserId()).isEqualTo(1L);
}
@Test @Test
void should_decrement_favorite_count_when_toggle_removes_relation() { void should_decrement_favorite_count_when_toggle_removes_relation() {
given(favoriteMapper.selectOne(any())).willReturn(new UserFavorite()); given(favoriteMapper.selectOne(any())).willReturn(new UserFavorite());
@@ -87,13 +120,28 @@ class FavoriteServiceTest {
given(favoriteMapper.physicalDelete(1L, 8L)).willReturn(0); given(favoriteMapper.physicalDelete(1L, 8L)).willReturn(0);
given(favoriteMapper.physicalDelete(1L, 9L)).willReturn(1); given(favoriteMapper.physicalDelete(1L, 9L)).willReturn(1);
favoriteService.removeBatch(1L, Arrays.asList(7L, 8L, 9L, null)); int deleted =
favoriteService.removeBatch(1L, Arrays.asList(7L, 8L, 9L, 7L, null));
assertThat(deleted).isEqualTo(2);
verify(dramaService).adjustFavoriteCount(7L, -1); verify(dramaService).adjustFavoriteCount(7L, -1);
verify(dramaService, never()).adjustFavoriteCount(8L, -1); verify(dramaService, never()).adjustFavoriteCount(8L, -1);
verify(dramaService).adjustFavoriteCount(9L, -1); verify(dramaService).adjustFavoriteCount(9L, -1);
} }
@Test
void should_remove_anonymous_batch_by_device_and_return_deleted_count() {
given(favoriteMapper.physicalDeleteDevice("device-a", 7L)).willReturn(1);
given(favoriteMapper.physicalDeleteDevice("device-a", 8L)).willReturn(1);
int deleted = favoriteService.removeBatch(
new InteractionIdentity(null, "device-a"), List.of(7L, 8L));
assertThat(deleted).isEqualTo(2);
verify(dramaService).adjustFavoriteCount(7L, -1);
verify(dramaService).adjustFavoriteCount(8L, -1);
}
@Test @Test
void should_use_database_page_and_keep_favorite_order_when_listing() { void should_use_database_page_and_keep_favorite_order_when_listing() {
UserFavorite first = favorite(51L); UserFavorite first = favorite(51L);
@@ -124,6 +172,24 @@ class FavoriteServiceTest {
verify(dramaService).listPublishedByIds(List.of(51L, 52L)); verify(dramaService).listPublishedByIds(List.of(51L, 52L));
} }
@Test
void should_page_anonymous_favorites_by_device() {
Page<UserFavorite> databasePage = new Page<>(1, 20, 0);
databasePage.setRecords(List.of());
given(favoriteMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
favoriteService.page(
new InteractionIdentity(null, "device-a"), 1, 20);
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<UserFavorite>> wrapperCaptor =
ArgumentCaptor.forClass(Wrapper.class);
verify(favoriteMapper).selectPage(any(Page.class), wrapperCaptor.capture());
assertThat(wrapperCaptor.getValue().getSqlSegment())
.contains("user_id IS NULL")
.contains("device_id");
}
private UserFavorite favorite(Long dramaId) { private UserFavorite favorite(Long dramaId) {
UserFavorite favorite = new UserFavorite(); UserFavorite favorite = new UserFavorite();
favorite.setDramaId(dramaId); favorite.setDramaId(dramaId);
@@ -7,22 +7,26 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.interaction.InteractionIdentity;
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.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.playback.dal.entity.WatchProgress; import com.fruitshorts.playback.dal.entity.WatchProgress;
import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper; import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
import com.fruitshorts.playback.dal.mapper.WatchProgressMapper; import com.fruitshorts.playback.dal.mapper.WatchProgressMapper;
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 org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.annotations.Select;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
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.mockito.ArgumentCaptor;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.lang.reflect.Method;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@@ -43,6 +47,7 @@ class WatchProgressServiceTest {
} }
private WatchProgressMapper progressMapper; private WatchProgressMapper progressMapper;
private WatchHistoryMapper historyMapper;
private DramaService dramaService; private DramaService dramaService;
private EpisodeService episodeService; private EpisodeService episodeService;
private WatchProgressService progressService; private WatchProgressService progressService;
@@ -50,11 +55,12 @@ class WatchProgressServiceTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
progressMapper = mock(WatchProgressMapper.class); progressMapper = mock(WatchProgressMapper.class);
historyMapper = mock(WatchHistoryMapper.class);
dramaService = mock(DramaService.class); dramaService = mock(DramaService.class);
episodeService = mock(EpisodeService.class); episodeService = mock(EpisodeService.class);
progressService = new WatchProgressService( progressService = new WatchProgressService(
progressMapper, progressMapper,
mock(WatchHistoryMapper.class), historyMapper,
dramaService, dramaService,
episodeService); episodeService);
} }
@@ -120,7 +126,7 @@ class WatchProgressServiceTest {
hidden.setId(9L); hidden.setId(9L);
hidden.setUserId(7L); hidden.setUserId(7L);
hidden.setDeleted(1); hidden.setDeleted(1);
given(progressMapper.selectAny(7L, 5L)).willReturn(hidden); given(progressMapper.selectAnyForIdentity(7L, "", 5L)).willReturn(hidden);
given(progressMapper.selectById(9L)).willReturn(hidden); given(progressMapper.selectById(9L)).willReturn(hidden);
ProgressSaveReqVO req = new ProgressSaveReqVO(); ProgressSaveReqVO req = new ProgressSaveReqVO();
req.setEpisodeId(88L); req.setEpisodeId(88L);
@@ -134,6 +140,185 @@ class WatchProgressServiceTest {
assertThat(hidden.getDeleted()).isZero(); assertThat(hidden.getDeleted()).isZero();
} }
@Test
void should_save_and_read_anonymous_progress_by_device() {
DramaEpisode episode = episode(88L, 1);
episode.setDramaId(5L);
given(episodeService.getPublished(88L)).willReturn(episode);
given(dramaService.getPublished(5L)).willReturn(drama(5L, "剧名", 10));
given(progressMapper.selectAnyForIdentity(null, "device-a", 5L))
.willReturn(null);
given(progressMapper.insert(any(WatchProgress.class))).willAnswer(invocation -> {
WatchProgress saved = invocation.getArgument(0);
saved.setId(99L);
return 1;
});
given(progressMapper.selectById(99L)).willAnswer(invocation -> {
WatchProgress saved = new WatchProgress();
saved.setId(99L);
saved.setDramaId(5L);
saved.setEpisodeId(88L);
saved.setPositionMs(12_000L);
saved.setDurationMs(60_000L);
saved.setPlayCount(1);
saved.setDeviceId("device-a");
return saved;
});
ProgressSaveReqVO req = new ProgressSaveReqVO();
req.setEpisodeId(88L);
req.setPositionMs(12_000L);
req.setDurationMs(60_000L);
progressService.save(new InteractionIdentity(null, "device-a"), req);
ArgumentCaptor<WatchProgress> progressCaptor =
ArgumentCaptor.forClass(WatchProgress.class);
verify(progressMapper).insert(progressCaptor.capture());
assertThat(progressCaptor.getValue().getUserId()).isNull();
assertThat(progressCaptor.getValue().getDeviceId()).isEqualTo("device-a");
ArgumentCaptor<WatchHistory> historyCaptor =
ArgumentCaptor.forClass(WatchHistory.class);
verify(historyMapper).insert(historyCaptor.capture());
assertThat(historyCaptor.getValue().getUserId()).isNull();
assertThat(historyCaptor.getValue().getDeviceId()).isEqualTo("device-a");
WatchProgress saved = progressCaptor.getValue();
saved.setUpdatedAt(LocalDateTime.of(2026, 10, 27, 9, 0));
Page<WatchProgress> databasePage = new Page<>(1, 20, 1);
databasePage.setRecords(List.of(saved));
given(progressMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
given(dramaService.listByIds(List.of(5L)))
.willReturn(List.of(drama(5L, "匿名观看", 10)));
given(episodeService.listByIds(List.of(88L)))
.willReturn(List.of(episode));
PageResult<ProgressRespVO> recent = progressService.recentPage(
new InteractionIdentity(null, "device-a"), 1, 20);
assertThat(recent.getList()).hasSize(1);
assertThat(recent.getList().get(0).getEpisodeId()).isEqualTo(88L);
}
@Test
void should_read_anonymous_progress_by_device() {
WatchProgress progress = progress(5L, 88L);
progress.setUserId(null);
progress.setDeviceId("device-a");
given(progressMapper.selectOne(any())).willReturn(progress);
ProgressRespVO result = progressService.ofDrama(
new InteractionIdentity(null, "device-a"), 5L);
assertThat(result.getEpisodeId()).isEqualTo(88L);
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<WatchProgress>> wrapperCaptor =
ArgumentCaptor.forClass(Wrapper.class);
verify(progressMapper).selectOne(wrapperCaptor.capture());
assertThat(wrapperCaptor.getValue().getSqlSegment())
.contains("user_id IS NULL")
.contains("device_id");
}
@Test
void should_read_logged_user_progress() {
WatchProgress progress = progress(5L, 88L);
progress.setUserId(9L);
given(progressMapper.selectOne(any())).willReturn(progress);
ProgressRespVO result = progressService.ofDrama(
new InteractionIdentity(9L, ""), 5L);
assertThat(result.getEpisodeId()).isEqualTo(88L);
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<WatchProgress>> wrapperCaptor =
ArgumentCaptor.forClass(Wrapper.class);
verify(progressMapper).selectOne(wrapperCaptor.capture());
assertThat(wrapperCaptor.getValue().getSqlSegment())
.contains("user_id")
.doesNotContain("user_id IS NULL");
}
@Test
void should_declare_jdbc_type_for_nullable_identity_sql() throws Exception {
Method method = WatchProgressMapper.class.getMethod(
"selectAnyForIdentity", Long.class, String.class, Long.class);
Select select = method.getAnnotation(Select.class);
String sql = String.join("\n", select.value());
assertThat(sql)
.contains("#{userId,jdbcType=BIGINT} IS NOT NULL")
.contains("#{userId,jdbcType=BIGINT} IS NULL")
.doesNotContain("#{userId} ");
}
@Test
void should_merge_watch_data_and_keep_more_advanced_progress() {
DramaEpisode episode = episode(88L, 2);
episode.setDramaId(5L);
given(episodeService.listByIds(List.of(88L))).willReturn(List.of(episode));
WatchProgress deviceProgress = progress(5L, 88L);
deviceProgress.setId(1L);
deviceProgress.setPositionMs(90_000L);
deviceProgress.setPlayCount(3);
given(progressMapper.selectList(any())).willReturn(List.of(deviceProgress));
WatchProgress accountProgress = progress(5L, 88L);
accountProgress.setId(2L);
accountProgress.setUserId(9L);
accountProgress.setPositionMs(60_000L);
accountProgress.setPlayCount(2);
given(progressMapper.selectAnyForIdentity(9L, "", 5L))
.willReturn(accountProgress);
WatchHistory deviceHistory = history(5L, 88L, 90_000L);
deviceHistory.setId(3L);
given(historyMapper.selectList(any())).willReturn(List.of(deviceHistory));
WatchHistory accountHistory = history(5L, 88L, 60_000L);
accountHistory.setId(4L);
accountHistory.setUserId(9L);
given(historyMapper.selectOne(any())).willReturn(accountHistory);
WatchProgressService.MergeResult result =
progressService.mergeDeviceIntoUser(9L, "device-a");
assertThat(result.progressMigrated()).isEqualTo(1);
assertThat(result.progressIgnored()).isZero();
assertThat(result.historyMigrated()).isEqualTo(1);
assertThat(result.historyIgnored()).isZero();
assertThat(accountProgress.getPositionMs()).isEqualTo(90_000L);
assertThat(accountProgress.getPlayCount()).isEqualTo(3);
verify(progressMapper).updateAny(accountProgress);
verify(progressMapper).deleteById(1L);
verify(historyMapper).updateById(accountHistory);
verify(historyMapper).deleteById(3L);
}
@Test
void should_ignore_device_progress_when_account_progress_is_ahead() {
DramaEpisode episode = episode(88L, 2);
episode.setDramaId(5L);
given(episodeService.listByIds(List.of(88L))).willReturn(List.of(episode));
WatchProgress deviceProgress = progress(5L, 88L);
deviceProgress.setId(1L);
deviceProgress.setPositionMs(50_000L);
given(progressMapper.selectList(any())).willReturn(List.of(deviceProgress));
WatchProgress accountProgress = progress(5L, 88L);
accountProgress.setId(2L);
accountProgress.setUserId(9L);
accountProgress.setPositionMs(70_000L);
given(progressMapper.selectAnyForIdentity(9L, "", 5L))
.willReturn(accountProgress);
WatchProgressService.MergeResult result =
progressService.mergeDeviceIntoUser(9L, "device-a");
assertThat(result.progressMigrated()).isZero();
assertThat(result.progressIgnored()).isEqualTo(1);
verify(progressMapper, never()).updateAny(any(WatchProgress.class));
verify(progressMapper).deleteById(1L);
}
private Drama drama(Long id, String title, int totalEpisodes) { private Drama drama(Long id, String title, int totalEpisodes) {
Drama drama = new Drama(); Drama drama = new Drama();
drama.setId(id); drama.setId(id);
@@ -149,4 +334,15 @@ class WatchProgressServiceTest {
episode.setEpNo(epNo); episode.setEpNo(epNo);
return episode; return episode;
} }
private WatchHistory history(Long dramaId, Long episodeId, long positionMs) {
WatchHistory history = new WatchHistory();
history.setDramaId(dramaId);
history.setEpisodeId(episodeId);
history.setPositionMs(positionMs);
history.setDurationMs(120_000L);
history.setDeviceId("device-a");
history.setWatchedAt(LocalDateTime.of(2026, 10, 27, 9, 0));
return history;
}
} }
@@ -37,7 +37,9 @@ public enum ErrorCode {
*/ */
CREATOR_NOT_BOUND(200004, "当前账号未绑定创作者主体"), CREATOR_NOT_BOUND(200004, "当前账号未绑定创作者主体"),
CREATOR_TARGET_REQUIRED(200005, "请先选择要代看的创作者"), CREATOR_TARGET_REQUIRED(200005, "请先选择要代看的创作者"),
CREATOR_IMPERSONATE_READONLY(200006, "代看模式下只读,不能修改创作者数据"); CREATOR_IMPERSONATE_READONLY(200006, "代看模式下只读,不能修改创作者数据"),
INTERACTION_IDENTITY_REQUIRED(200007, "缺少登录身份或设备标识,请重新登录");
private final int code; private final int code;
private final String message; private final String message;
@@ -0,0 +1,11 @@
// Author: fruit.com.cn
package com.fruitshorts.common.interaction;
/** 非付费互动的归属身份:登录用户优先,否则使用稳定设备号。 */
public record InteractionIdentity(Long userId, String deviceId) {
public boolean authenticated() {
return userId != null;
}
}
@@ -0,0 +1,33 @@
// Author: fruit.com.cn
package com.fruitshorts.framework.interaction;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.interaction.InteractionIdentity;
import org.springframework.stereotype.Component;
/** 点赞、收藏、评论共用的身份解析入口。 */
@Component
public class InteractionIdentityResolver {
public InteractionIdentity resolve(Long userId, String headerDeviceId, String bodyDeviceId) {
if (userId != null) {
return new InteractionIdentity(userId, "");
}
String deviceId = normalize(headerDeviceId);
if (deviceId.isEmpty()) {
deviceId = normalize(bodyDeviceId);
}
if (deviceId.isEmpty()) {
throw new ServiceException(
ErrorCode.INTERACTION_IDENTITY_REQUIRED,
ErrorCode.INTERACTION_IDENTITY_REQUIRED.getMessage());
}
return new InteractionIdentity(null, deviceId);
}
private String normalize(String value) {
return value == null ? "" : value.trim();
}
}
@@ -22,6 +22,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
public class AccessDeniedRecorder { public class AccessDeniedRecorder {
private final ObjectProvider<OperationLogSink> sinkProvider; private final ObjectProvider<OperationLogSink> sinkProvider;
private final ObjectProvider<WebUtils> webUtilsProvider;
public void record(HttpServletRequest request) { public void record(HttpServletRequest request) {
OperationLogSink sink = sinkProvider.getIfAvailable(); OperationLogSink sink = sinkProvider.getIfAvailable();
@@ -47,10 +48,16 @@ public class AccessDeniedRecorder {
.status("FAIL") .status("FAIL")
.errorMsg("无权限") .errorMsg("无权限")
.durationMs(0) .durationMs(0)
.ip(request == null ? "" : WebUtils.getClientIp(request)) .ip(request == null ? "" : clientIp(request))
.build()); .build());
} }
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
private String clientIp(HttpServletRequest request) {
WebUtils webUtils = webUtilsProvider.getIfAvailable();
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
}
/** 从当前线程取出请求,供全局异常处理使用。 */ /** 从当前线程取出请求,供全局异常处理使用。 */
public void recordCurrentRequest() { public void recordCurrentRequest() {
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) { if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
@@ -43,6 +43,7 @@ public class OperationLogAspect {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final ObjectProvider<OperationLogSink> sinkProvider; private final ObjectProvider<OperationLogSink> sinkProvider;
private final ObjectProvider<WebUtils> webUtilsProvider;
@Around("@annotation(operationLog)") @Around("@annotation(operationLog)")
public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable { public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
@@ -86,10 +87,16 @@ public class OperationLogAspect {
.status(error == null ? "SUCCESS" : "FAIL") .status(error == null ? "SUCCESS" : "FAIL")
.errorMsg(error == null ? "" : truncate(error.getMessage())) .errorMsg(error == null ? "" : truncate(error.getMessage()))
.durationMs(durationMs) .durationMs(durationMs)
.ip(request == null ? "" : WebUtils.getClientIp(request)) .ip(request == null ? "" : clientIp(request))
.build()); .build());
} }
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
private String clientIp(HttpServletRequest request) {
WebUtils webUtils = webUtilsProvider.getIfAvailable();
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
}
/** 把方法入参整理成 JSON,文件只记名称和大小。 */ /** 把方法入参整理成 JSON,文件只记名称和大小。 */
private String body(ProceedingJoinPoint point) { private String body(ProceedingJoinPoint point) {
Object[] args = point.getArgs(); Object[] args = point.getArgs();
@@ -62,6 +62,8 @@ public final class ImpersonationGuard {
public static String clientIp() { public static String clientIp() {
HttpServletRequest request = currentRequest(); HttpServletRequest request = currentRequest();
// 这里走静态 getClientIp——等价于 trusted-proxies 为空时的逻辑(只用 remoteAddr,不解析 XFF)。
// 这个类是纯静态工具(无 Spring 注入),且只在 Creator 代看场景用,安全影响低。
return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request); return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request);
} }
@@ -38,10 +38,14 @@ public class SecurityConfig {
"/app/discover/**", "/app/discover/**",
"/app/feed", "/app/feed",
"/app/categories/**", "/app/categories/**",
"/app/drama-categories",
"/app/tags",
"/app/playlists/**",
"/app/banners/**", "/app/banners/**",
"/app/dramas/**", "/app/dramas/**",
"/app/search", "/app/search",
"/app/episodes/*/play", "/app/episodes/*/play",
"/app/episodes/*/stats",
"/app/config/**", "/app/config/**",
/* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */ /* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */
"/app/config", "/app/config",
@@ -77,9 +81,21 @@ public class SecurityConfig {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(registry -> registry .authorizeHttpRequests(registry -> registry
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
/* 评论列表允许匿名浏览;发布/删除仍需登录(未列入白名单即需鉴权) */ /* 非付费互动允许设备身份;解锁、钱包与权益接口仍只允许登录用户。 */
.requestMatchers(HttpMethod.POST, "/app/likes/toggle").permitAll()
.requestMatchers(HttpMethod.POST, "/app/favorites/toggle").permitAll()
.requestMatchers(HttpMethod.POST, "/app/favorites/remove").permitAll()
.requestMatchers(HttpMethod.DELETE, "/app/favorites/*").permitAll()
.requestMatchers(HttpMethod.POST, "/app/comments").permitAll()
.requestMatchers(HttpMethod.DELETE, "/app/comments/*").permitAll()
.requestMatchers(HttpMethod.GET, "/app/comments").permitAll() .requestMatchers(HttpMethod.GET, "/app/comments").permitAll()
.requestMatchers(HttpMethod.GET, "/app/comments/count").permitAll() .requestMatchers(HttpMethod.GET, "/app/comments/count").permitAll()
.requestMatchers(HttpMethod.GET, "/app/favorites").permitAll()
.requestMatchers(HttpMethod.GET, "/app/watch/recent").permitAll()
.requestMatchers(HttpMethod.GET, "/app/watch/progress").permitAll()
.requestMatchers(HttpMethod.POST, "/app/watch/progress").permitAll()
.requestMatchers(HttpMethod.DELETE, "/app/watch/progress/*").permitAll()
.requestMatchers(HttpMethod.DELETE, "/app/watch/progress").permitAll()
.requestMatchers(PUBLIC_PATHS).permitAll() .requestMatchers(PUBLIC_PATHS).permitAll()
.anyRequest().authenticated()) .anyRequest().authenticated())
.exceptionHandling(handling -> handling .exceptionHandling(handling -> handling
@@ -3,25 +3,146 @@
package com.fruitshorts.framework.web; package com.fruitshorts.framework.web;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
public final class WebUtils { import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
/**
* 取真实客户端 IP。
*
* <p>安全策略:默认信任 {@link HttpServletRequest#getRemoteAddr()} 本身,只有当
* 它属于配置的可信代理 CIDR 时才解析 X-Forwarded-For / X-Real-IP 等头。
* 这样客户端伪造的 XFF 不会生效,只有经 Nginx / K8s ingress 等前置代理转发的请求
* 才能带上可信的 XFF 链。
*
* <p>生产建议:同时开启 Tomcat RemoteIpValve(prod profile 已配置),让
* {@code getRemoteAddr()} 在经过代理后直接就是客户端真实 IP。此时可信代理列表
* 配成空即可,Valve 已经帮我们做了 XFF 解析。
*/
@Slf4j
@Component
public class WebUtils {
private static final String UNKNOWN = "unknown"; private static final String UNKNOWN = "unknown";
private static final String[] PROXY_HEADERS = {"X-Forwarded-For", "X-Real-IP",
"Proxy-Client-IP", "WL-Proxy-Client-IP"};
private WebUtils() { /** 可信代理 CIDR 列表,逗号分隔;空表示永不解析 XFF,直接用 remoteAddr。 */
@Value("${fruitshorts.web.trusted-proxies:}")
private String trustedProxies = "";
/** 纯静态调用路径(不依赖 Spring),供测试或无 IoC 场景使用。 */
public static String getClientIp(HttpServletRequest request) {
return resolve(request, List.of());
} }
/** 取真实客户端 IP,兼容 Nginx 反向代理。 */ /** Spring 注入版:自动按配置解析 XFF。 */
public static String getClientIp(HttpServletRequest request) { public String clientIp(HttpServletRequest request) {
String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"}; List<String> cidrs = StringUtils.hasText(trustedProxies)
for (String header : headers) { ? Arrays.asList(trustedProxies.split(","))
: List.of();
return resolve(request, cidrs);
}
private static String resolve(HttpServletRequest request, List<String> trustedCidrs) {
String remoteAddr = request.getRemoteAddr();
if (isTrustedProxy(remoteAddr, trustedCidrs)) {
String fromHeader = readProxyHeader(request);
if (StringUtils.hasText(fromHeader)) {
return fromHeader;
}
}
return remoteAddr;
}
private static String readProxyHeader(HttpServletRequest request) {
for (String header : PROXY_HEADERS) {
String value = request.getHeader(header); String value = request.getHeader(header);
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) { if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
int comma = value.indexOf(','); // XFF 链格式:client, proxy1, proxy2 —— 最左侧是原始客户端 IP
return comma > 0 ? value.substring(0, comma).trim() : value.trim(); String[] parts = value.split(",");
return parts[0].trim();
} }
} }
return request.getRemoteAddr(); return "";
}
/**
* 判断 remoteAddr 是否属于可信代理。
*
* <p>CIDR 简化实现:只支持单个 IP 或 "/24" 这类前缀掩码,不支持复杂区间。
* 生产反代一般就是 127.0.0.1、10.0.0.0/8 这类,够用。
*/
static boolean isTrustedProxy(String remoteAddr, List<String> trustedCidrs) {
if (!StringUtils.hasText(remoteAddr) || trustedCidrs.isEmpty()) {
return false;
}
try {
InetAddress remote = InetAddress.getByName(remoteAddr.trim());
for (String cidr : trustedCidrs) {
if (cidrMatches(remote, cidr.trim())) {
return true;
}
}
} catch (UnknownHostException ex) {
log.debug("无法解析 remoteAddr {} 为 IP,跳过 XFF 信任判定", remoteAddr);
}
return false;
}
private static boolean cidrMatches(InetAddress target, String cidr) {
if (!cidr.contains("/")) {
// 单 IP 精确匹配
InetAddress trusted;
try {
trusted = InetAddress.getByName(cidr);
} catch (UnknownHostException ex) {
return false;
}
return trusted.equals(target);
}
String[] parts = cidr.split("/", 2);
String netPart = parts[0];
int prefixLen;
try {
prefixLen = Integer.parseInt(parts[1]);
} catch (NumberFormatException ex) {
return false;
}
InetAddress net;
try {
net = InetAddress.getByName(netPart);
} catch (UnknownHostException ex) {
return false;
}
byte[] targetBytes = target.getAddress();
byte[] netBytes = net.getAddress();
if (targetBytes.length != netBytes.length) {
return false;
}
int fullBytes = prefixLen / 8;
int remainingBits = prefixLen % 8;
for (int i = 0; i < fullBytes; i++) {
if (targetBytes[i] != netBytes[i]) {
return false;
}
}
if (remainingBits > 0 && fullBytes < targetBytes.length) {
int mask = (0xFF << (8 - remainingBits)) & 0xFF;
if ((targetBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) {
return false;
}
}
return true;
}
/** Spring 直接实例化;保留 package-private 方便单测 new。 */
WebUtils() {
} }
} }
@@ -0,0 +1,31 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/** 短剧标签。名称分中文、英文、印尼语。 */
@Data
@TableName("content_tag")
public class ContentTag {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/** 中文名称。 */
private String name;
private String nameEn;
private String nameId;
/** 已选语言的名称。 */
private String nameLocales;
/** 角标背景色,#RRGGBB。 */
private String bgColor;
private Integer sort;
private Integer status;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -26,6 +26,10 @@ public class Drama {
private String categoryIds; private String categoryIds;
private String genre; private String genre;
private String synopsis; private String synopsis;
/** 标题语言表,JSON。 */
private String titleLocales;
/** 简介语言表,JSON。 */
private String synopsisLocales;
private String coverUrl; private String coverUrl;
private String horizontalCoverUrl; private String horizontalCoverUrl;
private String language; private String language;
@@ -33,6 +37,8 @@ public class Drama {
private String dramaType; private String dramaType;
/** 内容类型多选,逗号分隔(ANIME/LIVE),drama_type 保留第一个 */ /** 内容类型多选,逗号分隔(ANIME/LIVE),drama_type 保留第一个 */
private String dramaTypes; private String dramaTypes;
/** 单选标签,对应 content_tag.id。 */
private Long tagId;
private Integer totalEpisodes; private Integer totalEpisodes;
private Integer freeEpisodes; private Integer freeEpisodes;
private Integer unlockCoin; private Integer unlockCoin;
@@ -14,6 +14,10 @@ public class DramaCategory {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.ASSIGN_ID)
private Long id; private Long id;
private String name; private String name;
private String nameEn;
private String nameId;
/** 已选语言的名称。 */
private String nameLocales;
private Integer sort; private Integer sort;
private Integer status; private Integer status;
} }
@@ -16,7 +16,12 @@ public class DramaClassification {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.ASSIGN_ID)
private Long id; private Long id;
/** 中文名称。 */
private String name; private String name;
private String nameEn;
private String nameId;
/** 已选语言的名称。 */
private String nameLocales;
private Integer sort; private Integer sort;
private Integer status; private Integer status;
private LocalDateTime createdAt; private LocalDateTime createdAt;
@@ -16,9 +16,18 @@ public class DramaPlaylistCategory {
@TableId(type = IdType.ASSIGN_ID) @TableId(type = IdType.ASSIGN_ID)
private Long id; private Long id;
/** 中文名称,列表和唯一性都用这一列。 */
private String name; private String name;
/** 分类描述,便于运营说明该分类的用途 */ private String nameEn;
private String nameId;
/** 中文描述。 */
private String description; private String description;
private String descriptionEn;
private String descriptionId;
/** 已选语言的名称。 */
private String nameLocales;
/** 已选语言的描述。 */
private String descriptionLocales;
private Integer sort; private Integer sort;
private Integer status; private Integer status;
private LocalDateTime createdAt; private LocalDateTime createdAt;
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more