Author SHA1 Message Date
Zhou Weidong 15b540cdd6 chore(merge): 合并内容多语言与转码通知 2026-10-24 16:57:31 +08:00
Zhou Weidong 50b3dd4a8e docs(api): 同步多语言筛选与转码通知契约 2026-10-24 16:53:26 +08:00
Zhou Weidong 1d34e47673 feat(admin): 增加工作台指标和转码通知 2026-10-24 16:53:26 +08:00
Zhou Weidong 2367a5d12b feat(app): 全部短剧改为请求体分页 2026-10-24 16:53:26 +08:00
Zhou Weidong ebc5f890fd feat(playback): 观看记录返回标题多语言 2026-10-24 16:53:26 +08:00
Zhou Weidong e60c47123c feat(content): 短剧分类和标签支持多语言 2026-10-24 16:53:26 +08:00
Zhou Weidong 5c20cf1ab9 Merge branch feat/app-version-and-c-end 2026-10-23 16:45:55 +08:00
Zhou Weidong 45cf405285 feat(api): 加C端分类频道和剧单详情接口 2026-10-23 16:45:28 +08:00
Zhou Weidong 4f80a691d1 feat(app-version): 加批量创建接口 2026-10-23 16:45:20 +08:00
Zhou Weidong 47f19a98eb chore(merge): 合并 App 版本管理后端 2026-10-23 15:27:35 +08:00
Zhou Weidong 62792413df feat(app): 新增后台 App 版本管理接口 2026-10-23 15:27:35 +08:00
Zhou Weidong 34c775620d chore(merge): 合并 compose Redis 依赖修复 2026-10-23 14:58:46 +08:00
Zhou Weidong b3774e0112 fix(deploy): compose 编排补充 REDIS_HOST 依赖 2026-10-23 14:58:46 +08:00
Zhou Weidong 0e6f7531d4 chore(merge): 合并大盘趋势与分布接口 2026-10-23 14:58:33 +08:00
Zhou Weidong 73a8db8498 feat(dashboard): 大盘趋势与分布接口 2026-10-23 14:58:33 +08:00
Zhou Weidong cf657707f9 chore(merge): 合并转码补齐功能 2026-10-23 14:14:39 +08:00
Zhou Weidong 40728e685b feat(media): 新增缺失转码产物自动补齐 2026-10-23 14:14:39 +08:00
Zhou Weidong df2da25833 chore(merge): 合并用户系统协议与播放改动 2026-10-23 12:34:26 +08:00
Zhou Weidong 1ea4cfeba3 test(media): 按物理删除校验重转码清理 2026-10-23 12:34:13 +08:00
Zhou Weidong ce6e3ef70a docs(api): 同步搜索协议播放与收藏契约 2026-10-23 12:34:13 +08:00
Zhou Weidong 87e20c31a9 feat(security): 允许匿名搜索与打开协议页 2026-10-23 12:34:13 +08:00
Zhou Weidong 22edf34ff1 feat(system): 支持后台维护三语协议 2026-10-23 12:34:13 +08:00
Zhou Weidong 16ba79a336 feat(interaction): 支持批量取消收藏 2026-10-23 12:34:13 +08:00
Zhou Weidong 9c25b1b397 fix(playback): 恢复已删除的观看进度 2026-10-23 12:34:13 +08:00
Zhou Weidong 5a80e6693f feat(playback): 播放票据返回各清晰度地址 2026-10-23 12:34:13 +08:00
Zhou Weidong ab58641bbe feat(user): 展示用户最近使用的系统 2026-10-23 12:34:13 +08:00
Zhou Weidong 45e3d84f59 docs(api): 补充分类与剧单管理接口文档 2026-10-22 22:17:58 +08:00
Zhou Weidong a3ff636e45 chore(sql): 补充转码设置菜单初始化补丁 2026-10-22 22:17:58 +08:00
Zhou Weidong 7b360ddccd feat(content): 新增运营分类与剧单分类管理 2026-10-22 22:17:58 +08:00
Zhou Weidong 758c7521bb Merge remote-tracking branch 'origin/develop' into develop 2026-10-22 18:21:05 +08:00
Zhou Weidong e730cfaa7d fix(media): 重转码物理清理旧产物避免唯一键冲突 2026-10-22 18:21:00 +08:00
Zhou Weidong 60a87a8d15 docs(client): 回填首页与我的视觉改版记录 2026-10-22 17:08:05 +08:00
Zhou Weidong 0b519b8ca1 docs(nav): 回填客户端四 Tab 导航记录 2026-10-22 16:22:07 +08:00
Zhou Weidong e6b4a747ce merge: 修复转码 rendition 幂等与失败落库 2026-10-22 15:37:01 +08:00
Zhou Weidong f009f75c03 docs(media): 回填转码修复记录 2026-10-22 15:36:51 +08:00
Zhou Weidong 91b621fe75 fix(media): 清理旧 rendition 并确保失败状态落库 2026-10-22 15:36:35 +08:00
Zhou Weidong 5d1a157085 merge: 修复转码任务认领与媒资校验 2026-10-22 15:27:58 +08:00
Zhou Weidong 5552caa6c1 fix(media): 修正转码任务认领与媒资 id 校验 2026-10-22 15:27:51 +08:00
Zhou Weidong ad84704d28 test(media): 覆盖转码认领与非法媒资 id 2026-10-22 15:27:37 +08:00
Zhou Weidong 08eddc9ed2 merge: 修复转码错误截断与进度上报 2026-10-22 15:13:50 +08:00
Zhou Weidong 660afaf66d fix(media): 转码错误信息截断并上报进度 2026-10-22 15:12:05 +08:00
Zhou Weidong f9bc6eee6d merge: 修复转码媒资 id 精度与存量兜底 2026-10-22 14:59:46 +08:00
Zhou Weidong 5ef5dd8eaf fix(media): 修正转码媒资 id 解析与存量分集补登记 2026-10-22 14:59:16 +08:00
Zhou Weidong a35b02dd18 merge: 修复转码保持原始宽高比 2026-10-22 14:31:30 +08:00
Zhou Weidong 04d25cd23d fix(media): 转码按短边等比定档并回写实际尺寸 2026-10-22 14:31:22 +08:00
Zhou Weidong 217ff24f1c test(media): 覆盖转码保持原始宽高比 2026-10-22 14:30:08 +08:00
Zhou Weidong 40a884cc85 merge: 补齐转码产物查询接口 2026-10-22 14:14:21 +08:00
Zhou Weidong 345408d5e7 feat(media): 新增清晰度与帧图查询接口 2026-10-22 14:14:13 +08:00
Zhou Weidong 090f149b31 test(media): 覆盖转码产物查询接口 2026-10-22 14:10:15 +08:00
Zhou Weidong f66eae5baf merge: 打通后台转码链路 2026-10-22 14:03:13 +08:00
Zhou Weidong 4219186ab0 feat(media): 上传与改片自动入队转码并支持手动重转 2026-10-22 14:03:04 +08:00
Zhou Weidong 7e6075a2e9 test(media): 覆盖转码入队与重转幂等 2026-10-22 14:01:26 +08:00
Zhou Weidong cd51aabe7e merge: 观看历史统一分页契约并移除 limit 2026-10-22 13:21:35 +08:00
Zhou Weidong c5468a669b refactor(app): 观看历史统一分页契约并移除 limit 2026-10-22 13:21:07 +08:00
Zhou Weidong 7b694938c6 merge: 收藏与观看历史支持分页 2026-10-22 12:23:52 +08:00
Zhou Weidong 71b0c7315a feat(app): 收藏与观看历史支持分页 2026-10-22 12:23:43 +08:00
Zhou Weidong ec15950851 merge: 修复转码分集绑定与产物回填 2026-10-22 12:04:08 +08:00
Zhou Weidong 7d563f2cd6 fix(media): 补齐分集转码绑定与产物回填 2026-10-22 12:03:58 +08:00
Zhou Weidong 6bdd245a83 merge: 合并转码配置与缩略图轴 2026-10-22 11:20:35 +08:00
Zhou Weidong 316baf28d6 feat(media): 支持后台转码配置与缩略图轴 2026-10-22 11:20:28 +08:00
Zhou Weidong 70da939a58 docs(plans): 合并剧集列表分页作者偏差登记 2026-10-22 09:18:42 +08:00
211 changed files with 12067 additions and 248 deletions

No files matched your search

+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"]
+384 -6
View File
@@ -168,9 +168,29 @@ 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 +200,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`)
@@ -227,7 +259,8 @@ app.register.max-per-device-per-day
"unlockCoin": 0, "unlockCoin": 0,
"likeCount": "45", "likeCount": "45",
"commentCount": "8", "commentCount": "8",
"playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c..." "playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...",
"thumbnailsUrl": "/files/transcoded/88/thumbnails/thumbnails.vtt?e=1760000000&s=8a1d..."
} }
] ]
} }
@@ -244,6 +277,7 @@ app.register.max-per-device-per-day
| `viewCount` | Long(JSON 字符串) | 取 `drama.view_count`,累计播放量,既有字段语义不变 | | `viewCount` | Long(JSON 字符串) | 取 `drama.view_count`,累计播放量,既有字段语义不变 |
| `episodes[].likeCount` | Long(JSON 字符串) | 本集点赞数,取 `drama_episode.like_count` | | `episodes[].likeCount` | Long(JSON 字符串) | 本集点赞数,取 `drama_episode.like_count` |
| `episodes[].commentCount` | Long(JSON 字符串) | 本集未删除评论数,按 `episode_id` 统计 | | `episodes[].commentCount` | Long(JSON 字符串) | 本集未删除评论数,按 `episode_id` 统计 |
| `episodes[].thumbnailsUrl` | String / null | 本集雪碧图 WebVTT 时间轴签名地址;没有 READY 产物时为 `null` |
计数是只读快照:互动操作完成后客户端重新拉取详情即可刷新;`Long` 字段一律按字符串下发, 计数是只读快照:互动操作完成后客户端重新拉取详情即可刷新;`Long` 字段一律按字符串下发,
客户端需要转成数字再展示(与 `viewCount` 相同)。 客户端需要转成数字再展示(与 `viewCount` 相同)。
@@ -262,7 +296,12 @@ app.register.max-per-device-per-day
"accessible": true, "accessible": true,
"accessType": "FREE", "accessType": "FREE",
"playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...", "playUrl": "/files/episode/202610/xxx.mp4?e=1760000000&s=9f2c...",
"qualities": ["AUTO"], "qualities": ["AUTO", "720p", "1080p"],
"tracks": [
{"quality": "AUTO", "playUrl": "/files/transcoded/88/master.m3u8?e=1760000000&s=9f2c..."},
{"quality": "720p", "playUrl": "/files/transcoded/88/720p/index.m3u8?e=1760000000&s=a1b2..."}
],
"thumbnailsUrl": "/files/transcoded/88/thumbnails/thumbnails.vtt?e=1760000000&s=8a1d...",
"unlockCoin": 0, "unlockCoin": 0,
"previewSeconds": 0, "previewSeconds": 0,
"likeCount": "45", "likeCount": "45",
@@ -277,22 +316,111 @@ app.register.max-per-device-per-day
**判定顺序由服务端决定,客户端不得自行推断可否播放。** 签名默认 15 分钟有效; **判定顺序由服务端决定,客户端不得自行推断可否播放。** 签名默认 15 分钟有效;
开启 `fruitshorts.media.signature-required` 后,`/files/episode/**` 没带有效签名会返回 403。 开启 `fruitshorts.media.signature-required` 后,`/files/episode/**` 没带有效签名会返回 403。
`thumbnailsUrl` 指向 WebVTT:cue 链接为同目录相对雪碧图
`sprite_XXX.jpg#xywh=x,y,w,h`。有 READY `media_thumbnail` 时返回签名地址,
无产物时为 `null`;该字段不影响 `playUrl`、`qualities` 和 HLS/原文件回落。
### 1.5 观看记录与收藏(已实现) ### 1.5 观看记录与收藏(已实现)
| 方法 | 路径 | 说明 | | 方法 | 路径 | 说明 |
| --- | --- | --- | | --- | --- | --- |
| POST | `/app/watch/progress` | 上报进度(建议每 10s 一次,切集时补一次) | | POST | `/app/watch/progress` | 上报进度(建议每 10s 一次,切集时补一次) |
| GET | `/app/watch/progress?dramaId=` | 某剧续看位置 | | GET | `/app/watch/progress?dramaId=` | 某剧续看位置 |
| GET | `/app/watch/recent?limit=20` | 最近观看 | | GET | `/app/watch/recent` | 最近观看分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
| DELETE | `/app/watch/progress/{dramaId}` | 删除某剧记录 | | DELETE | `/app/watch/progress/{dramaId}` | 删除某剧记录 |
| DELETE | `/app/watch/progress` | 清空记录 | | DELETE | `/app/watch/progress` | 清空记录 |
| POST | `/app/favorites/toggle` | 收藏/取消收藏,返回切换后状态 | | POST | `/app/favorites/toggle` | 收藏/取消收藏,返回切换后状态 |
| GET | `/app/favorites` | 收藏列表(卡片结构与首页一致) | | GET | `/app/favorites` | 收藏分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
| DELETE | `/app/favorites/{dramaId}` | 取消收藏 | | DELETE | `/app/favorites/{dramaId}` | 取消收藏 |
| POST | `/app/favorites/remove` | 批量取消收藏,请求体 `{ "dramaIds": ["12", "15"] }` |
进度合并规则:同一集内只前进不后退;换集直接采纳新集;`finished` 只在接近片尾或客户端显式上报时置位。 进度合并规则:同一集内只前进不后退;换集直接采纳新集;`finished` 只在接近片尾或客户端显式上报时置位。
这样用户换设备不会看到进度倒退。 这样用户换设备不会看到进度倒退。
#### 收藏分页
`GET /app/favorites?pageIndex=1&pageSize=20`
请求参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `pageIndex` | int | 否 | 1 | 页码,小于 1 按 1 处理 |
| `pageSize` | int | 否 | 20 | 每页数量,上限 100,小于 1 按 1 处理 |
响应 `data` 为 `PageResult<AppDramaCardVO>`:
```json
{
"total": "23",
"list": [
{
"id": "12",
"title": "替嫁新娘:总裁的掌心宠",
"cover": "/files/drama_cover/12.jpg",
"preview": {}
}
]
}
```
排序固定为收藏时间倒序 `created_at DESC`,收藏时间相同时按 `drama_id DESC`。
仅统计和返回仍处于已上线状态的短剧。
#### 最近观看分页
`GET /app/watch/recent?pageIndex=1&pageSize=20`
请求参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `pageIndex` | int | 否 | 1 | 页码,小于 1 按 1 处理 |
| `pageSize` | int | 否 | 20 | 每页数量,上限 100,小于 1 按 1 处理 |
分页响应 `data` 为 `PageResult<ProgressRespVO>`:
```json
{
"total": "18",
"list": [
{
"dramaId": "12",
"episodeId": "88",
"dramaTitle": "替嫁新娘:总裁的掌心宠",
"titleLocales": {
"zh": "替嫁新娘:总裁的掌心宠",
"en": "The Stand-in Bride: The CEO's Beloved",
"id": "Pengantin Pengganti: Kesayangan Presiden Direktur"
},
"dramaCover": "/files/drama_cover/12.jpg",
"episodeNumber": 6,
"totalEpisodes": 68,
"viewCount": "1800",
"positionMs": "80000",
"durationMs": "120000",
"finished": false,
"playCount": 3,
"updatedAt": "2026-10-22 10:00:00"
}
]
}
```
排序固定为 `updated_at DESC, id DESC`。每页记录通过批量 IN 查询装配短剧和分集,
不逐条访问数据库。越界页返回空 `list` 且 `total` 保持正确。
`ProgressRespVO` 展示字段:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `dramaTitle` | string / null | 短剧中文标题,旧客户端回退用 |
| `titleLocales` | object / null | 短剧标题语言表,key 为 `zh` / `en` / `id`。客户端按当前语言取,没有对应语言时回退 `zh` |
| `dramaCover` | string / null | 短剧封面 |
| `episodeNumber` | int / null | 当前续看集号 `ep_no` |
| `totalEpisodes` | int / null | 短剧总集数 |
| `viewCount` | Long(JSON 字符串)/ null | 短剧热度,取 `drama.view_count`。`playCount` 是用户自己的播放次数 |
### 1.6 离线下载(已实现) ### 1.6 离线下载(已实现)
服务端只发**授权**与**短时效地址**,分片由客户端直接向 CDN 拉取 —— 服务端只发**授权**与**短时效地址**,分片由客户端直接向 CDN 拉取 ——
@@ -460,6 +588,17 @@ GET /app/notices?pageIndex=1&pageSize=20
`expire_at` 为空或未过期的公告;按 `publish_at desc, id desc` 排序。 `expire_at` 为空或未过期的公告;按 `publish_at desc, id desc` 排序。
**表里没有数据时返回 `total=0, list=[]`(HTTP 与 code 都是成功),不是 404。** **表里没有数据时返回 `total=0, list=[]`(HTTP 与 code 都是成功),不是 404。**
#### 1.9.2a 协议公开页(匿名 HTML)
客户端按当前界面语言打开,不走 `{code,message,data}` 包装。正文在后台「协议设置」用 Markdown 维护,页面不另加标题。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/privacy/{lang}` | 隐私协议。`lang` 为 `zh` / `en` / `id` |
| GET | `/terms/{lang}` | 服务条款。语言同上 |
响应 `Content-Type: text/html;charset=UTF-8`。语言或路径不在上表时 HTTP 404。库里还没有该语言时返回内置缺省文案,不返回空页。
#### 1.9.3 `POST /app/creator/apply`(登录) #### 1.9.3 `POST /app/creator/apply`(登录)
```json ```json
@@ -521,6 +660,8 @@ GET /app/notices?pageIndex=1&pageSize=20
| 角色分类 | PUT · DELETE | `/admin/role-categories/{id}` | `system:role-category` | | 角色分类 | PUT · DELETE | `/admin/role-categories/{id}` | `system:role-category` |
| 系统配置 | GET | `/admin/configs` | `system:role` / `system:menu` | | 系统配置 | GET | `/admin/configs` | `system:role` / `system:menu` |
| 系统配置 | PUT | `/admin/configs` | `system:role` | | 系统配置 | PUT | `/admin/configs` | `system:role` |
| 协议 | GET | `/admin/legal-documents` | `system:role` / `system:menu` |
| 协议 | PUT | `/admin/legal-documents` | `system:role` |
| 操作日志 | GET | `/admin/operation-logs/page` · `/{id}` | `log:list` | | 操作日志 | GET | `/admin/operation-logs/page` · `/{id}` | `log:list` |
| 字典 | GET | `/admin/dicts/drama-category` · `/content-status` | `drama:list` | | 字典 | GET | `/admin/dicts/drama-category` · `/content-status` | `drama:list` |
@@ -553,6 +694,16 @@ GET /app/notices?pageIndex=1&pageSize=20
- 列表响应返回 `dramaTypes[]`、`categoryIds[]` 与按选中顺序映射的 `categoryNames[]`; - 列表响应返回 `dramaTypes[]`、`categoryIds[]` 与按选中顺序映射的 `categoryNames[]`;
分类名缺失时回退 `genre`。 分类名缺失时回退 `genre`。
- 后台与 App 过滤均使用 `(',' || column || ',') LIKE '%,value,%'` 整词匹配。 - 后台与 App 过滤均使用 `(',' || column || ',') LIKE '%,value,%'` 整词匹配。
- 短剧另有单选标签 `tagId`。不传保持原值,传 `0` 清空。列表返回 `tagId`、`tagName`、`tagNameEn`、`tagNameId`。后台编辑不再提交内容类型。
**标签**
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/content-tags?enabledOnly=` | `drama:list` | 标签列表。`enabledOnly=true` 只返回启用项 |
| POST | `/admin/content-tags` | `drama:create` | 新建。`locales` 勾选语言,中文必填,英文和印尼语可选 |
| PUT | `/admin/content-tags/{id}` | `drama:update` | 编辑 |
| DELETE | `/admin/content-tags/{id}` | `drama:delete` | 删除,并清空已选该标签的短剧 |
**剧集** **剧集**
@@ -597,6 +748,42 @@ GET /app/notices?pageIndex=1&pageSize=20
**上传会话归属**:`uploadId` 相当于上传凭证,`chunk` / `complete` / 进度查询都校验会话发起人, **上传会话归属**:`uploadId` 相当于上传凭证,`chunk` / `complete` / 进度查询都校验会话发起人,
别人拿到 `uploadId` 也塞不进分片(`{"code":403,"message":"无权操作该上传会话"}`)。 别人拿到 `uploadId` 也塞不进分片(`{"code":403,"message":"无权操作该上传会话"}`)。
**转码档位配置**
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/media/transcode-profile` | `episode:upload` | 读取当前配置;缺省返回四档默认值 |
| PUT | `/admin/media/transcode-profile` | `episode:upload` | 保存配置并记录操作日志 |
配置保存在 `sys_config` 的 `media.transcode.profile`,JSON 结构:
```json
{
"enabled": true,
"segmentSeconds": 6,
"ladder": [
{
"quality": "360p",
"width": 640,
"height": 360,
"videoBitrateKbps": 400,
"audioBitrateKbps": 64,
"enabled": true
}
],
"sprite": {
"enabled": true,
"intervalSeconds": 1,
"columns": 10,
"thumbWidth": 160
}
}
```
`quality` 必须唯一且非空,宽高必须为大于 0 的偶数,音视频码率必须大于 0,
至少启用一档;`segmentSeconds` 2–10、`intervalSeconds` 1–10、`columns` 5–20、
`thumbWidth` 120–240。非法请求返回统一错误码 `400` 且不写库。
### 2.3 App 用户管理(已实现) ### 2.3 App 用户管理(已实现)
| 方法 | 路径 | 权限点 | 说明 | | 方法 | 路径 | 权限点 | 说明 |
@@ -688,6 +875,7 @@ GET /app/notices?pageIndex=1&pageSize=20
| --- | --- | --- | --- | | --- | --- | --- | --- |
| GET | `/admin/dashboard/overview` | `dashboard:view` | 总览:用户 / 内容 / 播放 / 收入 / 成本 | | GET | `/admin/dashboard/overview` | `dashboard:view` | 总览:用户 / 内容 / 播放 / 收入 / 成本 |
| GET | `/admin/dashboard/transcode` | `dashboard:view` | 转码队列积压与失败任务明细(含 `errorMsg` / `retryCount`) | | GET | `/admin/dashboard/transcode` | `dashboard:view` | 转码队列积压与失败任务明细(含 `errorMsg` / `retryCount`) |
| GET | `/admin/notifications/transcode` | `drama:list` | 转码通知:`running` / `success` / `failed` 角标,以及各状态最近 20 条(含 `dramaTitle`、`episodeNo`、`episodeTitle`) |
**口径(与代码注释一致,前端 tooltip 可直接复用)** **口径(与代码注释一致,前端 tooltip 可直接复用)**
@@ -695,6 +883,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` 非空数(均排除逻辑删除) |
@@ -955,6 +1145,194 @@ GET /app/notices?pageIndex=1&pageSize=20
**筛选与错误码**:`title` 必填(1–128);`content` 最长 2000;公告不存在 → `200002 公告不存在`; **筛选与错误码**:`title` 必填(1–128);`content` 最长 2000;公告不存在 → `200002 公告不存在`;
`status` 只接受 0/1,其他值 → `400`。 `status` 只接受 0/1,其他值 → `400`。
### 2.13 运营分类管理(已实现)
> 「分类」是运营自定义的分组,与短剧**类型**(`/admin/drama-categories`,写 `drama_category`)是两套独立概念。
> 分类存在 `drama_classification`,通过 `drama_classification_drama` 关联任意多部短剧。
> 后台页面:菜单 **分类管理**(`/content/category-dramas` → `CategoryDramaView.vue`)。
**接口清单**(前缀 `/admin/drama-classifications`)
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/drama-classifications` | `drama:list` | 分类列表(带关联短剧数量) |
| POST | `/admin/drama-classifications` | `drama:create` | 新建分类,返回新分类 id |
| PUT | `/admin/drama-classifications/{id}` | `drama:update` | 编辑分类 |
| DELETE | `/admin/drama-classifications/{id}` | `drama:delete` | 删除分类(级联删关联,短剧本身保留) |
| GET | `/admin/drama-classifications/{id}/dramas` | `drama:list` | 分类下已关联的短剧(分页) |
| GET | `/admin/drama-classifications/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
| POST | `/admin/drama-classifications/{id}/dramas` | `drama:update` | 批量关联短剧,返回实际新增数量 |
| DELETE | `/admin/drama-classifications/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
**列表响应**
```json
{
"code": 0,
"message": "ok",
"data": [
{
"id": "2112807182243336193",
"name": "本周必看",
"sort": 1,
"status": 1,
"dramaCount": 12,
"updatedAt": "2026-10-22T19:41:02"
}
]
}
```
排序规则固定为 `sort asc, id desc`;`dramaCount` 是关联表按分类聚合的实时数量。
时间字段为 `LocalDateTime` 的 ISO 字符串(`yyyy-MM-ddTHH:mm:ss`,秒级),前端按需替换 `T` 为空格。
**新建 / 编辑请求体**
```json
{ "name": "本周必看", "sort": 1, "status": 1 }
```
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写分类名称」 |
| `sort` | 否 | 新建不传时取 `现有条数 + 1`;编辑不传(null)时保持原值 |
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1`,编辑不传保持原值 |
**关联短剧**
```json
POST /admin/drama-classifications/2112807182243336193/dramas
{ "dramaIds": ["2112807182243336194", "2112807182243336195"] }
```
返回 `data` 为实际新增条数(整数)。已关联的、以及不存在的 `dramaId` 会被静默跳过,不报错;
全部跳过时返回 `0`。`dramaIds` 为空数组 → `400 请选择短剧`。
**短剧列表项(`GET /{id}/dramas` 与 `/dramas/candidates` 共用)**
```json
{
"total": 12,
"list": [
{
"id": "2112807182243336194",
"title": "闪婚后首富老公竟是我老板",
"cover": "https://.../cover.jpg",
"status": "published",
"totalEpisodes": 80,
"sort": 100,
"updatedAt": "2026-10-22T18:00:00"
}
]
}
```
- 查询参数:`keyword`(按 `title` 模糊匹配,可空)、`pageIndex`(默认 1)、`pageSize`(默认 10,上限 100)
- 排序:`sort desc, id desc`
- `status` 取值:`draft` 草稿 / `reviewing` 审核中 / `approved` 待发布 / `published` 已上线 / `offline` 已下线
- `cover` 取自短剧 `cover_url`
**错误码**
| 场景 | 返回 |
| --- | --- |
| 分类名称重复(新建或改名撞已有) | `200001 分类名称已存在` |
| 分类 id 不存在(编辑/删除/查询/关联/移出) | `200002 分类不存在` |
| `name` 为空 | `400 请填写分类名称` |
| `dramaIds` 为空 | `400 请选择短剧` |
> 所有写操作带 `@OperationLog(module = "内容管理")` 操作日志。ID 下发口径见 **§0**。
### 2.14 剧单管理(已实现)
> 剧单使用**自己的一套分类**(`drama_playlist_category`),与「分类管理」和「类型」都没有关系。
> **没有「剧单」这一层实体**:分类直接挂短剧,关联表 `drama_playlist_category_drama(category_id, drama_id)`。
> 后台页面:菜单 **剧单管理**(`/content/drama-playlists` → `DramaPlaylistView.vue`)。
**接口清单**(前缀 `/admin/drama-playlist-categories`)
| 方法 | 路径 | 权限点 | 说明 |
| --- | --- | --- | --- |
| GET | `/admin/drama-playlist-categories` | `drama:list` | 剧单分类列表(带短剧数量) |
| POST | `/admin/drama-playlist-categories` | `drama:create` | 新建剧单分类,返回新分类 id |
| PUT | `/admin/drama-playlist-categories/{id}` | `drama:update` | 编辑剧单分类 |
| DELETE | `/admin/drama-playlist-categories/{id}` | `drama:delete` | 删除剧单分类(级联删关联,短剧本身保留) |
| GET | `/admin/drama-playlist-categories/{id}/dramas` | `drama:list` | 分类下已关联的短剧(分页) |
| GET | `/admin/drama-playlist-categories/{id}/dramas/candidates` | `drama:list` | 尚未关联到该分类的短剧(分页,供多选) |
| POST | `/admin/drama-playlist-categories/{id}/dramas` | `drama:update` | 批量把短剧加入分类,返回实际新增数量 |
| DELETE | `/admin/drama-playlist-categories/{id}/dramas/{dramaId}` | `drama:update` | 从分类移出短剧(幂等) |
**列表响应**
```json
{
"code": 0,
"message": "ok",
"data": [
{
"id": "2112807182243336196",
"name": "高甜先婚后爱",
"description": "站内投放位使用,按周更新",
"sort": 1,
"status": 1,
"dramaCount": 8
}
]
}
```
排序规则 `sort asc, id desc`;`dramaCount` 为该分类下已关联短剧数量。
**新建 / 编辑请求体**
```json
{
"name": "高甜先婚后爱",
"description": "站内投放位使用,按周更新",
"sort": 1,
"status": 1
}
```
| 字段 | 必填 | 说明 |
| --- | --- | --- |
| `name` | 是 | 去首尾空格后保存,全局唯一;`@NotBlank` 提示「请填写剧单分类名称」 |
| `description` | 否 | 最长 255 字符(超长 → `400 描述最多 255 个字符`);新建不传存空串,编辑不传保持原值 |
| `sort` | 否 | 新建不传取 `现有条数 + 1`;编辑不传保持原值 |
| `status` | 否 | `1` 启用 / `0` 停用;新建默认 `1` |
**关联短剧**
```json
POST /admin/drama-playlist-categories/2112807182243336196/dramas
{ "dramaIds": ["2112807182243336194"] }
```
返回实际新增条数;已关联或不存在的短剧自动跳过;`dramaIds` 为空 → `400 请选择短剧`。
`GET /{id}/dramas` 与 `GET /{id}/dramas/candidates` 的查询参数和响应结构与 **§2.13** 完全一致
(`keyword` / `pageIndex` / `pageSize`,响应 `{ total, list }`,列表项含
`id` / `title` / `cover` / `status` / `totalEpisodes` / `sort` / `updatedAt`)。
**错误码**
| 场景 | 返回 |
| --- | --- |
| 剧单分类名称重复 | `200001 剧单分类名称已存在` |
| 剧单分类 id 不存在 | `200002 剧单分类不存在` |
| `name` 为空 | `400 请填写剧单分类名称` |
| `description` 超过 255 | `400 描述最多 255 个字符` |
| `dramaIds` 为空 | `400 请选择短剧` |
**与「分类管理」的差异**
| 项 | 运营分类(2.13) | 剧单分类(2.14) |
| --- | --- | --- |
| 数据表 | `drama_classification` + `drama_classification_drama` | `drama_playlist_category` + `drama_playlist_category_drama` |
| 描述字段 | 无 | 有(`description`,≤255) |
| 列表返回 | 含 `updatedAt` | 含 `description`,不含 `updatedAt` |
| 菜单 | 分类管理(`/content/category-dramas`) | 剧单管理(`/content/drama-playlists`) |
| 用途 | 内容侧分组 | 运营侧投放/剧单位分组 |
## 3. 契约与实现状态对照 ## 3. 契约与实现状态对照
> 最后更新:2026-10-16(`develop` 分支)。未完成项汇总见仓库根 `README.md`「尚未完成」。 > 最后更新:2026-10-16(`develop` 分支)。未完成项汇总见仓库根 `README.md`「尚未完成」。
@@ -0,0 +1,24 @@
# 客户端收藏与观看历史分页
## 目标
- `/app/favorites` 改为 `PageResult<AppDramaCardVO>`,默认第 1 页、每页 20,最大 100。
- `/app/watch/recent` 默认返回 `PageResult<ProgressRespVO>`;请求带 `limit` 时保留一版旧
`List<ProgressRespVO>` 响应。
- 观看历史补充短剧标题、封面、集号和总集数,剧/集均批量查询。
## 实现步骤
1. 收藏关系使用 `selectPage`,按 `created_at DESC, drama_id DESC` 稳定排序;
只统计已上线短剧收藏,再按当前页 ID 批量加载短剧。
2. 观看进度使用 `selectPage`,按 `updated_at DESC, drama_id DESC` 稳定排序。
3. 当前页的 dramaId / episodeId 去重排序后,分别执行一次 IN 查询并装配展示字段。
4. Controller 归一化 pageIndex/pageSize;观看历史根据是否传 `limit` 分流新旧响应。
5. 更新 API 契约 §1.5,补 service/controller 测试。
## 风险与约束
- `limit` 分支仅用于旧客户端兼容,新分页响应与旧 List 响应不能混用。
- 已下线短剧不计入收藏 total,也不出现在收藏页。
- 观看历史展示字段找不到对应剧或集时保持 null,不影响历史记录返回。
- 不修改客户端、不改表结构、不启停服务、不操作真机。
@@ -0,0 +1,38 @@
# 转码产物查询接口
## 目标
- 媒体维度查询 rendition 与帧图产物。
- 分集维度聚合转码任务、rendition、帧图状态。
- `/admin/dashboard/transcode` 改为明确 VO,OpenAPI 不再出现匿名 Object。
## 设计
1. `MediaTranscodeOutputService` 统一读取媒体、任务、rendition 与 thumbnail。
2. rendition 按高度、视频码率、质量倒序,id 正序保证稳定。
3. thumbnail 优先读取 `thumbnails.vtt`,解析 cue 后分页;无记录返回 `EMPTY`,
记录失败返回 `FAILED`,不把缺产物当服务错误。
4. 分集聚合对不存在、无视频、无媒资、无任务返回明确 status 和空列表。
5. dashboard 使用强类型 queue/failed task VO,保留现有字段语义并补 total。
## 接口
- `GET /admin/media/{id}/renditions`
- `GET /admin/media/{id}/thumbnails?pageIndex=1&pageSize=100`
- `GET /admin/episodes/{id}/transcode`
- `GET /admin/dashboard/transcode`(响应类型由 Map 收敛为 VO)
缩略图响应内嵌 `PageResult<MediaThumbnailFrameVO>`,同时返回 sprite/VTT 元数据;
空产物 status 为 `EMPTY`,无绑定分集为 `NO_EPISODE`,损坏 VTT 为 `INVALID`。
## TDD
- 先提交媒体有/无产物、不存在、VTT 解析与分页边界测试。
- 再提交接口、VO、聚合服务和 dashboard 类型收敛实现。
- 门禁:`mvn -pl fruitshorts-module-media test`。
## 红线
- 不改 `/app` 契约、specs、ReelShortWeb、Flutter。
- 不改 P1 入队与手动重转逻辑。
- 不启停服务,不操作真机。
@@ -0,0 +1,40 @@
# 后台转码链路打通
## 现状取证
- 上传完成时 `MediaService.complete` 已为视频调用 `TranscodeService.enqueue`。
- 分集创建/替换视频地址时 `EpisodeService` 已调用
`EpisodeTranscodeBindingService.bind`,会复用并绑定同一媒体的未完成任务。
- 转码失败原因已写入 `transcode_task.error_msg`,最终状态写入 `status`。
- 缺口是后台手动触发/重转接口,以及对应幂等和链路测试。
## 实现
1. 保留上传完成和改片自动入队逻辑,补测试锁定行为。
2. `TranscodeService` 增加手动触发:
- QUEUED/RUNNING 直接返回现有任务;
- FAILED 重置原任务为 QUEUED;
- SUCCESS 才创建新任务,紧接着重复触发会复用新 QUEUED 任务。
3. 新增 `POST /admin/media/{id}/transcode`,校验媒资存在,复用 `episode:upload`。
4. 返回任务 id 与状态,便于后台提示。
实现时对同一媒资行使用 `FOR UPDATE`,让重复请求在事务内串行判定;
平台不存在的媒资保持 `DATA_NOT_FOUND`,不产生任务或 500。
## TDD 测试矩阵
| 场景 | 断言 |
| --- | --- |
| 视频上传完成 | `MediaService.complete` 调用一次 `enqueue(assetId, 0, 0, sourceUrl)` |
| 图片上传完成 | 不创建转码任务 |
| 手动触发成功媒资 | 新建一个 QUEUED 任务,重复调用复用同一任务 |
| 手动触发进行中媒资 | 直接返回 QUEUED/RUNNING 任务,不新增记录 |
| 手动触发失败媒资 | 原任务重置为 QUEUED,保留任务 id |
| 媒资不存在 | 返回既有 `DATA_NOT_FOUND`,控制器不产生 500 |
| worker 最终失败 | 任务状态 FAILED,`error_msg` 保留 ffmpeg 原因 |
## 验证
- 先提交失败测试,再提交实现。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`
- 不启停任何服务,不执行数据库变更,不改 Web/Flutter/specs/API 文档。
@@ -0,0 +1,53 @@
# 转码档位配置、雪碧图与播放缩略图轴
## 目标
1. 后台可配置转码档位与雪碧图参数,worker 对之后的新任务在 30 秒内自动生效。
2. 转码成功后生成雪碧图与 VTT,登记到 `media_thumbnail`。
3. 播放接口与详情剧集返回 `thumbnailsUrl`,无产物时为 `null`。
## 配置模型
- `sys_config.config_key = media.transcode.profile`,值为 JSON。
- 配置包含总开关、分片秒数、码率阶梯与雪碧图参数。
- 缺省配置等价于现有 360p/480p/720p/1080p 四档。
- 后台 GET 缺省或历史配置非法时返回 yml 等价默认值;PUT 非法时返回统一 400,且不写库。
- worker 读取配置缓存 30 秒;缺省、解析失败或校验失败时回退 yml 默认阶梯。
## 权限取舍
现有权限点没有 `media:transcode`。本次两个接口复用最小可用的
`episode:upload`,避免新增权限点导致已有角色需要补授权;不新增菜单或权限 SQL。
## 数据与产物
- 新增 `media_thumbnail`,按 `episode_id` 唯一,记录 VTT、雪碧图前缀、采样参数、
尺寸、帧数、时长、状态、错误与总大小。
- 雪碧图目录固定在 `transcoded/{taskId}/thumbnails/`:
`thumbnails.vtt` + `sprite_001.jpg` 等多张图。
- VTT cue 链接使用相对路径 `sprite_XXX.jpg#xywh=x,y,w,h`,同一 VTT 目录下可直接解析。
- 缩略图失败只把 `media_thumbnail.status` 置 `FAILED` 并记录错误;主 HLS 仍成功。
## 播放
- `PlayRespVO` 和 `AppEpisodeVO` 增加 `thumbnailsUrl`。
- 查询 `media_thumbnail` 仅读取 `READY` 产物;objectKey 经
`MediaStorageService.toPublicUrl` 后使用现有 `PlaybackSigner` 签名。
- 详情剧集列表批量查询缩略图,禁止 N+1。
- 不改变现有 HLS/原文件回落与 qualities 列表。
## 测试
- worker:配置解析、非法配置回退 yml、30 秒缓存、VTT 坐标、多雪碧图索引、
缩略图失败不阻断主转码。
- admin:GET 默认值、PUT 非法不落库、PUT 成功落库。
- playback:有 READY 缩略图返回签名 `thumbnailsUrl`,无产物返回 `null`。
- 门禁:`mvn -pl fruitshorts-transcode-worker,fruitshorts-admin-api,fruitshorts-app-api -am test`。
## 风险 / 边界
- 本次只对合并后的新转码任务生效,不回跑历史任务。
- 配置中的顶层 `enabled` 会持久化并返回;本单不改变既有队列消费开关语义,
worker 仍以 `worker-enabled` 决定是否消费任务。
- 雪碧图生成依赖 ffmpeg `tile` 滤镜;真实产物由 worker 门禁和 PM 后续环境验收,
本任务不启动服务、不改客户端。
@@ -0,0 +1,38 @@
# 转码分集绑定与运行态修复
## 已确认现场
admin-api/app-api/worker 均运行旧包;worker 未运行;`media_thumbnail` 表缺失;
新上传任务 drama_id/episode_id 为 0;旧 worker jar 缺 MediaThumbnail。
## 代码修复
1. 分集保存后按视频 URL 的 objectKey 查找 `media_asset`。
2. media 域新增绑定服务:
- 将 dramaId/episodeId 回填到对应 `transcode_task`;
- QUeued/RUNNING/SUCCESS 任务复用,不重复入队;
- FAILED/CANCELED 或不存在时新建任务;
- 已成功但 episodeId=0 的 rendition 同步回填。
3. `claimNext` 只认领 `episode_id > 0`,零绑定任务保留 QUEUED。
4. 缩略图登记使用 REQUIRES_NEW 独立事务;生成或登记失败只记 warn/error_msg,
主任务仍 SUCCESS。
5. 对 episode_id=0 且源文件不存在的明显测试垃圾标记 CANCELED,不删除。
## 迁移与运行
1. 确认 `media_thumbnail` 不存在后执行幂等 patch。
2. `mvn -DskipTests package` 全量重建。
3. 检查三个 jar 分别含:
- admin-api:MediaTranscodeProfile;
- app-api:PlayRespVO.thumbnailsUrl 对应新类;
- worker:MediaThumbnail / MediaThumbnailMapper。
4. 重启 8080/8081/worker,日志写 `logs/*.log`。
5. 冒烟 admin 配置、App 详情 thumbnailsUrl、worker 轮询。
6. 上传真实视频,创建绑定分集,等待 worker 消费,验证任务、四档 HLS、
media_thumbnail、VTT 与 sprite HTTP 200。
## 风险
- 旧 QUEUED 中无法绑定且源文件不存在的测试任务将被取消并记录 id。
- 真实视频端到端验证会写入运行数据库和媒资目录。
- 不修改 Web/Flutter,不操作真机。
@@ -0,0 +1,24 @@
# 转码任务认领与媒资 ID 校验
## 现场结论
- `media_asset.id=21` 确实存在,source_url 对应分集 id=13。
- 分集 13 的 video_asset_id=0,旧手动触发只拿媒资,不知道分集绑定,
因而创建了 media_asset_id=21、episode_id=0 的 QUEUED 任务。
- claim 只筛选 episode_id>0,因此该任务永久跳过且没有原因日志。
## 修复
1. POST /admin/media/{id}/transcode 严格只按 media_asset.id 查询;
不再把候选 id 当分集 id 兜底或补登记。
2. 媒资存在时按 source_url 反查分集;找到后绑定 drama_id/episode_id。
3. 找不到分集时拒绝建任务,避免生成永远无法认领的 episode_id=0 记录。
4. claim 增加 media_asset_id/source_url 条件,并记录被跳过任务 id 与原因。
5. RUNNING 无更新阈值收敛到 5 分钟,覆盖 worker 重启后的孤儿任务。
6. 一次性 patch 将 media_asset_id 不存在且 episode_id=0 的 QUEUED/RUNNING 标记 FAILED。
## 验证
- 非法 media id 拒绝、未绑定分集拒绝、合法 URL 自动绑定。
- claim 跳过原因、进度更新、僵尸任务恢复。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,28 @@
# 转码媒资 ID 精度与存量兜底修复
## 取证
- 示例分集 `2113150431755636737` 的 `video_asset_id` 为
`2113150398670966786`,与 `media_asset.id` 完全一致。
- JS `Number('2113150398670966786')` 序列化为 `2113150398670966800`,
超出安全整数后发生精度丢失,导致手动转码查询了错误 ID。
## 修复
1. 聚合响应的 episodeId/mediaAssetId/taskId 使用字符串。
2. 手动转码仍由后端 Long 接收精确路径 ID。
3. 媒资不存在时通过 content 模块的端口按候选 ID 查找分集:
- 分集 id;
- video_asset_id;
- transcode_task.id。
4. 找到分集后按 video_url/source_url/objectKey 反查媒资;
文件存在但媒资缺失时补登记并回填分集 video_asset_id。
5. 无可用视频时保持明确空态/错误语义。
## 验证
- 超 2^53 ID 字符串契约。
- 聚合无媒资空态。
- video_url 反查命中。
- 文件存在时补登记。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,27 @@
# 转码保持原始宽高比
## 目标
- 横屏源按档位短边作为高度,竖屏源按档位短边作为宽度。
- 源短边小于档位短边时按源短边输出,不放大。
- 输出宽高均为偶数,SAR 固定为 1。
- rendition 的 width/height 使用 ffprobe 探测到的实际值。
## 实施
1. ffprobe 读取源显示方向尺寸,旋转 90/270 度时交换宽高。
2. `effectiveShort = min(sourceShort, rungShort)` 并向下取偶数。
3. 横屏使用 `scale=-2:<effectiveShort>:flags=lanczos,setsar=1`;
竖屏使用 `scale=<effectiveShort>:-2:flags=lanczos,setsar=1`。
4. 转码完成后 ffprobe variant playlist,写入实际输出尺寸。
5. master playlist 的 RESOLUTION 同步使用实际尺寸。
## 不放大策略
选用“用源尺寸输出”:高于源短边的档位仍保留原 quality 标识和码率,
但分辨率封顶到源短边,避免所有档位都被跳过导致无产物。
## 验证
- 先补横屏、竖屏、小源码片、偶数、SAR=1 与实际尺寸回写测试。
- 门禁:`mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,29 @@
# 转码错误截断与进度上报
## 问题
- ffmpeg 错误输出超过 `error_msg varchar(500)`,失败回写 UPDATE 再次失败,
任务停在 RUNNING/0。
- worker 未解析 ffmpeg progress,前端只能看到 0。
- 缺少 RUNNING 超时收口。
## 修复
1. SQL patch 将 transcode_task/media_thumbnail 的 error_msg 改为 TEXT,可重复执行。
2. 新增统一错误消息截断,最多保留 500 字符并附总长度;即使补丁尚未执行,
也不会超过旧 varchar(500) 限制。
3. ffmpeg 使用 `-progress` 临时文件,worker 节流为约 1 秒写 transcode_task.progress。
4. rendition 阶段映射 0-90%,封面/缩略图 90-99%,成功后 100。
5. 失败保留最后进度;RUNNING 超过 10 分钟无 updated_at 变化标记 FAILED。
6. 手动重转复用最新任务,SUCCESS/FAILED/CANCELED 原地重置为 QUEUED、progress=0。
7. 成功写 rendition 前替换同媒资旧产物,避免重复重转唯一键冲突。
## 风险
- 进度写入只允许 RUNNING 状态,避免覆盖已完成/失败状态。
- 历史僵尸任务由 worker 下一轮自动收口,无需手工 SQL。
## 验证
- 错误截断、进度更新、僵尸重置、重复触发幂等测试。
- `mvn -pl fruitshorts-module-media,fruitshorts-transcode-worker test`。
@@ -0,0 +1,24 @@
# 转码 rendition 幂等与失败落库
## 根因
- 成功事务只按 media_asset_id 删除旧 rendition。
- 同一分集替换视频后 media_asset_id 改变、episode_id 不变,
旧行未被删除,触发 uk_rendition(episode_id, quality, format)。
- rendition 插入异常后任务未被可靠置为 FAILED。
## 修复
1. 成功事务删除条件分组为:
`media_asset_id = 本次媒体 OR (episode_id > 0 AND episode_id = 本次分集)`。
2. 缩略图登记按 episode_id 删除旧行后重新插入。
3. 主流程异常调用 failFinal,直接写 FAILED、错误、finished_at,保留 progress。
4. failFinal 自身异常在 worker 中 catch 并打印 ERROR,不静默。
5. error 截断同时保留头部与尾部,长度仍 <= 500。
## 验证
- 不同 media_asset_id、同 episode_id 的重复转码清理条件。
- thumbnail 旧行替换。
- 失败落库字段与尾段错误保留。
- `mvn -q -DskipTests=false test -pl ... -am`。
+19
View File
@@ -0,0 +1,19 @@
# 标签管理(替换短剧内容类型)
## 决定
不做「语言开关」总控。分类和剧单已经用 `name` / `nameEn` / `nameId` 三列。标签沿用同一套,避免两套国际化。语言总控要改短剧标题、简介、剧集标题,单独开一轮。
## 本轮
- 短剧编辑去掉「内容类型」。库里的 `drama_type` 先留着,推荐流的 `ANIME` / `LIVE` 筛选不受影响,后台不再改它。
- 内容管理下新增「标签管理」。
- 标签字段:中文名、英文名、印尼语名、排序、启用状态。三个名称都必填。
- 短剧 `tag_id` 单选,可空。编辑页用下拉,只列出启用中的标签。
- 已有短剧按原内容类型回填:`ANIME` → 漫剧,`LIVE` → 真人剧。
## 接口
- `GET/POST /admin/content-tags`,`PUT/DELETE /admin/content-tags/{id}`,权限沿用 `drama:list` / `create` / `update` / `delete`。
- 短剧保存增加 `tagId`。不传则保持原值;传 `0` 表示清空。
- 短剧列表返回 `tagId`、`tagName`、`tagNameEn`、`tagNameId`。
File diff suppressed because it is too large. Load diff
@@ -4,6 +4,7 @@ package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.admin.service.AppSessionSystemService;
import com.fruitshorts.admin.vo.AppUserWatchHistoryVO; import com.fruitshorts.admin.vo.AppUserWatchHistoryVO;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
@@ -13,6 +14,7 @@ import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.framework.log.OperationLog; import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.dal.entity.WatchHistory; import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.playback.service.WatchProgressService; import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.user.dal.entity.AppUserBanRecord; import com.fruitshorts.user.dal.entity.AppUserBanRecord;
import com.fruitshorts.user.service.AppUserAdminService; import com.fruitshorts.user.service.AppUserAdminService;
@@ -44,6 +46,7 @@ public class AppUserAdminController {
private final WatchProgressService watchProgressService; private final WatchProgressService watchProgressService;
private final DramaService dramaService; private final DramaService dramaService;
private final EpisodeService episodeService; private final EpisodeService episodeService;
private final AppSessionSystemService sessionSystem;
@Operation(summary = "App 用户分页查询") @Operation(summary = "App 用户分页查询")
@GetMapping("/page") @GetMapping("/page")
@@ -83,11 +86,15 @@ public class AppUserAdminController {
Map<Long, DramaEpisode> episodes = episodeService Map<Long, DramaEpisode> episodes = episodeService
.listByIds(rows.stream().map(WatchHistory::getEpisodeId).distinct().toList()) .listByIds(rows.stream().map(WatchHistory::getEpisodeId).distinct().toList())
.stream().collect(Collectors.toMap(DramaEpisode::getId, item -> item, (a, b) -> a)); .stream().collect(Collectors.toMap(DramaEpisode::getId, item -> item, (a, b) -> a));
return Result.ok(rows.stream().map(row -> toVo(row, dramas, episodes)).toList()); List<AppUserSession> sessions = sessionSystem.groupByUser(List.of(id))
.getOrDefault(id, List.of());
return Result.ok(rows.stream()
.map(row -> toVo(row, dramas, episodes, sessionSystem.match(sessions, row.getDeviceId())))
.toList());
} }
private AppUserWatchHistoryVO toVo(WatchHistory row, Map<Long, Drama> dramas, private AppUserWatchHistoryVO toVo(WatchHistory row, Map<Long, Drama> dramas,
Map<Long, DramaEpisode> episodes) { Map<Long, DramaEpisode> episodes, AppUserSession session) {
AppUserWatchHistoryVO vo = new AppUserWatchHistoryVO(); AppUserWatchHistoryVO vo = new AppUserWatchHistoryVO();
vo.setId(row.getId()); vo.setId(row.getId());
vo.setDramaId(row.getDramaId()); vo.setDramaId(row.getDramaId());
@@ -100,6 +107,10 @@ public class AppUserAdminController {
long position = row.getPositionMs() == null ? 0L : row.getPositionMs(); long position = row.getPositionMs() == null ? 0L : row.getPositionMs();
long duration = row.getDurationMs() == null ? 0L : row.getDurationMs(); long duration = row.getDurationMs() == null ? 0L : row.getDurationMs();
vo.setFinished(duration > 0 && position + 1000L >= duration); vo.setFinished(duration > 0 && position + 1000L >= duration);
if (session != null) {
vo.setPlatform(session.getPlatform());
vo.setOsVersion(session.getOsVersion());
}
Drama drama = dramas.get(row.getDramaId()); Drama drama = dramas.get(row.getDramaId());
if (drama != null) { if (drama != null) {
vo.setDramaTitle(drama.getTitle()); vo.setDramaTitle(drama.getTitle());
@@ -0,0 +1,98 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.system.service.AppVersionService;
import com.fruitshorts.system.vo.AppVersionQueryReqVO;
import com.fruitshorts.system.vo.AppVersionRespVO;
import com.fruitshorts.system.vo.AppVersionSaveReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/** 后台 - App 版本管理。 */
@Tag(name = "后台-App 版本")
@RestController
@RequestMapping("/admin/app-versions")
@RequiredArgsConstructor
public class AppVersionAdminController {
private final AppVersionService appVersionService;
@Operation(summary = "版本分页查询")
@GetMapping("/page")
@PreAuthorize("@ss.hasPermission('app-version:list')")
public Result<PageResult<AppVersionRespVO>> page(@Validated AppVersionQueryReqVO req) {
return Result.ok(appVersionService.page(req));
}
@Operation(summary = "版本详情")
@GetMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:list')")
public Result<AppVersionRespVO> detail(@PathVariable Long id) {
return Result.ok(appVersionService.detail(id));
}
@Operation(summary = "新建版本(默认发布)")
@PostMapping
@PreAuthorize("@ss.hasPermission('app-version:create')")
@OperationLog(module = "版本管理", action = "新建版本")
public Result<Long> create(@Valid @RequestBody AppVersionSaveReqVO req) {
return Result.ok(appVersionService.create(req));
}
@Operation(summary = "批量新建版本(一次事务)")
@PostMapping("/batch")
@PreAuthorize("@ss.hasPermission('app-version:create')")
@OperationLog(module = "版本管理", action = "批量新建版本")
public Result<java.util.List<Long>> batchCreate(
@NotEmpty(message = "请至少传一条")
@Size(max = 16, message = "单次不超过 16 条")
@Valid @RequestBody java.util.List<@Valid AppVersionSaveReqVO> reqs) {
return Result.ok(appVersionService.batchCreate(reqs));
}
@Operation(summary = "编辑版本")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:update')")
@OperationLog(module = "版本管理", action = "编辑版本")
public Result<Void> update(@PathVariable Long id, @Valid @RequestBody AppVersionSaveReqVO req) {
appVersionService.update(id, req);
return Result.ok();
}
@Operation(summary = "发布 / 下架")
@PutMapping("/{id}/status")
@PreAuthorize("@ss.hasPermission('app-version:update')")
@OperationLog(module = "版本管理", action = "版本上下架")
public Result<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
appVersionService.updateStatus(id, status);
return Result.ok();
}
@Operation(summary = "删除版本")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('app-version:delete')")
@OperationLog(module = "版本管理", action = "删除版本")
public Result<Void> delete(@PathVariable Long id) {
appVersionService.delete(id);
return Result.ok();
}
}
@@ -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,9 @@
package com.fruitshorts.admin.controller; package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.DashboardService; import com.fruitshorts.admin.service.DashboardService;
import com.fruitshorts.admin.vo.DashboardDistributionRespVO;
import com.fruitshorts.admin.vo.DashboardTrendRespVO;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@@ -40,7 +43,23 @@ public class DashboardAdminController {
@Operation(summary = "转码看板(队列积压与失败任务)") @Operation(summary = "转码看板(队列积压与失败任务)")
@GetMapping("/transcode") @GetMapping("/transcode")
@PreAuthorize("@ss.hasPermission('dashboard:view')") @PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<Map<String, Object>> transcode() { public Result<TranscodeDashboardRespVO> transcode() {
return Result.ok(dashboardService.transcode()); return Result.ok(dashboardService.transcode());
} }
/** 近 7 天每日趋势(用户注册 / 播放事件 / 转码任务)。 */
@Operation(summary = "大盘趋势(近 7 天每日数据,给折线图用)")
@GetMapping("/trend")
@PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<DashboardTrendRespVO> trend() {
return Result.ok(dashboardService.trend());
}
/** 分布:短剧状态 / 转码状态 / 片源覆盖 / 待处理审核。 */
@Operation(summary = "大盘分布(给饼图用)")
@GetMapping("/distribution")
@PreAuthorize("@ss.hasPermission('dashboard:view')")
public Result<DashboardDistributionRespVO> distribution() {
return Result.ok(dashboardService.distribution());
}
} }
@@ -0,0 +1,115 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.service.DramaClassificationService;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaClassificationRespVO;
import com.fruitshorts.content.vo.DramaClassificationSaveReqVO;
import com.fruitshorts.content.vo.DramaIdsReqVO;
import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 运营分类管理。分类与短剧类型(drama-categories)是两套独立概念,
* 分类可自定义增删,并关联任意多部短剧。
*/
@Tag(name = "后台-运营分类")
@RestController
@RequestMapping("/admin/drama-classifications")
@RequiredArgsConstructor
public class DramaClassificationController {
private final DramaClassificationService classificationService;
@Operation(summary = "分类列表(带关联数量)")
@GetMapping
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<List<DramaClassificationRespVO>> list() {
return Result.ok(classificationService.list());
}
@Operation(summary = "新建分类")
@PostMapping
@PreAuthorize("@ss.hasPermission('drama:create')")
@OperationLog(module = "内容管理", action = "新增分类")
public Result<Long> create(@Valid @RequestBody DramaClassificationSaveReqVO req) {
return Result.ok(classificationService.create(req));
}
@Operation(summary = "编辑分类")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "编辑分类")
public Result<Void> update(@PathVariable Long id,
@Valid @RequestBody DramaClassificationSaveReqVO req) {
classificationService.update(id, req);
return Result.ok();
}
@Operation(summary = "删除分类")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:delete')")
@OperationLog(module = "内容管理", action = "删除分类")
public Result<Void> delete(@PathVariable Long id) {
classificationService.delete(id);
return Result.ok();
}
@Operation(summary = "分类下已关联的短剧")
@GetMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> dramas(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(classificationService.pageDramas(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "尚未关联到该分类的短剧")
@GetMapping("/{id}/dramas/candidates")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> candidates(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(classificationService.pageCandidates(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "批量关联短剧")
@PostMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "分类关联短剧")
public Result<Integer> bindDramas(@PathVariable Long id,
@Valid @RequestBody DramaIdsReqVO req) {
return Result.ok(classificationService.bindDramas(id, req.getDramaIds()));
}
@Operation(summary = "移除分类下的短剧")
@DeleteMapping("/{id}/dramas/{dramaId}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "分类移除短剧")
public Result<Void> unbindDrama(@PathVariable Long id, @PathVariable Long dramaId) {
classificationService.unbindDrama(id, dramaId);
return Result.ok();
}
}
@@ -0,0 +1,115 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.service.DramaPlaylistCategoryService;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaIdsReqVO;
import com.fruitshorts.content.vo.DramaPlaylistCategoryRespVO;
import com.fruitshorts.content.vo.DramaPlaylistCategorySaveReqVO;
import com.fruitshorts.framework.log.OperationLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 剧单分类管理:分类直接关联短剧,没有「剧单」这一层。
* 与「类型」「分类管理」均无关。
*/
@Tag(name = "后台-剧单分类")
@RestController
@RequestMapping("/admin/drama-playlist-categories")
@RequiredArgsConstructor
public class DramaPlaylistCategoryController {
private final DramaPlaylistCategoryService categoryService;
@Operation(summary = "剧单分类列表")
@GetMapping
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<List<DramaPlaylistCategoryRespVO>> list() {
return Result.ok(categoryService.list());
}
@Operation(summary = "新建剧单分类")
@PostMapping
@PreAuthorize("@ss.hasPermission('drama:create')")
@OperationLog(module = "内容管理", action = "新增剧单分类")
public Result<Long> create(@Valid @RequestBody DramaPlaylistCategorySaveReqVO req) {
return Result.ok(categoryService.create(req));
}
@Operation(summary = "编辑剧单分类")
@PutMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "编辑剧单分类")
public Result<Void> update(@PathVariable Long id,
@Valid @RequestBody DramaPlaylistCategorySaveReqVO req) {
categoryService.update(id, req);
return Result.ok();
}
@Operation(summary = "删除剧单分类")
@DeleteMapping("/{id}")
@PreAuthorize("@ss.hasPermission('drama:delete')")
@OperationLog(module = "内容管理", action = "删除剧单分类")
public Result<Void> delete(@PathVariable Long id) {
categoryService.delete(id);
return Result.ok();
}
@Operation(summary = "分类下已关联的短剧")
@GetMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> dramas(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(categoryService.pageDramas(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "尚未关联到该分类的短剧")
@GetMapping("/{id}/dramas/candidates")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<PageResult<DramaBriefVO>> candidates(
@PathVariable Long id,
@RequestParam(required = false) String keyword,
@RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "10") int pageSize) {
return Result.ok(categoryService.pageCandidates(id, keyword, pageIndex, pageSize));
}
@Operation(summary = "批量关联短剧")
@PostMapping("/{id}/dramas")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "剧单分类关联短剧")
public Result<Integer> bindDramas(@PathVariable Long id,
@Valid @RequestBody DramaIdsReqVO req) {
return Result.ok(categoryService.bindDramas(id, req.getDramaIds()));
}
@Operation(summary = "移除分类下的短剧")
@DeleteMapping("/{id}/dramas/{dramaId}")
@PreAuthorize("@ss.hasPermission('drama:update')")
@OperationLog(module = "内容管理", action = "剧单分类移除短剧")
public Result<Void> unbindDrama(@PathVariable Long id, @PathVariable Long dramaId) {
categoryService.unbindDrama(id, dramaId);
return Result.ok();
}
}
@@ -0,0 +1,32 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.EpisodeTranscodeAdminService;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台剧集转码聚合查询。 */
@Tag(name = "后台-剧集转码")
@RestController
@RequestMapping("/admin/episodes")
@RequiredArgsConstructor
public class EpisodeTranscodeController {
private final EpisodeTranscodeAdminService service;
@Operation(summary = "查询分集转码聚合信息")
@GetMapping("/{id}/transcode")
@PreAuthorize("@ss.hasPermission('episode:list')")
public Result<EpisodeTranscodeRespVO> detail(@PathVariable Long id) {
return Result.ok(service.detail(id));
}
}
@@ -0,0 +1,47 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.system.service.LegalDocumentService;
import com.fruitshorts.system.vo.LegalDocumentVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 后台维护服务条款和隐私协议。公开页面由客户端服务按语言输出。
*/
@Tag(name = "后台-协议")
@RestController
@RequestMapping("/admin/legal-documents")
@RequiredArgsConstructor
public class LegalDocumentAdminController {
private final LegalDocumentService legalDocumentService;
@Operation(summary = "协议列表(服务条款、隐私协议,各含中英印尼语)")
@GetMapping
@PreAuthorize("@ss.hasAnyPermission('system:role','system:menu')")
public Result<List<LegalDocumentVO>> list() {
return Result.ok(legalDocumentService.list());
}
@Operation(summary = "保存协议")
@PutMapping
@PreAuthorize("@ss.hasPermission('system:role')")
@OperationLog(module = "后台管理", action = "修改服务条款或隐私协议")
public Result<Void> save(@RequestBody List<LegalDocumentVO> items) {
legalDocumentService.save(items);
return Result.ok();
}
}
@@ -5,12 +5,18 @@ package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.framework.security.ImpersonationGuard; import com.fruitshorts.framework.security.ImpersonationGuard;
import com.fruitshorts.framework.log.OperationLog;
import com.fruitshorts.media.config.MediaTranscodeProfile;
import com.fruitshorts.media.service.MediaService; import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.media.vo.MediaAssetRespVO; import com.fruitshorts.media.vo.MediaAssetRespVO;
import com.fruitshorts.media.vo.TranscodeTriggerRespVO;
import com.fruitshorts.media.vo.UploadCompleteReqVO; import com.fruitshorts.media.vo.UploadCompleteReqVO;
import com.fruitshorts.media.vo.UploadInitReqVO; import com.fruitshorts.media.vo.UploadInitReqVO;
import com.fruitshorts.media.vo.UploadInitRespVO; import com.fruitshorts.media.vo.UploadInitRespVO;
import com.fruitshorts.media.vo.UploadProgressRespVO; import com.fruitshorts.media.vo.UploadProgressRespVO;
import com.fruitshorts.admin.service.TranscodeBackfillAdminService;
import com.fruitshorts.admin.vo.TranscodeBackfillRespVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@@ -19,6 +25,7 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
@@ -35,6 +42,8 @@ import org.springframework.web.multipart.MultipartFile;
public class MediaController { public class MediaController {
private final MediaService mediaService; private final MediaService mediaService;
private final MediaTranscodeProfileService profileService;
private final TranscodeBackfillAdminService backfillAdminService;
@Operation(summary = "初始化分片上传") @Operation(summary = "初始化分片上传")
@PostMapping("/upload/init") @PostMapping("/upload/init")
@@ -78,4 +87,40 @@ public class MediaController {
public Result<MediaAssetRespVO> get(@PathVariable Long id) { public Result<MediaAssetRespVO> get(@PathVariable Long id) {
return Result.ok(mediaService.get(id)); return Result.ok(mediaService.get(id));
} }
@Operation(summary = "手动触发或重转媒资")
@PostMapping("/{id}/transcode")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "触发媒资转码")
public Result<TranscodeTriggerRespVO> transcode(@PathVariable Long id) {
ImpersonationGuard.rejectWrite();
return Result.ok(mediaService.triggerTranscode(id));
}
@Operation(summary = "读取转码档位配置")
@GetMapping("/transcode-profile")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<MediaTranscodeProfile> transcodeProfile() {
return Result.ok(profileService.readConfiguredProfile());
}
@Operation(summary = "保存转码档位配置")
@PutMapping("/transcode-profile")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "修改转码设置")
public Result<MediaTranscodeProfile> saveTranscodeProfile(
@Valid @RequestBody MediaTranscodeProfile profile) {
ImpersonationGuard.rejectWrite();
return Result.ok(profileService.save(profile));
}
@Operation(summary = "手动补齐转码:扫描缺产物/帧图的分集并入队")
@PostMapping("/transcode/backfill")
@PreAuthorize("@ss.hasPermission('episode:upload')")
@OperationLog(module = "后台管理", action = "补齐转码")
public Result<TranscodeBackfillRespVO> backfill(
@RequestParam(value = "batchSize", required = false) Integer batchSize) {
ImpersonationGuard.rejectWrite();
return Result.ok(backfillAdminService.runOnce(batchSize));
}
} }
@@ -0,0 +1,46 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 后台媒资转码产物只读查询。 */
@Tag(name = "后台-媒资转码产物")
@RestController
@RequestMapping("/admin/media")
@RequiredArgsConstructor
public class MediaTranscodeOutputController {
private final MediaTranscodeOutputService outputService;
@Operation(summary = "查询媒资清晰度产物")
@GetMapping("/{id}/renditions")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<List<MediaRenditionRespVO>> renditions(@PathVariable Long id) {
return Result.ok(outputService.renditions(id));
}
@Operation(summary = "分页查询媒资帧图产物")
@GetMapping("/{id}/thumbnails")
@PreAuthorize("@ss.hasPermission('episode:upload')")
public Result<MediaThumbnailRespVO> thumbnails(
@PathVariable Long id,
@RequestParam(defaultValue = "1") Integer pageIndex,
@RequestParam(defaultValue = "100") Integer pageSize) {
return Result.ok(outputService.thumbnails(id, pageIndex, pageSize));
}
}
@@ -0,0 +1,33 @@
// Author: fruit.com.cn
// 后台转码通知接口。
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeNoticeService;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import com.fruitshorts.common.pojo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** 后台转码通知。 */
@Tag(name = "后台-转码通知")
@RestController
@RequestMapping("/admin/notifications")
@RequiredArgsConstructor
public class TranscodeNoticeController {
private final TranscodeNoticeService transcodeNoticeService;
/** 转码中、成功、失败的角标和最近任务,含短剧与集数。 */
@Operation(summary = "转码通知(角标与最近任务)")
@GetMapping("/transcode")
@PreAuthorize("@ss.hasPermission('drama:list')")
public Result<TranscodeNoticeRespVO> transcode() {
return Result.ok(transcodeNoticeService.notices());
}
}
@@ -0,0 +1,62 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 按用户最近会话解析系统。同一设备优先,否则用仍有效的最近一次登录。
*/
@Service
@RequiredArgsConstructor
public class AppSessionSystemService {
private final AppUserSessionMapper sessionMapper;
/** 按用户分组,组内按最近活跃倒序。 */
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
Map<Long, List<AppUserSession>> grouped = new HashMap<>();
if (userIds == null || userIds.isEmpty()) {
return grouped;
}
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
.in(AppUserSession::getUserId, userIds)
.orderByDesc(AppUserSession::getLastActiveAt)
.orderByDesc(AppUserSession::getId));
for (AppUserSession session : sessions) {
grouped.computeIfAbsent(session.getUserId(), key -> new ArrayList<>()).add(session);
}
return grouped;
}
/** 观看记录优先匹配同一设备,其次取未吊销会话。 */
public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
if (sessions == null || sessions.isEmpty()) {
return null;
}
if (StringUtils.hasText(deviceId)) {
for (AppUserSession session : sessions) {
if (deviceId.equals(session.getDeviceId())) {
return session;
}
}
}
for (AppUserSession session : sessions) {
if (session.getRevokedAt() == null) {
return session;
}
}
return sessions.get(0);
}
}
@@ -3,6 +3,9 @@
package com.fruitshorts.admin.service; package com.fruitshorts.admin.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.admin.vo.DashboardDistributionRespVO;
import com.fruitshorts.admin.vo.DashboardTrendRespVO;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.commerce.dal.entity.CoinLedger; import com.fruitshorts.commerce.dal.entity.CoinLedger;
import com.fruitshorts.commerce.dal.entity.Entitlement; import com.fruitshorts.commerce.dal.entity.Entitlement;
import com.fruitshorts.commerce.dal.entity.Orders; import com.fruitshorts.commerce.dal.entity.Orders;
@@ -21,6 +24,8 @@ import com.fruitshorts.interaction.dal.entity.ContentReport;
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper; import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
import com.fruitshorts.interaction.dal.mapper.ContentReportMapper; import com.fruitshorts.interaction.dal.mapper.ContentReportMapper;
import com.fruitshorts.media.service.TranscodeService; import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import com.fruitshorts.playback.dal.entity.WatchHistory; import com.fruitshorts.playback.dal.entity.WatchHistory;
import com.fruitshorts.playback.dal.entity.WatchProgress; import com.fruitshorts.playback.dal.entity.WatchProgress;
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper; import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
@@ -41,6 +46,8 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
/** /**
* 运营大盘(只读聚合)。 * 运营大盘(只读聚合)。
* *
@@ -51,7 +58,11 @@ import java.util.Map;
* <ul> * <ul>
* <li>用户:`total` = app_user 未删除总数;`newToday`/`new7d` = 按 created_at 落在当天 / 近 7 天; * <li>用户:`total` = app_user 未删除总数;`newToday`/`new7d` = 按 created_at 落在当天 / 近 7 天;
* `active7d` = last_login_at 在近 7 天内(**不是 DAU**:真正的日活需要按天留存登录快照, * `active7d` = last_login_at 在近 7 天内(**不是 DAU**:真正的日活需要按天留存登录快照,
* 当前没有逐日快照数据源,见 notes);`banned`/`limited` = 按 status 计数。</li> * 当前没有逐日快照数据源,见 notes);`androidActive7d`/`iosActive7d` =
* `app_user_device` 中状态为 active、近 7 天有心跳的去重设备数;
* `retention1d` = 昨日注册用户中今天仍登录的比例,分母为 0 时返回 null;
* `retention7d` = 8 至 14 天前注册的用户中,近 7 天仍登录的比例,分母为 0 时返回 null;
* `banned`/`limited` = 按 status 计数。</li>
* <li>内容:短剧按 status 计数(`reviewing` 视为待审、`published` 视为已上线); * <li>内容:短剧按 status 计数(`reviewing` 视为待审、`published` 视为已上线);
* 剧集总数与已上线数;`episodeWithMedia` = video_url 非空的剧集数。</li> * 剧集总数与已上线数;`episodeWithMedia` = video_url 非空的剧集数。</li>
* <li>播放:`viewTotal`/`playTotal` = 短剧表上累计计数列的求和(累计口径,不限定时间范围); * <li>播放:`viewTotal`/`playTotal` = 短剧表上累计计数列的求和(累计口径,不限定时间范围);
@@ -69,6 +80,9 @@ import java.util.Map;
public class DashboardService { public class DashboardService {
private static final int ACTIVE_WINDOW_DAYS = 7; private static final int ACTIVE_WINDOW_DAYS = 7;
private static final int RETENTION_WINDOW_DAYS = 7;
private static final String PLATFORM_ANDROID = "ANDROID";
private static final String PLATFORM_IOS = "IOS";
private final AppUserMapper appUserMapper; private final AppUserMapper appUserMapper;
private final AppUserOtpMapper appUserOtpMapper; private final AppUserOtpMapper appUserOtpMapper;
@@ -83,6 +97,7 @@ public class DashboardService {
private final CoinLedgerMapper coinLedgerMapper; private final CoinLedgerMapper coinLedgerMapper;
private final EntitlementMapper entitlementMapper; private final EntitlementMapper entitlementMapper;
private final TranscodeService transcodeService; private final TranscodeService transcodeService;
private final JdbcTemplate jdbcTemplate;
public Map<String, Object> overview() { public Map<String, Object> overview() {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
@@ -101,17 +116,71 @@ public class DashboardService {
} }
/** 转码看板:队列积压与失败明细。 */ /** 转码看板:队列积压与失败明细。 */
public Map<String, Object> transcode() { public TranscodeDashboardRespVO transcode() {
Map<String, Object> data = new LinkedHashMap<>(); TranscodeDashboardRespVO data = new TranscodeDashboardRespVO();
data.put("generatedAt", LocalDateTime.now()); data.setGeneratedAt(LocalDateTime.now());
data.put("queue", transcodeService.stats()); data.setQueue(transcodeService.stats());
data.put("failedTasks", transcodeService.failedTasks(20)); data.setFailedTasks(transcodeService.failedTasks(20).stream()
data.put("notes", List.of( .map(TranscodeTaskRespVO::from)
.toList());
data.setNotes(List.of(
"queue 为累计口径(不限时间),反映当前积压与历史成败分布", "queue 为累计口径(不限时间),反映当前积压与历史成败分布",
"failedTasks 最多返回 20 条,按 id 倒序")); "failedTasks 最多返回 20 条,按 id 倒序"));
return data; return data;
} }
/** 近 7 天每日趋势,给折线图用。 */
public DashboardTrendRespVO trend() {
int days = 7;
LocalDate today = LocalDate.now();
List<String> dates = new ArrayList<>(days);
List<Long> newUsers = new ArrayList<>(days);
List<Long> playEvents = new ArrayList<>(days);
List<Long> newTranscodes = new ArrayList<>(days);
List<Long> transcodeSuccess = new ArrayList<>(days);
for (int i = days - 1; i >= 0; i--) {
LocalDate d = today.minusDays(i);
dates.add(d.toString());
newUsers.add(countForDate("SELECT COUNT(*) FROM app_user WHERE deleted = 0 AND DATE(created_at) = ?", d));
playEvents.add(countForDate("SELECT COUNT(*) FROM watch_history WHERE DATE(watched_at) = ?", d));
newTranscodes.add(countForDate("SELECT COUNT(*) FROM transcode_task WHERE DATE(created_at) = ?", d));
transcodeSuccess.add(countForDate("SELECT COUNT(*) FROM transcode_task WHERE status = 'SUCCESS' AND DATE(created_at) = ?", d));
}
return new DashboardTrendRespVO(dates, newUsers, playEvents, newTranscodes, transcodeSuccess);
}
/** 各域状态分布,给饼图用。 */
public DashboardDistributionRespVO distribution() {
DashboardDistributionRespVO vo = new DashboardDistributionRespVO();
vo.setDramaStatus(groupBy("SELECT status, COUNT(*) FROM drama WHERE deleted = 0 GROUP BY status"));
vo.setTranscodeStatus(groupBy("SELECT status, COUNT(*) FROM transcode_task GROUP BY status"));
vo.setEpisodeMedia(groupBy("""
SELECT CASE WHEN video_url IS NOT NULL AND video_url <> '' THEN '有片源' ELSE '无片源' END AS bucket,
COUNT(*) FROM drama_episode WHERE deleted = 0 GROUP BY bucket"""));
List<DashboardDistributionRespVO.Item> pending = new ArrayList<>();
pending.add(new DashboardDistributionRespVO.Item("评论待审", orZero(commentMapper.selectCount(
Wrappers.<ContentComment>lambdaQuery().eq(ContentComment::getStatus, "pending")))));
pending.add(new DashboardDistributionRespVO.Item("举报待处理", orZero(reportMapper.selectCount(
Wrappers.<ContentReport>lambdaQuery().eq(ContentReport::getStatus, "pending")))));
vo.setPendingModeration(pending);
return vo;
}
/** 按日期查计数,空结果返回 0。 */
private long countForDate(String sql, LocalDate date) {
Long count = jdbcTemplate.queryForObject(sql, Long.class, date);
return count == null ? 0L : count;
}
/** 两列 GROUP BY 查询返回 Map<key, count>。 */
private Map<String, Long> groupBy(String sql) {
Map<String, Long> result = new LinkedHashMap<>();
jdbcTemplate.query(sql, rs -> {
result.put(rs.getString(1), rs.getLong(2));
});
return result;
}
private Map<String, Object> userMetrics(LocalDateTime todayStart, LocalDateTime sevenDaysAgo) { private Map<String, Object> userMetrics(LocalDateTime todayStart, LocalDateTime sevenDaysAgo) {
Map<String, Object> user = new LinkedHashMap<>(); Map<String, Object> user = new LinkedHashMap<>();
user.put("total", countUser(Wrappers.<AppUser>lambdaQuery())); user.put("total", countUser(Wrappers.<AppUser>lambdaQuery()));
@@ -125,9 +194,47 @@ public class DashboardService {
user.put("limited", countUser(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getStatus, "limited"))); user.put("limited", countUser(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getStatus, "limited")));
user.put("deactivated", countUser(Wrappers.<AppUser>lambdaQuery() user.put("deactivated", countUser(Wrappers.<AppUser>lambdaQuery()
.eq(AppUser::getStatus, "deactivated"))); .eq(AppUser::getStatus, "deactivated")));
putActiveDevices(user, sevenDaysAgo);
user.put("retention1d", retentionRate(todayStart.minusDays(1), todayStart, todayStart));
user.put("retention7d", retentionRate(
todayStart.minusDays(RETENTION_WINDOW_DAYS * 2L),
todayStart.minusDays(RETENTION_WINDOW_DAYS),
sevenDaysAgo));
return user; return user;
} }
/** 近 7 天仍活跃的安卓、iOS 设备,按设备号去重。 */
private void putActiveDevices(Map<String, Object> user, LocalDateTime since) {
Map<String, Long> counts = new LinkedHashMap<>();
jdbcTemplate.query("""
SELECT UPPER(platform), COUNT(DISTINCT device_id)
FROM app_user_device
WHERE deleted = 0 AND status = 'active' AND last_seen_at >= ?
GROUP BY UPPER(platform)
""", rs -> {
counts.put(rs.getString(1), rs.getLong(2));
}, since);
user.put("androidActive7d", counts.getOrDefault(PLATFORM_ANDROID, 0L));
user.put("iosActive7d", counts.getOrDefault(PLATFORM_IOS, 0L));
}
/** 队列留存率。注册队列为空时返回 null,避免把没有样本显示成 0%。 */
private Double retentionRate(LocalDateTime cohortStart, LocalDateTime cohortEnd, LocalDateTime returnedSince) {
Long cohort = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM app_user
WHERE deleted = 0 AND created_at >= ? AND created_at < ?
""", Long.class, cohortStart, cohortEnd);
if (cohort == null || cohort == 0L) {
return null;
}
Long returned = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM app_user
WHERE deleted = 0 AND created_at >= ? AND created_at < ? AND last_login_at >= ?
""", Long.class, cohortStart, cohortEnd, returnedSince);
long back = returned == null ? 0L : returned;
return Math.round(back * 1000.0 / cohort) / 1000.0;
}
private Map<String, Object> contentMetrics() { private Map<String, Object> contentMetrics() {
Map<String, Object> content = new LinkedHashMap<>(); Map<String, Object> content = new LinkedHashMap<>();
content.put("dramaTotal", dramaMapper.selectCount(null)); content.put("dramaTotal", dramaMapper.selectCount(null));
@@ -205,12 +312,12 @@ public class DashboardService {
private Map<String, Object> costMetrics(LocalDateTime sevenDaysAgo) { private Map<String, Object> costMetrics(LocalDateTime sevenDaysAgo) {
Map<String, Object> cost = new LinkedHashMap<>(); Map<String, Object> cost = new LinkedHashMap<>();
Map<String, Object> queue = transcodeService.stats(); TranscodeQueueStatsVO queue = transcodeService.stats();
cost.put("transcodeQueued", queue.get("queued")); cost.put("transcodeQueued", queue.getQueued());
cost.put("transcodeRunning", queue.get("running")); cost.put("transcodeRunning", queue.getRunning());
cost.put("transcodeFailed", queue.get("failed")); cost.put("transcodeFailed", queue.getFailed());
cost.put("transcodeSuccess", queue.get("success")); cost.put("transcodeSuccess", queue.getSuccess());
cost.put("renditions", queue.get("renditions")); cost.put("renditions", queue.getRenditions());
cost.put("otpSent7d", appUserOtpMapper.selectCount(Wrappers.<AppUserOtp>lambdaQuery() cost.put("otpSent7d", appUserOtpMapper.selectCount(Wrappers.<AppUserOtp>lambdaQuery()
.ge(AppUserOtp::getCreatedAt, sevenDaysAgo))); .ge(AppUserOtp::getCreatedAt, sevenDaysAgo)));
cost.put("cdnTrafficBytes", null); cost.put("cdnTrafficBytes", null);
@@ -222,6 +329,8 @@ public class DashboardService {
List<String> notes = new ArrayList<>(); List<String> notes = new ArrayList<>();
notes.add("DAU 暂无数据源:需要按天留存登录快照(ops_daily_stat 已建表但当前无产出)," notes.add("DAU 暂无数据源:需要按天留存登录快照(ops_daily_stat 已建表但当前无产出),"
+ "现以 active7d(近 7 天登录过)近似"); + "现以 active7d(近 7 天登录过)近似");
notes.add("androidActive7d / iosActive7d 是近 7 天 last_seen_at 仍活跃的去重设备,不是安装量");
notes.add("retention1d 是昨日注册且今天仍登录的比例;retention7d 是 8 至 14 天前注册、近 7 天仍登录的比例;队列为空时为 null");
notes.add("CDN 流量与带宽成本暂无数据源:需接入 CDN 账单或访问日志,cdnTrafficBytes 恒为 null"); notes.add("CDN 流量与带宽成本暂无数据源:需接入 CDN 账单或访问日志,cdnTrafficBytes 恒为 null");
notes.add("收入金额在商店未接入前恒为 0:订单表无真实商店订单,金币解锁收入请参考 coinConsumed"); notes.add("收入金额在商店未接入前恒为 0:订单表无真实商店订单,金币解锁收入请参考 coinConsumed");
notes.add("viewTotal/playTotal 是短剧表上的累计计数,与 playEvents7d 的流水口径不可相加"); notes.add("viewTotal/playTotal 是短剧表上的累计计数,与 playEvents7d 的流水口径不可相加");
@@ -0,0 +1,103 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Locale;
/** 聚合剧集与媒资转码产物,供后台编辑页一次读取。 */
@Service
@RequiredArgsConstructor
public class EpisodeTranscodeAdminService {
private static final String STATUS_EPISODE_NOT_FOUND = "EPISODE_NOT_FOUND";
private static final String STATUS_NO_VIDEO = "NO_VIDEO";
private static final String STATUS_NO_MEDIA_ASSET = "NO_MEDIA_ASSET";
private static final String STATUS_NO_TASK = "NO_TASK";
private static final String REASON_EPISODE_NOT_FOUND = "分集不存在或已删除";
private static final String REASON_NO_VIDEO = "分集未配置视频";
private static final String REASON_NO_MEDIA_ASSET = "未找到分集视频对应的媒资";
private static final int THUMBNAIL_PAGE_INDEX = 1;
private static final int THUMBNAIL_PAGE_SIZE = 100;
private final DramaEpisodeMapper episodeMapper;
private final MediaTranscodeOutputService outputService;
public EpisodeTranscodeRespVO detail(Long episodeId) {
DramaEpisode episode = episodeId == null ? null : episodeMapper.selectById(episodeId);
if (episode == null) {
return empty(episodeId, STATUS_EPISODE_NOT_FOUND, REASON_EPISODE_NOT_FOUND);
}
boolean hasVideoAsset = episode.getVideoAssetId() != null
&& episode.getVideoAssetId() > 0;
if (!StringUtils.hasText(episode.getVideoUrl()) && !hasVideoAsset) {
return empty(episodeId, STATUS_NO_VIDEO, REASON_NO_VIDEO);
}
Long mediaAssetId = outputService.resolveMediaAssetId(episode.getVideoUrl());
if ((mediaAssetId == null || mediaAssetId <= 0) && hasVideoAsset
&& outputService.mediaAssetExists(episode.getVideoAssetId())) {
mediaAssetId = episode.getVideoAssetId();
}
if (mediaAssetId == null || mediaAssetId <= 0) {
return empty(episodeId, STATUS_NO_MEDIA_ASSET, REASON_NO_MEDIA_ASSET);
}
EpisodeTranscodeRespVO result = new EpisodeTranscodeRespVO();
result.setEpisodeId(idString(episodeId));
result.setMediaAssetId(idString(mediaAssetId));
result.setRenditions(outputService.renditionsForMediaAssetId(mediaAssetId));
result.setThumbnails(outputService.thumbnailForEpisode(
episodeId, mediaAssetId, THUMBNAIL_PAGE_INDEX, THUMBNAIL_PAGE_SIZE));
TranscodeTaskRespVO task = outputService.latestTask(mediaAssetId);
if (task == null) {
result.setStatus(taskStatusOf(episode));
result.setProgress(0);
result.setRetryCount(0);
result.setErrorMsg("");
result.setUpdatedAt(episode.getUpdatedAt());
return result;
}
result.setTaskId(idString(task.getId()));
result.setStatus(task.getStatus());
result.setProgress(task.getProgress());
result.setRetryCount(task.getRetryCount());
result.setErrorMsg(task.getErrorMsg());
result.setUpdatedAt(task.getUpdatedAt());
return result;
}
private EpisodeTranscodeRespVO empty(Long episodeId, String status, String reason) {
EpisodeTranscodeRespVO result = new EpisodeTranscodeRespVO();
result.setEpisodeId(idString(episodeId));
result.setStatus(status);
result.setProgress(0);
result.setRetryCount(0);
result.setErrorMsg(reason);
result.setRenditions(List.of());
result.setThumbnails(MediaThumbnailRespVO.empty(
null, episodeId, MediaThumbnailRespVO.STATUS_EMPTY,
THUMBNAIL_PAGE_INDEX, THUMBNAIL_PAGE_SIZE));
return result;
}
private String idString(Long id) {
return id == null ? null : String.valueOf(id);
}
private String taskStatusOf(DramaEpisode episode) {
return StringUtils.hasText(episode.getTranscodeStatus())
? episode.getTranscodeStatus().toUpperCase(Locale.ROOT)
: STATUS_NO_TASK;
}
}
@@ -0,0 +1,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);
}
}
@@ -17,6 +17,7 @@ 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.AppUser; import com.fruitshorts.user.dal.entity.AppUser;
import com.fruitshorts.user.dal.entity.AppUserSession;
import com.fruitshorts.user.dal.mapper.AppUserMapper; import com.fruitshorts.user.dal.mapper.AppUserMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -46,6 +47,7 @@ public class WatchHistoryAdminService {
private final AppUserMapper appUserMapper; private final AppUserMapper appUserMapper;
private final DramaMapper dramaMapper; private final DramaMapper dramaMapper;
private final DramaEpisodeMapper dramaEpisodeMapper; private final DramaEpisodeMapper dramaEpisodeMapper;
private final AppSessionSystemService sessionSystem;
/** 按后台筛选条件分页查询观看记录。 */ /** 按后台筛选条件分页查询观看记录。 */
public PageResult<AdminWatchHistoryVO> page(WatchHistoryQueryReqVO req) { public PageResult<AdminWatchHistoryVO> page(WatchHistoryQueryReqVO req) {
@@ -125,10 +127,13 @@ public class WatchHistoryAdminService {
Map<Long, AppUser> users = loadUsers(rows); Map<Long, AppUser> users = loadUsers(rows);
Map<Long, Drama> dramas = loadDramas(rows); Map<Long, Drama> dramas = loadDramas(rows);
Map<Long, DramaEpisode> episodes = loadEpisodes(rows); Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
rows.stream().map(WatchHistory::getUserId).distinct().toList());
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())));
} }
return list; return list;
} }
@@ -161,7 +166,7 @@ public class WatchHistoryAdminService {
} }
private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama, private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama,
DramaEpisode episode) { DramaEpisode episode, AppUserSession session) {
AdminWatchHistoryVO vo = new AdminWatchHistoryVO(); AdminWatchHistoryVO vo = new AdminWatchHistoryVO();
vo.setId(row.getId()); vo.setId(row.getId());
vo.setUserId(row.getUserId()); vo.setUserId(row.getUserId());
@@ -172,6 +177,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) {
vo.setPlatform(session.getPlatform());
vo.setOsVersion(session.getOsVersion());
}
long position = row.getPositionMs() == null ? 0L : row.getPositionMs(); long position = row.getPositionMs() == null ? 0L : row.getPositionMs();
long duration = row.getDurationMs() == null ? 0L : row.getDurationMs(); long duration = row.getDurationMs() == null ? 0L : row.getDurationMs();
vo.setFinished(duration > 0L && position + FINISHED_TOLERANCE_MS >= duration); vo.setFinished(duration > 0L && position + FINISHED_TOLERANCE_MS >= duration);
@@ -29,5 +29,9 @@ public class AdminWatchHistoryVO {
private Boolean finished; private Boolean finished;
private String source; private String source;
private String deviceId; private String deviceId;
/** ANDROID / IOS / WEB,来自该次设备的登录会话。 */
private String platform;
/** 系统版本,例如 Android 16。 */
private String osVersion;
private LocalDateTime watchedAt; private LocalDateTime watchedAt;
} }
@@ -28,5 +28,9 @@ public class AppUserWatchHistoryVO {
private Boolean finished; private Boolean finished;
private String source; private String source;
private String deviceId; private String deviceId;
/** ANDROID / IOS / WEB,来自该次设备的登录会话。 */
private String platform;
/** 系统版本。 */
private String osVersion;
private LocalDateTime watchedAt; private LocalDateTime watchedAt;
} }
@@ -0,0 +1,39 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/** 运营大盘分布(给饼图用)。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DashboardDistributionRespVO {
/** 短剧状态分布:key = 状态码,value = 数量;含 total 汇总。 */
private Map<String, Long> dramaStatus;
/** 转码任务状态分布。 */
private Map<String, Long> transcodeStatus;
/** 有片源 / 无片源剧集分布。 */
private Map<String, Long> episodeMedia;
/** 互动待处理:评论待审、举报待审。 */
private List<Item> pendingModeration;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Item {
private String label;
private Long value;
}
}
@@ -0,0 +1,31 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/** 运营大盘趋势(近 N 天每日数据,给折线图用)。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DashboardTrendRespVO {
/** 日期标签,格式 yyyy-MM-dd,从最早到最新。 */
private List<String> dates;
/** 每日新增用户数(与 dates 对齐)。 */
private List<Long> newUsers;
/** 每日播放事件数(watch_history 行数,与 dates 对齐)。 */
private List<Long> playEvents;
/** 每日新增转码任务数(transcode_task 行数,与 dates 对齐)。 */
private List<Long> newTranscodes;
/** 每日转码成功数(与 dates 对齐)。 */
private List<Long> transcodeSuccess;
}
@@ -0,0 +1,28 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 后台剧集编辑页一次性获取的转码状态。 */
@Data
@Schema(description = "分集转码聚合信息")
public class EpisodeTranscodeRespVO {
private String episodeId;
private String mediaAssetId;
private String taskId;
private String status;
private Integer progress;
private Integer retryCount;
private String errorMsg;
private LocalDateTime updatedAt;
private List<MediaRenditionRespVO> renditions = List.of();
private MediaThumbnailRespVO thumbnails;
}
@@ -0,0 +1,32 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/** 一轮转码补齐巡检的结果。 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TranscodeBackfillRespVO {
/** 本轮实际补入队的分集数。 */
private int triggered;
/** 补入队的分集与任务明细。 */
private List<Item> items;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Item {
private String episodeId;
private String taskId;
}
}
@@ -0,0 +1,22 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.vo;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 后台转码看板强类型响应。 */
@Data
@Schema(description = "转码看板")
public class TranscodeDashboardRespVO {
private LocalDateTime generatedAt;
private TranscodeQueueStatsVO queue;
private List<TranscodeTaskRespVO> failedTasks = List.of();
private List<String> notes = List.of();
}
@@ -0,0 +1,35 @@
// Author: fruit.com.cn
// 转码通知响应:角标数量和最近任务。
package com.fruitshorts.admin.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/** 转码通知:角标数量和最近任务。 */
@Data
public class TranscodeNoticeRespVO {
private long running;
private long success;
private long failed;
private List<Item> runningList = new ArrayList<>();
private List<Item> successList = new ArrayList<>();
private List<Item> failedList = new ArrayList<>();
/** 一条转码通知,带短剧和集数。 */
@Data
public static class Item {
private Long id;
private String status;
private String dramaTitle;
private Integer episodeNo;
private String episodeTitle;
private Integer progress;
private String errorMsg;
private LocalDateTime updatedAt;
}
}
@@ -0,0 +1,52 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.DashboardService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.TranscodeDashboardRespVO;
import com.fruitshorts.media.vo.TranscodeQueueStatsVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class DashboardTranscodeContractTest {
private DashboardService dashboardService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
dashboardService = mock(DashboardService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new DashboardAdminController(dashboardService));
}
@Test
void should_return_typed_queue_and_failed_tasks() throws Exception {
TranscodeQueueStatsVO queue = new TranscodeQueueStatsVO(
10L, 2L, 1L, 5L, 1L, 1L, 20L);
TranscodeDashboardRespVO vo = new TranscodeDashboardRespVO();
vo.setQueue(queue);
vo.setFailedTasks(List.of());
vo.setNotes(List.of("queue total"));
given(dashboardService.transcode()).willReturn(vo);
mockMvc.perform(get("/admin/dashboard/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.queue.total").value(10))
.andExpect(jsonPath("$.data.queue.queued").value(2))
.andExpect(jsonPath("$.data.queue.running").value(1))
.andExpect(jsonPath("$.data.queue.success").value(5))
.andExpect(jsonPath("$.data.queue.failed").value(1))
.andExpect(jsonPath("$.data.failedTasks").isArray());
}
}
@@ -0,0 +1,69 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.EpisodeTranscodeAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.EpisodeTranscodeRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class EpisodeTranscodeContractTest {
private EpisodeTranscodeAdminService service;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
service = mock(EpisodeTranscodeAdminService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new EpisodeTranscodeController(service));
}
@Test
void should_return_aggregated_episode_transcode_state() throws Exception {
String episodeId = "2113150431755636737";
String mediaAssetId = "2113150398670966786";
String taskId = "2113150398935207938";
EpisodeTranscodeRespVO vo = new EpisodeTranscodeRespVO();
vo.setEpisodeId(episodeId);
vo.setMediaAssetId(mediaAssetId);
vo.setTaskId(taskId);
vo.setStatus("SUCCESS");
vo.setProgress(100);
vo.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 15, 10));
given(service.detail(Long.parseLong(episodeId))).willReturn(vo);
mockMvc.perform(get("/admin/episodes/" + episodeId + "/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.episodeId").value(episodeId))
.andExpect(jsonPath("$.data.mediaAssetId").value(mediaAssetId))
.andExpect(jsonPath("$.data.taskId").value(taskId))
.andExpect(jsonPath("$.data.status").value("SUCCESS"))
.andExpect(jsonPath("$.data.progress").value(100))
.andExpect(jsonPath("$.data.updatedAt").value("2026-10-22T15:10:00"));
}
@Test
void should_return_explicit_empty_state_when_episode_has_no_video() throws Exception {
EpisodeTranscodeRespVO vo = new EpisodeTranscodeRespVO();
vo.setEpisodeId("31");
vo.setStatus("NO_VIDEO");
given(service.detail(31L)).willReturn(vo);
mockMvc.perform(get("/admin/episodes/31/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("NO_VIDEO"))
.andExpect(jsonPath("$.data.renditions").isEmpty());
}
}
@@ -0,0 +1,90 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaRenditionRespVO;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class MediaTranscodeOutputContractTest {
private MediaTranscodeOutputService outputService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
outputService = mock(MediaTranscodeOutputService.class);
mockMvc = ControllerContractSupport.mockMvcOf(
new MediaTranscodeOutputController(outputService));
}
@Test
void should_return_typed_rendition_list() throws Exception {
MediaRenditionRespVO vo = new MediaRenditionRespVO();
vo.setQuality("1080p");
vo.setQualityName("1080P");
vo.setResolution("1920x1080");
vo.setVideoBitrateKbps(5000);
vo.setVideoCodec("H.264");
vo.setAudioCodec("AAC");
vo.setContainer("HLS");
vo.setHlsUrl("/files/master.m3u8");
vo.setSizeBytes(4096L);
vo.setStatus("ready");
given(outputService.renditions(88L)).willReturn(List.of(vo));
mockMvc.perform(get("/admin/media/88/renditions"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data[0].quality").value("1080p"))
.andExpect(jsonPath("$.data[0].resolution").value("1920x1080"))
.andExpect(jsonPath("$.data[0].videoBitrateKbps").value(5000))
.andExpect(jsonPath("$.data[0].hlsUrl").value("/files/master.m3u8"));
}
@Test
void should_return_not_found_for_missing_media() throws Exception {
given(outputService.renditions(404L))
.willThrow(new ServiceException(ErrorCode.DATA_NOT_FOUND, "媒资不存在"));
mockMvc.perform(get("/admin/media/404/renditions"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode()))
.andExpect(jsonPath("$.message").value("媒资不存在"));
}
@Test
void should_return_empty_thumbnail_status_without_error() throws Exception {
MediaThumbnailRespVO vo = new MediaThumbnailRespVO();
vo.setStatus("EMPTY");
vo.setPageIndex(1);
vo.setPageSize(100);
vo.setFrames(PageResult.empty());
given(outputService.thumbnails(88L, 1, 100)).willReturn(vo);
mockMvc.perform(get("/admin/media/88/thumbnails"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.status").value("EMPTY"))
.andExpect(jsonPath("$.data.frames.total").value(0))
.andExpect(jsonPath("$.data.frames.list").isEmpty());
verify(outputService).thumbnails(88L, 1, 100);
}
}
@@ -0,0 +1,100 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.media.config.MediaTranscodeProfile;
import com.fruitshorts.media.config.TranscodeProperties;
import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.system.service.ConfigService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 后台转码配置接口:默认值、非法拒绝与成功落库。
*/
class MediaTranscodeProfileContractTest {
private ConfigService configService;
private ObjectMapper objectMapper;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
configService = mock(ConfigService.class);
objectMapper = new ObjectMapper();
MediaTranscodeProfileService profileService = new MediaTranscodeProfileService(
configService, objectMapper, new TranscodeProperties());
MediaController controller = new MediaController(
mock(MediaService.class), profileService,
mock(com.fruitshorts.admin.service.TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller);
given(configService.get(eq(MediaTranscodeProfileService.CONFIG_KEY), anyString()))
.willReturn("");
}
@Test
void should_return_default_profile_when_config_is_missing() throws Exception {
mockMvc.perform(get("/admin/media/transcode-profile"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.segmentSeconds").value(6))
.andExpect(jsonPath("$.data.ladder.length()").value(4))
.andExpect(jsonPath("$.data.ladder[0].quality").value("360p"))
.andExpect(jsonPath("$.data.sprite.columns").value(10));
}
@Test
void should_reject_illegal_profile_without_writing_config() throws Exception {
MediaTranscodeProfile profile = new MediaTranscodeProfile();
profile.getLadder().get(0).setWidth(641);
mockMvc.perform(put("/admin/media/transcode-profile")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(profile)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("宽高必须为正偶数"));
verify(configService, never()).update(any());
}
@Test
void should_persist_profile_when_request_is_valid() throws Exception {
MediaTranscodeProfile profile = new MediaTranscodeProfile();
profile.setSegmentSeconds(4);
mockMvc.perform(put("/admin/media/transcode-profile")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(profile)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.segmentSeconds").value(4));
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
verify(configService).update(captor.capture());
assertThat(captor.getValue().get(MediaTranscodeProfileService.CONFIG_KEY))
.contains("\"segmentSeconds\":4");
}
}
@@ -0,0 +1,65 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeBackfillAdminService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.media.service.MediaService;
import com.fruitshorts.media.service.MediaTranscodeProfileService;
import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.media.vo.TranscodeTriggerRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* 后台手动触发转码的最小契约。
*/
class MediaTranscodeTriggerContractTest {
private MediaService mediaService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mediaService = mock(MediaService.class);
MediaController controller = new MediaController(
mediaService, mock(MediaTranscodeProfileService.class),
mock(TranscodeBackfillAdminService.class));
mockMvc = ControllerContractSupport.mockMvcOf(controller);
}
@Test
void should_return_task_id_and_status_when_triggering_transcode() throws Exception {
given(mediaService.triggerTranscode(88L))
.willReturn(new TranscodeTriggerRespVO(100L, TranscodeService.STATUS_QUEUED));
mockMvc.perform(post("/admin/media/88/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.taskId").value("100"))
.andExpect(jsonPath("$.data.status").value(TranscodeService.STATUS_QUEUED));
verify(mediaService).triggerTranscode(88L);
}
@Test
void should_keep_not_found_semantics_when_media_does_not_exist() throws Exception {
given(mediaService.triggerTranscode(404L))
.willThrow(new ServiceException(ErrorCode.DATA_NOT_FOUND, "媒资不存在"));
mockMvc.perform(post("/admin/media/404/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(ErrorCode.DATA_NOT_FOUND.getCode()))
.andExpect(jsonPath("$.message").value("媒资不存在"));
}
}
@@ -0,0 +1,53 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.controller;
import com.fruitshorts.admin.service.TranscodeNoticeService;
import com.fruitshorts.admin.support.ControllerContractSupport;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class TranscodeNoticeContractTest {
private TranscodeNoticeService transcodeNoticeService;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
transcodeNoticeService = mock(TranscodeNoticeService.class);
mockMvc = ControllerContractSupport.mockMvcOf(new TranscodeNoticeController(transcodeNoticeService));
}
@Test
void should_return_drama_and_episode_when_transcode_notice_is_requested() throws Exception {
TranscodeNoticeRespVO data = new TranscodeNoticeRespVO();
data.setRunning(1L);
data.setSuccess(2L);
data.setFailed(3L);
TranscodeNoticeRespVO.Item item = new TranscodeNoticeRespVO.Item();
item.setDramaTitle("重生");
item.setEpisodeNo(4);
item.setEpisodeTitle("第4集");
data.setFailedList(List.of(item));
given(transcodeNoticeService.notices()).willReturn(data);
mockMvc.perform(get("/admin/notifications/transcode"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.running").value(1))
.andExpect(jsonPath("$.data.success").value(2))
.andExpect(jsonPath("$.data.failed").value(3))
.andExpect(jsonPath("$.data.failedList[0].dramaTitle").value("重生"))
.andExpect(jsonPath("$.data.failedList[0].episodeNo").value(4))
.andExpect(jsonPath("$.data.failedList[0].episodeTitle").value("第4集"));
}
}
@@ -0,0 +1,48 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.user.dal.entity.AppUserSession;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/** 观看记录匹配登录系统。 */
class AppSessionSystemServiceTest {
private final AppSessionSystemService service = new AppSessionSystemService(null);
@Test
void should_use_same_device_session_when_watch_history_has_device() {
AppUserSession older = session("device-1", "ANDROID", "14", null);
AppUserSession newer = session("device-2", "IOS", "18", null);
AppUserSession matched = service.match(List.of(newer, older), "device-1");
assertThat(matched.getPlatform()).isEqualTo("ANDROID");
assertThat(matched.getOsVersion()).isEqualTo("14");
}
@Test
void should_use_active_session_when_device_does_not_match() {
AppUserSession revoked = session("device-9", "WEB", "1", LocalDateTime.now());
AppUserSession active = session("device-2", "IOS", "18", null);
AppUserSession matched = service.match(List.of(revoked, active), "missing");
assertThat(matched.getPlatform()).isEqualTo("IOS");
}
private AppUserSession session(String deviceId, String platform, String osVersion,
LocalDateTime revokedAt) {
AppUserSession session = new AppUserSession();
session.setDeviceId(deviceId);
session.setPlatform(platform);
session.setOsVersion(osVersion);
session.setRevokedAt(revokedAt);
return session;
}
}
@@ -0,0 +1,116 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.media.service.MediaTranscodeOutputService;
import com.fruitshorts.media.vo.MediaThumbnailRespVO;
import com.fruitshorts.media.vo.TranscodeTaskRespVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.time.LocalDateTime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
class EpisodeTranscodeAdminServiceTest {
private static final Long EPISODE_ID = 2113150431755636737L;
private static final Long MEDIA_ASSET_ID = 2113150398670966786L;
private static final Long TASK_ID = 2113150398935207938L;
private DramaEpisodeMapper episodeMapper;
private MediaTranscodeOutputService outputService;
private EpisodeTranscodeAdminService service;
@BeforeEach
void setUp() {
episodeMapper = mock(DramaEpisodeMapper.class);
outputService = mock(MediaTranscodeOutputService.class);
service = new EpisodeTranscodeAdminService(episodeMapper, outputService);
}
@Test
void should_return_episode_not_found_state_without_aggregating_media() {
given(episodeMapper.selectById(404L)).willReturn(null);
var result = service.detail(404L);
assertThat(result.getStatus()).isEqualTo("EPISODE_NOT_FOUND");
assertThat(result.getEpisodeId()).isEqualTo("404");
assertThat(result.getRenditions()).isEmpty();
verifyNoInteractions(outputService);
}
@Test
void should_return_no_video_state_when_episode_video_url_is_blank() {
DramaEpisode episode = new DramaEpisode();
episode.setId(31L);
episode.setVideoUrl("");
given(episodeMapper.selectById(31L)).willReturn(episode);
var result = service.detail(31L);
assertThat(result.getStatus()).isEqualTo("NO_VIDEO");
assertThat(result.getRenditions()).isEmpty();
verifyNoInteractions(outputService);
}
@Test
void should_return_exact_snowflake_media_asset_id_as_string() {
DramaEpisode episode = episode(MEDIA_ASSET_ID);
given(episodeMapper.selectById(EPISODE_ID)).willReturn(episode);
given(outputService.resolveMediaAssetId(episode.getVideoUrl())).willReturn(null);
given(outputService.mediaAssetExists(MEDIA_ASSET_ID)).willReturn(true);
given(outputService.renditionsForMediaAssetId(MEDIA_ASSET_ID)).willReturn(List.of());
given(outputService.thumbnailForEpisode(
EPISODE_ID, MEDIA_ASSET_ID, 1, 100))
.willReturn(MediaThumbnailRespVO.empty(
MEDIA_ASSET_ID, EPISODE_ID,
MediaThumbnailRespVO.STATUS_EMPTY, 1, 100));
TranscodeTaskRespVO task = new TranscodeTaskRespVO();
task.setId(TASK_ID);
task.setMediaAssetId(MEDIA_ASSET_ID);
task.setStatus("SUCCESS");
task.setProgress(100);
task.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 15, 10));
given(outputService.latestTask(MEDIA_ASSET_ID)).willReturn(task);
var result = service.detail(EPISODE_ID);
assertThat(result.getEpisodeId()).isEqualTo("2113150431755636737");
assertThat(result.getMediaAssetId()).isEqualTo("2113150398670966786");
assertThat(result.getTaskId()).isEqualTo("2113150398935207938");
assertThat(result.getUpdatedAt()).isEqualTo(task.getUpdatedAt());
}
@Test
void should_return_explicit_empty_state_when_episode_media_is_missing() {
DramaEpisode episode = episode(MEDIA_ASSET_ID);
given(episodeMapper.selectById(EPISODE_ID)).willReturn(episode);
given(outputService.mediaAssetExists(MEDIA_ASSET_ID)).willReturn(false);
given(outputService.resolveMediaAssetId(episode.getVideoUrl())).willReturn(null);
var result = service.detail(EPISODE_ID);
assertThat(result.getMediaAssetId()).isNull();
assertThat(result.getStatus()).isEqualTo("NO_MEDIA_ASSET");
assertThat(result.getErrorMsg()).isNotBlank();
assertThat(result.getRenditions()).isEmpty();
}
private DramaEpisode episode(Long videoAssetId) {
DramaEpisode episode = new DramaEpisode();
episode.setId(EPISODE_ID);
episode.setDramaId(7L);
episode.setDurationSec(120);
episode.setVideoAssetId(videoAssetId);
episode.setVideoUrl("/files/episode/202610/video.mp4");
return episode;
}
}
@@ -0,0 +1,67 @@
// Author: fruit.com.cn
package com.fruitshorts.admin.service;
import com.fruitshorts.admin.vo.TranscodeNoticeRespVO;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class TranscodeNoticeServiceTest {
@Test
void should_attach_drama_and_episode_when_failed_tasks_are_loaded() throws Exception {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
doAnswer(invocation -> {
assertTrue(invocation.getArgument(0, String.class).contains("?"));
return null;
}).when(jdbc).query(anyString(), any(RowCallbackHandler.class), eq("RUNNING"), eq("SUCCESS"), eq("FAILED"));
when(jdbc.query(anyString(), any(RowMapper.class), any(), anyString(), any()))
.thenAnswer(invocation -> {
String sql = invocation.getArgument(0, String.class);
String status = invocation.getArgument(3, String.class);
if (!"FAILED".equals(status)) {
return java.util.List.of();
}
assertTrue(sql.contains("drama_title"));
assertTrue(sql.contains("?"));
RowMapper<?> mapper = invocation.getArgument(1);
ResultSet rs = failedRow();
return java.util.List.of(mapper.mapRow(rs, 0));
});
TranscodeNoticeRespVO data = new TranscodeNoticeService(jdbc).notices();
assertEquals(1, data.getFailedList().size());
assertEquals("重生", data.getFailedList().get(0).getDramaTitle());
assertEquals(4, data.getFailedList().get(0).getEpisodeNo());
assertEquals("第4集", data.getFailedList().get(0).getEpisodeTitle());
}
private ResultSet failedRow() throws Exception {
ResultSet rs = mock(ResultSet.class);
when(rs.getLong("id")).thenReturn(9L);
when(rs.getString("status")).thenReturn("FAILED");
when(rs.getInt("progress")).thenReturn(0);
when(rs.getString("error_msg")).thenReturn("boom");
when(rs.getTimestamp("updated_at")).thenReturn(Timestamp.valueOf(LocalDateTime.of(2026, 10, 24, 12, 0)));
when(rs.getString("drama_title")).thenReturn("重生");
when(rs.getObject("ep_no")).thenReturn(4);
when(rs.getString("title")).thenReturn("第4集");
return rs;
}
}
@@ -58,7 +58,7 @@ class WatchHistoryAdminServiceTest {
dramaMapper = mock(DramaMapper.class); dramaMapper = mock(DramaMapper.class);
dramaEpisodeMapper = mock(DramaEpisodeMapper.class); dramaEpisodeMapper = mock(DramaEpisodeMapper.class);
service = new WatchHistoryAdminService(watchHistoryMapper, appUserMapper, dramaMapper, service = new WatchHistoryAdminService(watchHistoryMapper, appUserMapper, dramaMapper,
dramaEpisodeMapper); dramaEpisodeMapper, mock(AppSessionSystemService.class));
} }
@Test @Test
@@ -68,7 +68,7 @@ public class AppAuthController {
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)") @Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
@PostMapping("/refresh") @PostMapping("/refresh")
public Result<TokenRespVO> refresh(@Valid @RequestBody RefreshReqVO req) { public Result<TokenRespVO> refresh(@Valid @RequestBody RefreshReqVO req) {
return Result.ok(authService.refresh(req.getRefreshToken())); return Result.ok(authService.refresh(req.getRefreshToken(), req.getPlatform(), req.getOsVersion()));
} }
/** 登出:默认只吊销当前设备的会话,allDevices=true 时吊销全部。 */ /** 登出:默认只吊销当前设备的会话,allDevices=true 时吊销全部。 */
@@ -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));
}
} }
@@ -4,9 +4,12 @@ package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService; import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.vo.AppDramaCardVO; import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.service.FavoriteService; import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.vo.FavoriteRemoveReqVO;
import com.fruitshorts.playback.vo.FavoriteToggleReqVO; import com.fruitshorts.playback.vo.FavoriteToggleReqVO;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@@ -18,10 +21,9 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 收藏。 */ /** 收藏。 */
@Tag(name = "客户端-收藏") @Tag(name = "客户端-收藏")
@RestController @RestController
@@ -42,9 +44,13 @@ public class AppFavoriteController {
/** 收藏列表,卡片结构与首页一致。 */ /** 收藏列表,卡片结构与首页一致。 */
@Operation(summary = "我的收藏列表") @Operation(summary = "我的收藏列表")
@GetMapping @GetMapping
public Result<List<AppDramaCardVO>> list() { public Result<PageResult<AppDramaCardVO>> list(
return Result.ok(appCatalogService.toCards( @RequestParam(defaultValue = "1") int pageIndex,
favoriteService.listDramas(SecurityUtils.getAppUserId()))); @RequestParam(defaultValue = "20") int pageSize) {
PageResult<Drama> page = favoriteService.page(
SecurityUtils.getAppUserId(), pageIndex, pageSize);
return Result.ok(new PageResult<>(
page.getTotal(), appCatalogService.toCards(page.getList())));
} }
@Operation(summary = "取消收藏") @Operation(summary = "取消收藏")
@@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
/** 客户端搜索:按标题或简介模糊匹配已上线短剧。 */ /** 客户端搜索:按标题或简介模糊匹配已上线短剧。不需要登录。 */
@Tag(name = "客户端-搜索") @Tag(name = "客户端-搜索")
@RestController @RestController
@RequestMapping("/app") @RequestMapping("/app")
@@ -2,6 +2,7 @@
package com.fruitshorts.app.controller; package com.fruitshorts.app.controller;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.common.pojo.Result; import com.fruitshorts.common.pojo.Result;
import com.fruitshorts.framework.security.SecurityUtils; import com.fruitshorts.framework.security.SecurityUtils;
import com.fruitshorts.playback.service.WatchProgressService; import com.fruitshorts.playback.service.WatchProgressService;
@@ -20,8 +21,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** 观看进度与观看记录。 */ /** 观看进度与观看记录。 */
@Tag(name = "客户端-观看进度") @Tag(name = "客户端-观看进度")
@RestController @RestController
@@ -45,10 +44,14 @@ public class AppWatchController {
return Result.ok(progressService.ofDrama(SecurityUtils.getAppUserId(), dramaId)); return Result.ok(progressService.ofDrama(SecurityUtils.getAppUserId(), dramaId));
} }
@Operation(summary = "最近观看列表") /** 最近观看分页,契约与 /app/favorites 一致:pageIndex/pageSize。 */
@Operation(summary = "最近观看分页")
@GetMapping("/recent") @GetMapping("/recent")
public Result<List<ProgressRespVO>> recent(@RequestParam(defaultValue = "20") int limit) { public Result<PageResult<ProgressRespVO>> recent(
return Result.ok(progressService.recent(SecurityUtils.getAppUserId(), limit)); @RequestParam(defaultValue = "1") int pageIndex,
@RequestParam(defaultValue = "20") int pageSize) {
return Result.ok(progressService.recentPage(
SecurityUtils.getAppUserId(), pageIndex, pageSize));
} }
@Operation(summary = "删除某部剧的观看记录") @Operation(summary = "删除某部剧的观看记录")
@@ -0,0 +1,44 @@
// Author: fruit.com.cn
package com.fruitshorts.app.controller;
import com.fruitshorts.system.service.LegalDocumentService;
import com.fruitshorts.system.service.LegalPages;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* 协议公开页。客户端按当前语言打开 /privacy/zh 或 /terms/en,不需要登录。
*/
@RestController
@RequiredArgsConstructor
public class LegalPageController {
private static final MediaType HTML = MediaType.parseMediaType("text/html;charset=UTF-8");
private final LegalDocumentService legalDocumentService;
/** 隐私协议。语言只接受 zh、en、id。 */
@GetMapping("/" + LegalPages.PATH_PRIVACY + "/{lang}")
public ResponseEntity<String> privacy(@PathVariable String lang) {
return page(LegalPages.PATH_PRIVACY, lang);
}
/** 服务条款。语言只接受 zh、en、id。 */
@GetMapping("/" + LegalPages.PATH_TERMS + "/{lang}")
public ResponseEntity<String> terms(@PathVariable String lang) {
return page(LegalPages.PATH_TERMS, lang);
}
private ResponseEntity<String> page(String path, String lang) {
String html = legalDocumentService.render(path, lang);
if (html == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().contentType(HTML).body(html);
}
}
@@ -8,24 +8,33 @@ import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.app.vo.AppDramaDetailVO; import com.fruitshorts.app.vo.AppDramaDetailVO;
import com.fruitshorts.app.vo.AppEpisodeVO; import com.fruitshorts.app.vo.AppEpisodeVO;
import com.fruitshorts.app.vo.AppFeedVO; import com.fruitshorts.app.vo.AppFeedVO;
import com.fruitshorts.app.vo.AppPlaylistDetailVO;
import com.fruitshorts.app.vo.AppSectionVO; import com.fruitshorts.app.vo.AppSectionVO;
import com.fruitshorts.common.pojo.CursorResult; import com.fruitshorts.common.pojo.CursorResult;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.ContentBanner; import com.fruitshorts.content.dal.entity.ContentBanner;
import com.fruitshorts.content.dal.entity.ContentTag;
import com.fruitshorts.content.dal.entity.Drama; import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import com.fruitshorts.content.enums.BannerPosition; import com.fruitshorts.content.enums.BannerPosition;
import com.fruitshorts.content.service.BannerService; import com.fruitshorts.content.service.BannerService;
import com.fruitshorts.content.service.ContentLocaleTexts;
import com.fruitshorts.content.service.ContentTagService;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaClassificationService;
import com.fruitshorts.content.service.DramaPlaylistCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodeService; import com.fruitshorts.content.service.EpisodeService;
import com.fruitshorts.interaction.service.CommentService; import com.fruitshorts.interaction.service.CommentService;
import com.fruitshorts.media.service.PlaybackSigner; import com.fruitshorts.media.service.PlaybackSigner;
import com.fruitshorts.media.service.ThumbnailUrlResolver;
import com.fruitshorts.content.vo.DramaCategoryRespVO; import com.fruitshorts.content.vo.DramaCategoryRespVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
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;
@@ -43,37 +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;
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));
@@ -91,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);
} }
/** /**
@@ -102,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) {
@@ -110,15 +194,20 @@ public class AppCatalogService {
List<DramaEpisode> episodes = episodeService.listPublishedByDrama(dramaId); List<DramaEpisode> episodes = episodeService.listPublishedByDrama(dramaId);
Map<Long, Long> episodeCommentCounts = commentService.countByEpisodes( Map<Long, Long> episodeCommentCounts = commentService.countByEpisodes(
episodes.stream().map(DramaEpisode::getId).sorted().toList()); episodes.stream().map(DramaEpisode::getId).sorted().toList());
String categoryName = categoryNameMap().getOrDefault(drama.getCategoryId(), ""); Map<Long, String> thumbnailUrls = thumbnailUrlResolver.resolveAll(
episodes.stream().map(DramaEpisode::getId).sorted().toList());
List<Map<String, String>> types = dramaCategoryService.localesForDrama(drama, categoryLocaleMap());
AppDramaDetailVO detail = new AppDramaDetailVO(); AppDramaDetailVO detail = new AppDramaDetailVO();
detail.setId(drama.getId()); detail.setId(drama.getId());
detail.setTitle(drama.getTitle()); Map<String, String> titles = ContentLocaleTexts.read(drama.getTitleLocales(), drama.getTitle(), null, null);
detail.setSynopsis(drama.getSynopsis()); Map<String, String> synopses = ContentLocaleTexts.read(
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
detail.setTitleLocales(titles);
detail.setSynopsisLocales(synopses);
detail.setCover(drama.getCoverUrl()); detail.setCover(drama.getCoverUrl());
detail.setGenre(drama.getGenre()); detail.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());
@@ -128,16 +217,77 @@ public class AppCatalogService {
detail.setFavoriteCount(drama.getFavoriteCount()); detail.setFavoriteCount(drama.getFavoriteCount());
detail.setCommentCount(commentService.countByDrama(dramaId)); detail.setCommentCount(commentService.countByDrama(dramaId));
detail.setEpisodes(episodes.stream() detail.setEpisodes(episodes.stream()
.map(episode -> toEpisode(episode, episodeCommentCounts)) .map(episode -> toEpisode(episode, episodeCommentCounts, thumbnailUrls))
.toList()); .toList());
return detail; return detail;
} }
/** C 端剧单列表:按页返回已启用剧单,每条只含该页剧单的已上线短剧。 */
public PageResult<AppPlaylistDetailVO> playlists(int pageIndex, int pageSize) {
var all = dramaPlaylistCategoryService.listEnabled();
int safeIndex = Math.max(1, pageIndex);
int safeSize = pageSize <= 0
? DEFAULT_PLAYLIST_PAGE_SIZE
: Math.min(pageSize, MAX_PLAYLIST_PAGE_SIZE);
int fromIndex = (safeIndex - 1) * safeSize;
if (fromIndex >= all.size()) {
return new PageResult<>(all.size(), List.of());
}
int toIndex = Math.min(fromIndex + safeSize, all.size());
List<AppPlaylistDetailVO> page = new ArrayList<>();
for (var category : all.subList(fromIndex, toIndex)) {
page.add(playlistDetail(category.getId(), 1, PLAYLIST_DRAMA_PREVIEW_SIZE));
}
return new PageResult<>(all.size(), page);
}
/** C 端剧单详情:剧单基本信息 + 该页已上线短剧卡片。 */
public AppPlaylistDetailVO playlistDetail(Long playlistId, int pageIndex, int pageSize) {
var category = dramaPlaylistCategoryService.getEnabledById(playlistId);
List<Long> allIds = dramaPlaylistCategoryService.listDramaIdsByCategory(playlistId);
List<Drama> published = dramaService.listPublishedByIds(allIds);
// 保留关联表原始顺序:按 allIds 位置重新排序
Map<Long, Integer> orderMap = new HashMap<>();
for (int i = 0; i < allIds.size(); i++) {
orderMap.put(allIds.get(i), i);
}
List<Drama> ordered = published.stream()
.sorted((a, b) -> {
Integer ia = orderMap.getOrDefault(a.getId(), Integer.MAX_VALUE);
Integer ib = orderMap.getOrDefault(b.getId(), Integer.MAX_VALUE);
return Integer.compare(ia, ib);
})
.toList();
int safeIndex = Math.max(1, pageIndex);
int safeSize = pageSize <= 0
? DEFAULT_PLAYLIST_DRAMA_PAGE_SIZE
: Math.min(pageSize, MAX_PLAYLIST_DRAMA_PAGE_SIZE);
int from = (safeIndex - 1) * safeSize;
List<Drama> pageRows = from >= ordered.size()
? List.of()
: ordered.subList(from, Math.min(from + safeSize, ordered.size()));
Map<String, String> locales = ContentLocaleTexts.read(
category.getNameLocales(), category.getName(), category.getNameEn(), category.getNameId());
Map<String, String> descriptions = ContentLocaleTexts.read(
category.getDescriptionLocales(), category.getDescription(),
category.getDescriptionEn(), category.getDescriptionId());
AppPlaylistDetailVO vo = new AppPlaylistDetailVO();
vo.setId(category.getId());
vo.setLocales(locales);
vo.setDescriptionLocales(descriptions);
vo.setDramaCount(ordered.size());
vo.setPageIndex(safeIndex);
vo.setPageSize(safeSize);
vo.setList(cards(pageRows, categoryLocaleMap()));
return vo;
}
private List<AppBannerVO> banners(String position) { private List<AppBannerVO> banners(String position) {
return bannerService.listActive(position).stream().map(this::toBanner).toList(); return bannerService.listActive(position).stream().map(this::toBanner).toList();
} }
private List<AppSectionVO> categorySections(int size, Map<Long, String> categoryNames) { private List<AppSectionVO> categorySections(int size, Map<Long, Map<String, String>> categoryLocales) {
List<AppSectionVO> sections = new ArrayList<>(); List<AppSectionVO> sections = new ArrayList<>();
for (DramaCategoryRespVO category : dramaCategoryService.listBasic()) { for (DramaCategoryRespVO category : dramaCategoryService.listBasic()) {
if (sections.size() >= MAX_CATEGORY_SECTIONS) { if (sections.size() >= MAX_CATEGORY_SECTIONS) {
@@ -147,17 +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)));
} }
} }
@@ -171,26 +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(
previews.values().stream().map(DramaEpisode::getId).sorted().toList());
Map<Long, ContentTag> tags = loadTags(dramas);
return dramas.stream() return dramas.stream()
.map(drama -> toCard( .map(drama -> toCard(
drama, categoryNames, previews.get(drama.getId()), commentCounts)) drama, categoryLocales, tags, previews.get(drama.getId()), commentCounts,
thumbnailUrls))
.toList(); .toList();
} }
private AppDramaCardVO toCard(Drama drama, Map<Long, String> categoryNames, private AppDramaCardVO toCard(Drama drama, Map<Long, Map<String, String>> categoryLocales,
DramaEpisode preview, Map<Long, Long> commentCounts) { Map<Long, ContentTag> tags,
DramaEpisode preview, Map<Long, Long> commentCounts,
Map<Long, String> thumbnailUrls) {
List<Map<String, String>> types = dramaCategoryService.localesForDrama(drama, categoryLocales);
AppDramaCardVO card = new AppDramaCardVO(); AppDramaCardVO card = new AppDramaCardVO();
card.setId(drama.getId()); card.setId(drama.getId());
card.setTitle(drama.getTitle()); Map<String, String> titles = ContentLocaleTexts.read(drama.getTitleLocales(), drama.getTitle(), null, null);
Map<String, String> synopses = ContentLocaleTexts.read(
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
card.setTitleLocales(titles);
card.setCover(drama.getCoverUrl()); card.setCover(drama.getCoverUrl());
card.setSynopsis(shortSynopsis(drama.getSynopsis())); card.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());
@@ -201,11 +361,13 @@ public class AppCatalogService {
? 0L : commentCounts.getOrDefault(preview.getId(), 0L)); ? 0L : commentCounts.getOrDefault(preview.getId(), 0L));
card.setLanguage(drama.getLanguage()); card.setLanguage(drama.getLanguage());
card.setDramaType(drama.getDramaType()); card.setDramaType(drama.getDramaType());
card.setPreview(preview == null ? null : toEpisode(preview, commentCounts)); card.setPreview(preview == null
? null : toEpisode(preview, commentCounts, thumbnailUrls));
return card; return card;
} }
private AppEpisodeVO toEpisode(DramaEpisode episode, Map<Long, Long> commentCounts) { private AppEpisodeVO toEpisode(DramaEpisode episode, Map<Long, Long> commentCounts,
Map<Long, String> thumbnailUrls) {
AppEpisodeVO vo = new AppEpisodeVO(); AppEpisodeVO vo = new AppEpisodeVO();
vo.setId(episode.getId()); vo.setId(episode.getId());
vo.setNumber(episode.getEpNo()); vo.setNumber(episode.getEpNo());
@@ -219,6 +381,7 @@ public class AppCatalogService {
vo.setUnlockCoin(episode.getUnlockCoin()); vo.setUnlockCoin(episode.getUnlockCoin());
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount()); vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L)); vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L));
vo.setThumbnailsUrl(thumbnailUrls.get(episode.getId()));
if (free) { if (free) {
// 播放地址统一在这里签名:客户端拿不到可长期复用的裸地址 // 播放地址统一在这里签名:客户端拿不到可长期复用的裸地址
vo.setPlayUrl(playbackSigner.sign(playableSource(episode))); vo.setPlayUrl(playbackSigner.sign(playableSource(episode)));
@@ -234,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 "";
@@ -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;
}
@@ -24,4 +24,6 @@ public class AppEpisodeVO {
* 详情页拿到就能直接播,不必按集再请求一次播放票据。 * 详情页拿到就能直接播,不必按集再请求一次播放票据。
*/ */
private String playUrl; private String playUrl;
/** 雪碧图 WebVTT 时间轴地址;没有产物时为 null */
private String thumbnailsUrl;
} }
@@ -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;
}
} }
@@ -17,15 +17,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;
@@ -58,7 +61,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 +97,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 +125,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 +145,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 +164,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);
}
} }
@@ -0,0 +1,185 @@
// Author: fruit.com.cn
package com.fruitshorts.app.controller;
import com.fruitshorts.app.service.AppCatalogService;
import com.fruitshorts.app.support.ControllerContractSupport;
import com.fruitshorts.app.vo.AppDramaCardVO;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.framework.security.LoginUser;
import com.fruitshorts.playback.service.FavoriteService;
import com.fruitshorts.playback.service.WatchProgressService;
import com.fruitshorts.playback.vo.ProgressRespVO;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDateTime;
import java.util.List;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/** 客户端收藏与观看历史分页契约。 */
class AppLibraryPagingContractTest {
private static final long USER_ID = 1001L;
private FavoriteService favoriteService;
private AppCatalogService catalogService;
private WatchProgressService progressService;
private MockMvc favoriteMvc;
private MockMvc watchMvc;
@BeforeEach
void setUp() {
favoriteService = mock(FavoriteService.class);
catalogService = mock(AppCatalogService.class);
progressService = mock(WatchProgressService.class);
favoriteMvc = ControllerContractSupport.mockMvcOf(
new AppFavoriteController(favoriteService, catalogService));
watchMvc = ControllerContractSupport.mockMvcOf(
new AppWatchController(progressService));
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
new LoginUser(USER_ID, "app-user", "APP_USER", List.of()),
null,
List.of()));
}
@AfterEach
void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
void should_page_favorites_with_default_size_and_non_overlapping_second_page()
throws Exception {
Drama first = drama(101L, "收藏一");
Drama second = drama(102L, "收藏二");
Drama third = drama(103L, "收藏三");
given(favoriteService.page(USER_ID, 1, 20))
.willReturn(new PageResult<>(21L, List.of(first, second)));
given(favoriteService.page(USER_ID, 2, 20))
.willReturn(new PageResult<>(21L, List.of(third)));
given(catalogService.toCards(List.of(first, second)))
.willReturn(List.of(card(101L), card(102L)));
given(catalogService.toCards(List.of(third)))
.willReturn(List.of(card(103L)));
favoriteMvc.perform(get("/app/favorites"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value(0))
.andExpect(jsonPath("$.data.total").value("21"))
.andExpect(jsonPath("$.data.list.length()").value(2))
.andExpect(jsonPath("$.data.list[0].id").value("101"))
.andExpect(jsonPath("$.data.list[1].id").value("102"));
favoriteMvc.perform(get("/app/favorites").param("pageIndex", "2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value("21"))
.andExpect(jsonPath("$.data.list.length()").value(1))
.andExpect(jsonPath("$.data.list[0].id").value("103"));
verify(favoriteService).page(USER_ID, 1, 20);
verify(favoriteService).page(USER_ID, 2, 20);
}
@Test
void should_page_recent_watch_with_display_fields() throws Exception {
ProgressRespVO first = progress(12L, 88L, 6, "剧名一", 68);
ProgressRespVO second = progress(13L, 99L, 2, "剧名二", 20);
ProgressRespVO third = progress(14L, 100L, 1, "剧名三", 16);
given(progressService.recentPage(USER_ID, 1, 20))
.willReturn(new PageResult<>(23L, List.of(first, second)));
given(progressService.recentPage(USER_ID, 2, 20))
.willReturn(new PageResult<>(23L, List.of(third)));
watchMvc.perform(get("/app/watch/recent"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value("23"))
.andExpect(jsonPath("$.data.list.length()").value(2))
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名一"))
.andExpect(jsonPath("$.data.list[0].episodeNumber").value(6))
.andExpect(jsonPath("$.data.list[0].totalEpisodes").value(68))
.andExpect(jsonPath("$.data.list[1].dramaTitle").value("剧名二"))
.andExpect(jsonPath("$.data.list[1].episodeNumber").value(2));
watchMvc.perform(get("/app/watch/recent").param("pageIndex", "2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value("23"))
.andExpect(jsonPath("$.data.list.length()").value(1))
.andExpect(jsonPath("$.data.list[0].dramaId").value("14"))
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名三"));
verify(progressService).recentPage(USER_ID, 1, 20);
verify(progressService).recentPage(USER_ID, 2, 20);
}
@Test
void should_keep_total_and_return_empty_list_when_watch_page_is_out_of_range()
throws Exception {
given(progressService.recentPage(USER_ID, 9, 20))
.willReturn(new PageResult<>(23L, List.of()));
watchMvc.perform(get("/app/watch/recent").param("pageIndex", "9"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value("23"))
.andExpect(jsonPath("$.data.list").isArray())
.andExpect(jsonPath("$.data.list").isEmpty());
}
@Test
void should_ignore_removed_limit_and_still_return_page_result() throws Exception {
// limit 已从契约移除:即使客户端误传,也应走分页并返回 PageResult。
given(progressService.recentPage(USER_ID, 1, 20))
.willReturn(new PageResult<>(3L, List.of(progress(12L, 88L, 6, "剧名一", 68))));
watchMvc.perform(get("/app/watch/recent").param("limit", "5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.total").value("3"))
.andExpect(jsonPath("$.data.list").isArray())
.andExpect(jsonPath("$.data.list.length()").value(1))
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名一"));
verify(progressService).recentPage(USER_ID, 1, 20);
}
private Drama drama(Long id, String title) {
Drama drama = new Drama();
drama.setId(id);
drama.setTitle(title);
return drama;
}
private AppDramaCardVO card(Long id) {
AppDramaCardVO card = new AppDramaCardVO();
card.setId(id);
return card;
}
private ProgressRespVO progress(Long dramaId, Long episodeId, int episodeNumber,
String dramaTitle, int totalEpisodes) {
ProgressRespVO vo = new ProgressRespVO();
vo.setDramaId(dramaId);
vo.setEpisodeId(episodeId);
vo.setEpisodeNumber(episodeNumber);
vo.setDramaTitle(dramaTitle);
vo.setDramaCover("/files/cover/" + dramaId + ".jpg");
vo.setTotalEpisodes(totalEpisodes);
vo.setPositionMs(80_000L);
vo.setDurationMs(120_000L);
vo.setFinished(false);
vo.setPlayCount(1);
vo.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 10, 0));
return vo;
}
}
@@ -15,6 +15,7 @@ import org.springframework.test.web.servlet.MockMvc;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.isNull;
@@ -55,7 +56,9 @@ class AppPlaybackContractTest {
@Test @Test
void should_return_free_access_when_episode_is_free() throws Exception { void should_return_free_access_when_episode_is_free() throws Exception {
given(playbackService.play(isNull(), eq(11L), any(), any())) given(playbackService.play(isNull(), eq(11L), any(), any()))
.willReturn(ticket(11L, true, PlaybackService.ACCESS_FREE, "/files/ep.mp4?s=1")); .willReturn(ticket(11L, true, PlaybackService.ACCESS_FREE,
"/files/ep.mp4?s=1",
"/files/transcoded/11/thumbnails/thumbnails.vtt?e=1&s=sig"));
mockMvc.perform(get("/app/episodes/11/play").header("X-Device-Id", "device-9")) mockMvc.perform(get("/app/episodes/11/play").header("X-Device-Id", "device-9"))
.andExpect(status().isOk()) .andExpect(status().isOk())
@@ -66,13 +69,15 @@ class AppPlaybackContractTest {
.andExpect(jsonPath("$.data.accessible").value(true)) .andExpect(jsonPath("$.data.accessible").value(true))
.andExpect(jsonPath("$.data.accessType").value(PlaybackService.ACCESS_FREE)) .andExpect(jsonPath("$.data.accessType").value(PlaybackService.ACCESS_FREE))
.andExpect(jsonPath("$.data.playUrl").value("/files/ep.mp4?s=1")) .andExpect(jsonPath("$.data.playUrl").value("/files/ep.mp4?s=1"))
.andExpect(jsonPath("$.data.thumbnailsUrl")
.value("/files/transcoded/11/thumbnails/thumbnails.vtt?e=1&s=sig"))
.andExpect(jsonPath("$.data.likeCount").value("88")) .andExpect(jsonPath("$.data.likeCount").value("88"))
.andExpect(jsonPath("$.data.commentCount").value("0")); .andExpect(jsonPath("$.data.commentCount").value("0"));
} }
@Test @Test
void should_return_coin_required_when_episode_is_locked_and_not_entitled() throws Exception { void should_return_coin_required_when_episode_is_locked_and_not_entitled() throws Exception {
PlayRespVO locked = ticket(12L, false, PlaybackService.ACCESS_COIN_REQUIRED, ""); PlayRespVO locked = ticket(12L, false, PlaybackService.ACCESS_COIN_REQUIRED, "", null);
locked.setUnlockCoin(60); locked.setUnlockCoin(60);
given(playbackService.play(isNull(), eq(12L), any(), any())).willReturn(locked); given(playbackService.play(isNull(), eq(12L), any(), any())).willReturn(locked);
@@ -81,13 +86,15 @@ class AppPlaybackContractTest {
.andExpect(jsonPath("$.data.accessible").value(false)) .andExpect(jsonPath("$.data.accessible").value(false))
.andExpect(jsonPath("$.data.accessType").value(PlaybackService.ACCESS_COIN_REQUIRED)) .andExpect(jsonPath("$.data.accessType").value(PlaybackService.ACCESS_COIN_REQUIRED))
.andExpect(jsonPath("$.data.playUrl").value("")) .andExpect(jsonPath("$.data.playUrl").value(""))
.andExpect(jsonPath("$.data.thumbnailsUrl").value(nullValue()))
.andExpect(jsonPath("$.data.unlockCoin").value(60)); .andExpect(jsonPath("$.data.unlockCoin").value(60));
} }
@Test @Test
void should_pass_episode_id_and_device_header_when_play_is_requested() throws Exception { void should_pass_episode_id_and_device_header_when_play_is_requested() throws Exception {
given(playbackService.play(isNull(), eq(13L), eq("device-9"), any())) given(playbackService.play(isNull(), eq(13L), eq("device-9"), any()))
.willReturn(ticket(13L, true, PlaybackService.ACCESS_FREE, "/files/ep13.mp4?s=1")); .willReturn(ticket(13L, true, PlaybackService.ACCESS_FREE,
"/files/ep13.mp4?s=1", null));
mockMvc.perform(get("/app/episodes/13/play").header("X-Device-Id", "device-9")) mockMvc.perform(get("/app/episodes/13/play").header("X-Device-Id", "device-9"))
.andExpect(status().isOk()); .andExpect(status().isOk());
@@ -95,7 +102,8 @@ class AppPlaybackContractTest {
verify(playbackService).play(isNull(), eq(13L), eq("device-9"), any()); verify(playbackService).play(isNull(), eq(13L), eq("device-9"), any());
} }
private PlayRespVO ticket(Long episodeId, boolean accessible, String accessType, String playUrl) { private PlayRespVO ticket(Long episodeId, boolean accessible, String accessType,
String playUrl, String thumbnailsUrl) {
PlayRespVO vo = new PlayRespVO(); PlayRespVO vo = new PlayRespVO();
vo.setEpisodeId(episodeId); vo.setEpisodeId(episodeId);
vo.setDramaId(7L); vo.setDramaId(7L);
@@ -105,6 +113,7 @@ class AppPlaybackContractTest {
vo.setAccessible(accessible); vo.setAccessible(accessible);
vo.setAccessType(accessType); vo.setAccessType(accessType);
vo.setPlayUrl(playUrl); vo.setPlayUrl(playUrl);
vo.setThumbnailsUrl(thumbnailsUrl);
vo.setQualities(List.of("AUTO")); vo.setQualities(List.of("AUTO"));
vo.setUnlockCoin(0); vo.setUnlockCoin(0);
vo.setPreviewSeconds(0); vo.setPreviewSeconds(0);
@@ -7,11 +7,15 @@ 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;
import com.fruitshorts.media.service.PlaybackSigner; import com.fruitshorts.media.service.PlaybackSigner;
import com.fruitshorts.media.service.ThumbnailUrlResolver;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -35,6 +39,7 @@ class AppCatalogServiceTest {
private EpisodeService episodeService; private EpisodeService episodeService;
private DramaCategoryService dramaCategoryService; private DramaCategoryService dramaCategoryService;
private CommentService commentService; private CommentService commentService;
private ThumbnailUrlResolver thumbnailUrlResolver;
private AppCatalogService catalogService; private AppCatalogService catalogService;
@BeforeEach @BeforeEach
@@ -43,10 +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);
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); dramaCategoryService, mock(ContentTagService.class), dramaClassificationService, dramaPlaylistCategoryService,
playbackSigner, commentService, thumbnailUrlResolver);
} }
@Test @Test
@@ -66,6 +76,8 @@ class AppCatalogServiceTest {
given(commentService.countByDrama(42L)).willReturn(96L); given(commentService.countByDrama(42L)).willReturn(96L);
given(commentService.countByEpisodes(List.of(11L, 22L))) given(commentService.countByEpisodes(List.of(11L, 22L)))
.willReturn(Map.of(11L, 2L, 22L, 4L)); .willReturn(Map.of(11L, 2L, 22L, 4L));
given(thumbnailUrlResolver.resolveAll(List.of(11L, 22L)))
.willReturn(Map.of(22L, "/files/transcoded/22/thumbnails/thumbnails.vtt"));
AppDramaDetailVO detail = catalogService.dramaDetail(42L); AppDramaDetailVO detail = catalogService.dramaDetail(42L);
@@ -75,7 +87,10 @@ class AppCatalogServiceTest {
assertThat(detail.getCommentCount()).isEqualTo(96L); assertThat(detail.getCommentCount()).isEqualTo(96L);
assertThat(detail.getEpisodes().get(0).getLikeCount()).isEqualTo(66L); assertThat(detail.getEpisodes().get(0).getLikeCount()).isEqualTo(66L);
assertThat(detail.getEpisodes().get(0).getCommentCount()).isEqualTo(4L); assertThat(detail.getEpisodes().get(0).getCommentCount()).isEqualTo(4L);
assertThat(detail.getEpisodes().get(0).getThumbnailsUrl())
.isEqualTo("/files/transcoded/22/thumbnails/thumbnails.vtt");
verify(commentService).countByDrama(42L); verify(commentService).countByDrama(42L);
verify(thumbnailUrlResolver).resolveAll(List.of(11L, 22L));
} }
@Test @Test
@@ -12,6 +12,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper; import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodePriceSync;
import org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -41,7 +42,10 @@ class DramaServiceFavoriteCountTest {
dramaMapper, dramaMapper,
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));
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);
@@ -11,6 +11,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper; import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodePriceSync;
import org.apache.ibatis.builder.MapperBuilderAssistant; 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;
@@ -45,7 +46,10 @@ class DramaServiceFeedTest {
dramaMapper, dramaMapper,
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));
} }
@Test @Test
@@ -12,6 +12,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper; import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodePriceSync;
import com.fruitshorts.content.vo.DramaSaveReqVO; import com.fruitshorts.content.vo.DramaSaveReqVO;
import org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
@@ -46,7 +47,10 @@ class DramaServiceK88Test {
dramaMapper, dramaMapper,
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));
} }
@Test @Test
@@ -13,6 +13,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper; import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper;
import com.fruitshorts.content.service.DramaCategoryService; import com.fruitshorts.content.service.DramaCategoryService;
import com.fruitshorts.content.service.DramaService; import com.fruitshorts.content.service.DramaService;
import com.fruitshorts.content.service.EpisodePriceSync;
import com.fruitshorts.content.vo.DramaPageReqVO; import com.fruitshorts.content.vo.DramaPageReqVO;
import com.fruitshorts.content.vo.DramaRespVO; import com.fruitshorts.content.vo.DramaRespVO;
import com.fruitshorts.content.vo.DramaSaveReqVO; import com.fruitshorts.content.vo.DramaSaveReqVO;
@@ -54,7 +55,10 @@ class DramaServiceMultiTagTest {
dramaMapper, dramaMapper,
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));
} }
@Test @Test
@@ -13,6 +13,7 @@ import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
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.content.vo.EpisodeSaveReqVO; import com.fruitshorts.content.vo.EpisodeSaveReqVO;
import com.fruitshorts.media.service.EpisodeTranscodeBindingService;
import org.apache.ibatis.builder.MapperBuilderAssistant; 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;
@@ -46,7 +47,9 @@ class EpisodeServiceK89Test {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
episodeMapper = mock(DramaEpisodeMapper.class); episodeMapper = mock(DramaEpisodeMapper.class);
episodeService = new EpisodeService(episodeMapper, mock(DramaService.class)); episodeService = new EpisodeService(
episodeMapper, mock(DramaService.class),
mock(EpisodeTranscodeBindingService.class));
} }
@Test @Test
@@ -0,0 +1,33 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.system.service.LegalPageHtml;
import com.fruitshorts.system.service.LegalPages;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LegalPageHtmlTest {
@Test
void should_render_markdown_without_an_extra_title() {
String html = LegalPageHtml.render("zh", "第一行\n\n<script>alert(1)</script>\n\n**粗体**");
assertTrue(html.contains("<html lang=\"zh\">"));
assertFalse(html.contains("<h1>"));
assertTrue(html.contains("<p>第一行</p>"));
assertTrue(html.contains("&lt;script&gt;"));
assertTrue(html.contains("<strong>粗体</strong>"));
}
@Test
void should_map_public_paths_to_document_codes() {
assertEquals(LegalPages.PRIVACY, LegalPages.docCodeOfPath("privacy"));
assertEquals(LegalPages.TERMS, LegalPages.docCodeOfPath("terms"));
assertNull(LegalPages.docCodeOfPath("other"));
}
}
@@ -5,7 +5,9 @@ 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.media.dal.entity.MediaRendition;
import com.fruitshorts.media.service.PlaybackSigner; import com.fruitshorts.media.service.PlaybackSigner;
import com.fruitshorts.media.service.ThumbnailUrlResolver;
import com.fruitshorts.media.service.TranscodeService; import com.fruitshorts.media.service.TranscodeService;
import com.fruitshorts.playback.dal.entity.PlaybackTicket; import com.fruitshorts.playback.dal.entity.PlaybackTicket;
import com.fruitshorts.playback.dal.mapper.PlaybackTicketMapper; import com.fruitshorts.playback.dal.mapper.PlaybackTicketMapper;
@@ -42,6 +44,7 @@ class PlaybackServiceTest {
private PlaybackSigner signer; private PlaybackSigner signer;
private EntitlementPort entitlementPort; private EntitlementPort entitlementPort;
private TranscodeService transcodeService; private TranscodeService transcodeService;
private ThumbnailUrlResolver thumbnailUrlResolver;
private PlaybackService playbackService; private PlaybackService playbackService;
@BeforeEach @BeforeEach
@@ -52,10 +55,12 @@ class PlaybackServiceTest {
signer = mock(PlaybackSigner.class); signer = mock(PlaybackSigner.class);
entitlementPort = mock(EntitlementPort.class); entitlementPort = mock(EntitlementPort.class);
transcodeService = mock(TranscodeService.class); transcodeService = mock(TranscodeService.class);
thumbnailUrlResolver = mock(ThumbnailUrlResolver.class);
playbackService = new PlaybackService(episodeService, dramaService, ticketMapper, signer, playbackService = new PlaybackService(episodeService, dramaService, ticketMapper, signer,
entitlementPort, transcodeService); entitlementPort, transcodeService, thumbnailUrlResolver);
given(dramaService.getPublished(anyLong())).willReturn(drama()); given(dramaService.getPublished(anyLong())).willReturn(drama());
given(transcodeService.listRenditions(anyLong())).willReturn(List.of()); given(transcodeService.listRenditions(anyLong())).willReturn(List.of());
given(thumbnailUrlResolver.resolve(anyLong())).willReturn(null);
given(signer.sign(anyString())).willReturn("/files/episode/1.mp4?e=1&s=sig"); given(signer.sign(anyString())).willReturn("/files/episode/1.mp4?e=1&s=sig");
} }
@@ -72,6 +77,27 @@ class PlaybackServiceTest {
verify(ticketMapper, never()).insert(any(PlaybackTicket.class)); verify(ticketMapper, never()).insert(any(PlaybackTicket.class));
} }
@Test
void should_return_signed_thumbnails_url_when_thumbnail_exists() {
given(episodeService.getPublished(11L)).willReturn(episode(11L, 1, 0, "/files/episode/1.mp4"));
given(thumbnailUrlResolver.resolve(11L))
.willReturn("/files/transcoded/1/thumbnails/thumbnails.vtt?e=1&s=sig");
PlayRespVO resp = playbackService.play(null, 11L, "device-9", "203.0.113.8");
assertThat(resp.getThumbnailsUrl())
.isEqualTo("/files/transcoded/1/thumbnails/thumbnails.vtt?e=1&s=sig");
}
@Test
void should_return_null_thumbnails_url_when_thumbnail_is_absent() {
given(episodeService.getPublished(11L)).willReturn(episode(11L, 1, 0, "/files/episode/1.mp4"));
PlayRespVO resp = playbackService.play(null, 11L, "device-9", "203.0.113.8");
assertThat(resp.getThumbnailsUrl()).isNull();
}
@Test @Test
void should_return_coin_required_when_episode_is_locked_and_not_entitled() { void should_return_coin_required_when_episode_is_locked_and_not_entitled() {
given(episodeService.getPublished(12L)).willReturn(episode(12L, 0, 60, "/files/episode/2.mp4")); given(episodeService.getPublished(12L)).willReturn(episode(12L, 0, 60, "/files/episode/2.mp4"));
@@ -122,6 +148,30 @@ class PlaybackServiceTest {
verify(signer).sign("/files/episode/15/master.m3u8"); verify(signer).sign("/files/episode/15/master.m3u8");
} }
@Test
void should_sign_each_ready_rendition_when_episode_has_multiple_qualities() {
DramaEpisode episode = episode(16L, 1, 0, "/files/episode/origin.mp4");
episode.setHlsUrl("/files/transcoded/16/master.m3u8");
given(episodeService.getPublished(16L)).willReturn(episode);
given(signer.sign(anyString())).willAnswer(invocation -> invocation.getArgument(0) + "?s=1");
MediaRendition ready = new MediaRendition();
ready.setQuality("720p");
ready.setPlayUrl("/files/transcoded/16/720p/index.m3u8");
ready.setStatus("ready");
MediaRendition failed = new MediaRendition();
failed.setQuality("1080p");
failed.setPlayUrl("/files/transcoded/16/1080p/index.m3u8");
failed.setStatus("failed");
given(transcodeService.listRenditions(16L)).willReturn(List.of(ready, failed));
PlayRespVO resp = playbackService.play(null, 16L, "device-9", "203.0.113.8");
assertThat(resp.getTracks()).extracting(track -> track.getQuality())
.containsExactly("AUTO", "720p");
assertThat(resp.getTracks().get(1).getPlayUrl())
.isEqualTo("/files/transcoded/16/720p/index.m3u8?s=1");
}
private DramaEpisode episode(Long id, int isFree, int unlockCoin, String videoUrl) { private DramaEpisode episode(Long id, int isFree, int unlockCoin, String videoUrl) {
DramaEpisode episode = new DramaEpisode(); DramaEpisode episode = new DramaEpisode();
episode.setId(id); episode.setId(id);
@@ -0,0 +1,55 @@
// Author: fruit.com.cn
package com.fruitshorts.app.service;
import com.fruitshorts.media.dal.entity.MediaThumbnail;
import com.fruitshorts.media.service.MediaStorageService;
import com.fruitshorts.media.service.PlaybackSigner;
import com.fruitshorts.media.service.ThumbnailUrlResolver;
import com.fruitshorts.media.service.TranscodeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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;
/**
* 缩略图 objectKey 到公开签名地址的转换。
*/
class ThumbnailUrlResolverTest {
private TranscodeService transcodeService;
private MediaStorageService storageService;
private PlaybackSigner signer;
private ThumbnailUrlResolver resolver;
@BeforeEach
void setUp() {
transcodeService = mock(TranscodeService.class);
storageService = mock(MediaStorageService.class);
signer = mock(PlaybackSigner.class);
resolver = new ThumbnailUrlResolver(transcodeService, storageService, signer);
}
@Test
void should_sign_vtt_public_url_when_ready_thumbnail_exists() {
MediaThumbnail thumbnail = new MediaThumbnail();
thumbnail.setVttObjectKey("transcoded/88/thumbnails/thumbnails.vtt");
given(transcodeService.findReadyThumbnail(11L)).willReturn(thumbnail);
given(storageService.toPublicUrl(thumbnail.getVttObjectKey()))
.willReturn("/files/transcoded/88/thumbnails/thumbnails.vtt");
given(signer.sign("/files/transcoded/88/thumbnails/thumbnails.vtt"))
.willReturn("/files/transcoded/88/thumbnails/thumbnails.vtt?e=1&s=sig");
assertThat(resolver.resolve(11L))
.isEqualTo("/files/transcoded/88/thumbnails/thumbnails.vtt?e=1&s=sig");
verify(signer).sign("/files/transcoded/88/thumbnails/thumbnails.vtt");
}
@Test
void should_return_null_when_thumbnail_record_is_absent() {
assertThat(resolver.resolve(12L)).isNull();
}
}
@@ -2,13 +2,23 @@
package com.fruitshorts.playback.service; package com.fruitshorts.playback.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.pojo.PageResult;
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;
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper; import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
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.Arrays; import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@@ -20,6 +30,12 @@ import static org.mockito.Mockito.verify;
/** 收藏关系变化时同步维护短剧收藏数。 */ /** 收藏关系变化时同步维护短剧收藏数。 */
class FavoriteServiceTest { class FavoriteServiceTest {
@BeforeAll
static void initTableInfoCache() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, UserFavorite.class);
}
private UserFavoriteMapper favoriteMapper; private UserFavoriteMapper favoriteMapper;
private DramaService dramaService; private DramaService dramaService;
private FavoriteService favoriteService; private FavoriteService favoriteService;
@@ -77,4 +93,46 @@ class FavoriteServiceTest {
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_use_database_page_and_keep_favorite_order_when_listing() {
UserFavorite first = favorite(51L);
UserFavorite second = favorite(52L);
Page<UserFavorite> databasePage = new Page<>(2, 20, 25);
databasePage.setRecords(List.of(first, second));
given(favoriteMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
Drama firstDrama = drama(51L);
Drama secondDrama = drama(52L);
given(dramaService.listPublishedByIds(List.of(51L, 52L)))
.willReturn(List.of(secondDrama, firstDrama));
PageResult<Drama> result = favoriteService.page(1L, 2, 20);
assertThat(result.getTotal()).isEqualTo(25);
assertThat(result.getList()).containsExactly(firstDrama, secondDrama);
@SuppressWarnings("unchecked")
ArgumentCaptor<Page<UserFavorite>> pageCaptor = ArgumentCaptor.forClass(Page.class);
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<UserFavorite>> wrapperCaptor =
ArgumentCaptor.forClass(Wrapper.class);
verify(favoriteMapper).selectPage(pageCaptor.capture(), wrapperCaptor.capture());
assertThat(pageCaptor.getValue().getCurrent()).isEqualTo(2);
assertThat(pageCaptor.getValue().getSize()).isEqualTo(20);
assertThat(wrapperCaptor.getValue().getSqlSegment())
.contains("created_at DESC")
.contains("drama_id DESC");
verify(dramaService).listPublishedByIds(List.of(51L, 52L));
}
private UserFavorite favorite(Long dramaId) {
UserFavorite favorite = new UserFavorite();
favorite.setDramaId(dramaId);
return favorite;
}
private Drama drama(Long id) {
Drama drama = new Drama();
drama.setId(id);
return drama;
}
} }
@@ -0,0 +1,152 @@
// Author: fruit.com.cn
package com.fruitshorts.playback.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.pojo.PageResult;
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.playback.dal.entity.WatchProgress;
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
import com.fruitshorts.playback.dal.mapper.WatchProgressMapper;
import com.fruitshorts.playback.vo.ProgressRespVO;
import com.fruitshorts.playback.vo.ProgressSaveReqVO;
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.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/** 观看历史分页、稳定排序与批量展示字段装配。 */
class WatchProgressServiceTest {
@BeforeAll
static void initTableInfoCache() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, WatchProgress.class);
}
private WatchProgressMapper progressMapper;
private DramaService dramaService;
private EpisodeService episodeService;
private WatchProgressService progressService;
@BeforeEach
void setUp() {
progressMapper = mock(WatchProgressMapper.class);
dramaService = mock(DramaService.class);
episodeService = mock(EpisodeService.class);
progressService = new WatchProgressService(
progressMapper,
mock(WatchHistoryMapper.class),
dramaService,
episodeService);
}
@Test
void should_page_recent_and_fill_display_fields_with_two_batch_queries() {
WatchProgress first = progress(12L, 88L);
WatchProgress second = progress(13L, 99L);
Page<WatchProgress> databasePage = new Page<>(1, 20, 23);
databasePage.setRecords(List.of(first, second));
given(progressMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
given(dramaService.listByIds(List.of(12L, 13L)))
.willReturn(List.of(drama(13L, "剧名二", 20), drama(12L, "剧名一", 68)));
given(episodeService.listByIds(List.of(88L, 99L)))
.willReturn(List.of(episode(99L, 2), episode(88L, 6)));
PageResult<ProgressRespVO> result =
progressService.recentPage(1001L, 1, 20);
assertThat(result.getTotal()).isEqualTo(23);
assertThat(result.getList()).hasSize(2);
assertThat(result.getList().get(0).getDramaTitle()).isEqualTo("剧名一");
assertThat(result.getList().get(0).getEpisodeNumber()).isEqualTo(6);
assertThat(result.getList().get(0).getTotalEpisodes()).isEqualTo(68);
assertThat(result.getList().get(1).getDramaTitle()).isEqualTo("剧名二");
assertThat(result.getList().get(1).getEpisodeNumber()).isEqualTo(2);
@SuppressWarnings("unchecked")
ArgumentCaptor<Page<WatchProgress>> pageCaptor = ArgumentCaptor.forClass(Page.class);
@SuppressWarnings("unchecked")
ArgumentCaptor<Wrapper<WatchProgress>> wrapperCaptor =
ArgumentCaptor.forClass(Wrapper.class);
verify(progressMapper).selectPage(pageCaptor.capture(), wrapperCaptor.capture());
assertThat(pageCaptor.getValue().getCurrent()).isEqualTo(1);
assertThat(pageCaptor.getValue().getSize()).isEqualTo(20);
assertThat(wrapperCaptor.getValue().getSqlSegment())
.contains("updated_at DESC")
.contains("id DESC");
verify(dramaService, times(1)).listByIds(List.of(12L, 13L));
verify(episodeService, times(1)).listByIds(List.of(88L, 99L));
}
private WatchProgress progress(Long dramaId, Long episodeId) {
WatchProgress progress = new WatchProgress();
progress.setUserId(1001L);
progress.setDramaId(dramaId);
progress.setEpisodeId(episodeId);
progress.setPositionMs(80_000L);
progress.setDurationMs(120_000L);
progress.setFinished(0);
progress.setPlayCount(1);
progress.setUpdatedAt(LocalDateTime.of(2026, 10, 22, 10, 0));
return progress;
}
@Test
void should_revive_deleted_progress_when_same_drama_is_reported_again() {
DramaEpisode episode = episode(88L, 1);
episode.setDramaId(5L);
given(episodeService.getPublished(88L)).willReturn(episode);
given(dramaService.getPublished(5L)).willReturn(drama(5L, "剧名", 10));
WatchProgress hidden = progress(5L, 88L);
hidden.setId(9L);
hidden.setUserId(7L);
hidden.setDeleted(1);
given(progressMapper.selectAny(7L, 5L)).willReturn(hidden);
given(progressMapper.selectById(9L)).willReturn(hidden);
ProgressSaveReqVO req = new ProgressSaveReqVO();
req.setEpisodeId(88L);
req.setPositionMs(1_000L);
req.setDurationMs(2_000L);
progressService.save(7L, req);
verify(progressMapper, never()).insert(any(WatchProgress.class));
verify(progressMapper).updateAny(hidden);
assertThat(hidden.getDeleted()).isZero();
}
private Drama drama(Long id, String title, int totalEpisodes) {
Drama drama = new Drama();
drama.setId(id);
drama.setTitle(title);
drama.setCoverUrl("/files/cover/" + id + ".jpg");
drama.setTotalEpisodes(totalEpisodes);
return drama;
}
private DramaEpisode episode(Long id, int epNo) {
DramaEpisode episode = new DramaEpisode();
episode.setId(id);
episode.setEpNo(epNo);
return episode;
}
}
@@ -38,13 +38,20 @@ 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/episodes/*/play", "/app/episodes/*/play",
"/app/config/**", "/app/config/**",
/* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */ /* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */
"/app/config", "/app/config",
"/app/notices", "/app/notices",
/* 服务条款与隐私协议:登录前就要能打开,按语言返回 HTML */
"/privacy/**",
"/terms/**",
/* 埋点上报:游客浏览也要记录,匿名可访问 */ /* 埋点上报:游客浏览也要记录,匿名可访问 */
"/app/events", "/app/events",
/* 媒资:封面与视频用 <img>/<video> 直接访问,无法带请求头。 /* 媒资:封面与视频用 <img>/<video> 直接访问,无法带请求头。
+4
View File
@@ -25,6 +25,10 @@
<groupId>com.fruitshorts</groupId> <groupId>com.fruitshorts</groupId>
<artifactId>fruitshorts-module-system</artifactId> <artifactId>fruitshorts-module-system</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.fruitshorts</groupId>
<artifactId>fruitshorts-module-media</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
@@ -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;
} }
@@ -0,0 +1,29 @@
// 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;
/** 运营分类:与短剧类型(drama_category)是两套独立概念。 */
@Data
@TableName("drama_classification")
public class DramaClassification {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/** 中文名称。 */
private String name;
private String nameEn;
private String nameId;
/** 已选语言的名称。 */
private String nameLocales;
private Integer sort;
private Integer status;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,22 @@
// 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("drama_classification_drama")
public class DramaClassificationDrama {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private Long classificationId;
private Long dramaId;
private LocalDateTime createdAt;
}
@@ -0,0 +1,35 @@
// 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;
/** 剧单专属分类:只服务于剧单分组,与运营分类(drama_classification)无关。 */
@Data
@TableName("drama_playlist_category")
public class DramaPlaylistCategory {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/** 中文名称,列表和唯一性都用这一列。 */
private String name;
private String nameEn;
private String nameId;
/** 中文描述。 */
private String description;
private String descriptionEn;
private String descriptionId;
/** 已选语言的名称。 */
private String nameLocales;
/** 已选语言的描述。 */
private String descriptionLocales;
private Integer sort;
private Integer status;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
@@ -0,0 +1,22 @@
// 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("drama_playlist_category_drama")
public class DramaPlaylistCategoryDrama {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private Long categoryId;
private Long dramaId;
private LocalDateTime createdAt;
}
@@ -0,0 +1,9 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.ContentTag;
public interface ContentTagMapper extends BaseMapper<ContentTag> {
}
@@ -0,0 +1,9 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.DramaClassificationDrama;
public interface DramaClassificationDramaMapper extends BaseMapper<DramaClassificationDrama> {
}
@@ -0,0 +1,9 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.DramaClassification;
public interface DramaClassificationMapper extends BaseMapper<DramaClassification> {
}
@@ -4,6 +4,46 @@ package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.DramaEpisode; import com.fruitshorts.content.dal.entity.DramaEpisode;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface DramaEpisodeMapper extends BaseMapper<DramaEpisode> { public interface DramaEpisodeMapper extends BaseMapper<DramaEpisode> {
/**
* 查询需要补转码的分集:有片源但没有可用码率产物,或缺少缩略图轴,且当前没有排队/执行中的任务。
*
* @param afterId 上一批处理到的分集 ID,用于游标轮转,避免固定前 N 条长期占用名额
* @param limit 单批上限
* @param requireFrames 是否把"缺缩略图"也视为缺失;关闭雪碧图时传 false
*/
@Select("""
<script>
SELECT e.id, e.drama_id, e.video_asset_id, e.video_url
FROM drama_episode e
WHERE e.deleted = 0
AND e.id &gt; #{afterId}
AND (e.video_asset_id &gt; 0
OR (e.video_url IS NOT NULL AND e.video_url &lt;&gt; ''))
AND NOT EXISTS (
SELECT 1 FROM transcode_task t
WHERE t.episode_id = e.id AND t.status IN ('QUEUED', 'RUNNING'))
AND (
NOT EXISTS (
SELECT 1 FROM media_rendition r
WHERE r.episode_id = e.id AND r.deleted = 0 AND r.status = 'ready')
<if test="requireFrames">
OR NOT EXISTS (
SELECT 1 FROM media_thumbnail m
WHERE m.episode_id = e.id AND m.deleted = 0)
</if>
)
ORDER BY e.id ASC
LIMIT #{limit}
</script>
""")
List<DramaEpisode> selectTranscodeBackfillCandidates(@Param("afterId") long afterId,
@Param("limit") int limit,
@Param("requireFrames") boolean requireFrames);
} }
@@ -0,0 +1,9 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.DramaPlaylistCategoryDrama;
public interface DramaPlaylistCategoryDramaMapper extends BaseMapper<DramaPlaylistCategoryDrama> {
}
@@ -0,0 +1,9 @@
// Author: fruit.com.cn
package com.fruitshorts.content.dal.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fruitshorts.content.dal.entity.DramaPlaylistCategory;
public interface DramaPlaylistCategoryMapper extends BaseMapper<DramaPlaylistCategory> {
}
@@ -0,0 +1,173 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** 内容名称的可选语言。中文必填,英文和印尼语按勾选保存。 */
public final class ContentLocaleTexts {
public static final String ZH = "zh";
public static final String EN = "en";
public static final String ID = "id";
private static final int NAME_LIMIT = 64;
private static final int TITLE_LIMIT = 80;
private static final int DESCRIPTION_LIMIT = 255;
private static final int SYNOPSIS_LIMIT = 1000;
private static final List<String> CODES = List.of(ZH, EN, ID);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final TypeReference<Map<String, String>> MAP_TYPE = new TypeReference<>() {
};
private ContentLocaleTexts() {
}
public static Map<String, String> names(Map<String, String> locales, String name,
String nameEn, String nameId) {
Map<String, String> source = locales == null ? legacy(name, nameEn, nameId) : locales;
return normalize(source, NAME_LIMIT, "名称");
}
public static Map<String, String> titles(Map<String, String> locales, String title) {
Map<String, String> source = locales == null ? legacy(title, null, null) : locales;
return normalize(source, TITLE_LIMIT, "名称");
}
public static Map<String, String> descriptions(Map<String, String> locales, Map<String, String> names,
String description, String descriptionEn,
String descriptionId) {
return optional(locales, names, description, descriptionEn, descriptionId, DESCRIPTION_LIMIT, "描述");
}
public static Map<String, String> synopses(Map<String, String> locales, Map<String, String> titles,
String synopsis) {
return optional(locales, titles, synopsis, null, null, SYNOPSIS_LIMIT, "简介");
}
private static Map<String, String> optional(Map<String, String> locales, Map<String, String> required,
String zh, String en, String id, int limit, String field) {
Map<String, String> source = locales == null ? legacy(zh, en, id) : locales;
Map<String, String> result = new LinkedHashMap<>();
for (String code : required.keySet()) {
String value = trim(source.get(code));
if (value.length() > limit) {
throw tooLong(code, field, limit);
}
if (!value.isEmpty()) {
result.put(code, value);
}
}
return result;
}
public static Map<String, String> read(String json, String zh, String en, String id) {
Map<String, String> parsed = parse(json);
Map<String, String> result = new LinkedHashMap<>();
put(result, ZH, first(parsed.get(ZH), zh));
put(result, EN, first(parsed.get(EN), en));
put(result, ID, first(parsed.get(ID), id));
return result;
}
public static String json(Map<String, String> locales) {
try {
return MAPPER.writeValueAsString(locales == null ? Map.of() : locales);
} catch (Exception ex) {
throw new ServiceException(ErrorCode.BAD_REQUEST, "语言内容无法保存");
}
}
public static String value(Map<String, String> locales, String code) {
String text = locales == null ? null : locales.get(code);
return text == null ? "" : text;
}
private static Map<String, String> normalize(Map<String, String> source, int limit, String field) {
Map<String, String> result = new LinkedHashMap<>();
for (String code : CODES) {
if (!source.containsKey(code)) {
continue;
}
String value = trim(source.get(code));
if (value.isEmpty()) {
throw new ServiceException(ErrorCode.BAD_REQUEST, "请填写" + label(code) + field);
}
if (value.length() > limit) {
throw tooLong(code, field, limit);
}
result.put(code, value);
}
rejectUnknown(source);
if (!result.containsKey(ZH)) {
throw new ServiceException(ErrorCode.BAD_REQUEST, "请选择中文并填写中文" + field);
}
return result;
}
private static Map<String, String> legacy(String zh, String en, String id) {
Map<String, String> source = new LinkedHashMap<>();
source.put(ZH, zh);
if (!trim(en).isEmpty()) {
source.put(EN, en);
}
if (!trim(id).isEmpty()) {
source.put(ID, id);
}
return source;
}
private static void rejectUnknown(Map<String, String> source) {
for (String code : source.keySet()) {
if (!CODES.contains(code)) {
throw new ServiceException(ErrorCode.BAD_REQUEST, "不支持的语言");
}
}
}
private static Map<String, String> parse(String json) {
if (json == null || json.isBlank()) {
return Map.of();
}
try {
Map<String, String> parsed = MAPPER.readValue(json, MAP_TYPE);
return parsed == null ? Map.of() : parsed;
} catch (Exception ex) {
return Map.of();
}
}
private static void put(Map<String, String> target, String code, String value) {
String text = trim(value);
if (!text.isEmpty()) {
target.put(code, text);
}
}
private static String first(String preferred, String fallback) {
return trim(preferred).isEmpty() ? fallback : preferred;
}
private static String trim(String value) {
return value == null ? "" : value.trim();
}
private static String label(String code) {
return switch (code) {
case EN -> "英文";
case ID -> "印尼语";
default -> "中文";
};
}
private static ServiceException tooLong(String code, String field, int limit) {
return new ServiceException(ErrorCode.BAD_REQUEST, label(code) + field + "最多 " + limit + " 个字符");
}
}
@@ -0,0 +1,179 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.content.dal.entity.ContentTag;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.mapper.ContentTagMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.vo.ContentTagRespVO;
import com.fruitshorts.content.vo.ContentTagSaveReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** 短剧标签。名称先选语言,中文必填,英文和印尼语按勾选填写。 */
@Service
@RequiredArgsConstructor
public class ContentTagService {
private final ContentTagMapper tagMapper;
private final DramaMapper dramaMapper;
public List<ContentTagRespVO> list() {
return tagMapper.selectList(Wrappers.<ContentTag>lambdaQuery()
.orderByAsc(ContentTag::getSort)
.orderByDesc(ContentTag::getId))
.stream()
.map(this::toResp)
.toList();
}
public List<ContentTagRespVO> listEnabled() {
return tagMapper.selectList(Wrappers.<ContentTag>lambdaQuery()
.eq(ContentTag::getStatus, 1)
.orderByAsc(ContentTag::getSort)
.orderByDesc(ContentTag::getId))
.stream()
.map(this::toResp)
.toList();
}
public Long create(ContentTagSaveReqVO req) {
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), null);
ContentTag entity = new ContentTag();
writeNames(entity, locales);
entity.setBgColor(normalizeColor(req.getBgColor()));
Long count = tagMapper.selectCount(null);
entity.setSort(req.getSort() == null
? (count == null ? 0 : count.intValue()) + 1
: req.getSort());
entity.setStatus(req.getStatus() == null ? 1 : req.getStatus());
tagMapper.insert(entity);
return entity.getId();
}
public void update(Long id, ContentTagSaveReqVO req) {
ContentTag entity = getExisting(id);
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), id);
writeNames(entity, locales);
if (req.getBgColor() != null) {
entity.setBgColor(normalizeColor(req.getBgColor()));
}
if (req.getSort() != null) {
entity.setSort(req.getSort());
}
if (req.getStatus() != null) {
entity.setStatus(req.getStatus());
}
tagMapper.updateById(entity);
}
public void delete(Long id) {
getExisting(id);
dramaMapper.update(null, Wrappers.<Drama>lambdaUpdate()
.eq(Drama::getTagId, id)
.set(Drama::getTagId, null));
tagMapper.deleteById(id);
}
/** 短剧保存时校验标签存在且启用。空 id 表示不选。 */
public void requireEnabled(Long id) {
if (id == null || id <= 0L) {
return;
}
ContentTag tag = tagMapper.selectById(id);
if (tag == null || tag.getStatus() == null || tag.getStatus() != 1) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "标签不存在或已停用");
}
}
private Map<String, String> namesOf(ContentTagSaveReqVO req) {
return ContentLocaleTexts.names(req.getLocales(), req.getName(), req.getNameEn(), req.getNameId());
}
private void writeNames(ContentTag entity, Map<String, String> locales) {
entity.setName(locales.get(ContentLocaleTexts.ZH));
entity.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
entity.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
entity.setNameLocales(ContentLocaleTexts.json(locales));
}
private String normalizeColor(String color) {
if (color == null || color.isBlank()) {
return "#E5484D";
}
return color.trim().toUpperCase();
}
private ContentTag getExisting(Long id) {
ContentTag entity = id == null ? null : tagMapper.selectById(id);
if (entity == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "标签不存在");
}
return entity;
}
private void ensureNameAvailable(String name, Long excludeId) {
Long count = tagMapper.selectCount(Wrappers.<ContentTag>lambdaQuery()
.eq(ContentTag::getName, name.trim())
.ne(excludeId != null, ContentTag::getId, excludeId));
if (count != null && count > 0) {
throw new ServiceException(ErrorCode.DATA_EXISTS, "标签名称已存在");
}
}
private ContentTagRespVO toResp(ContentTag tag) {
ContentTagRespVO vo = new ContentTagRespVO();
vo.setId(tag.getId());
Map<String, String> locales = ContentLocaleTexts.read(
tag.getNameLocales(), tag.getName(), tag.getNameEn(), tag.getNameId());
vo.setName(locales.get(ContentLocaleTexts.ZH));
vo.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
vo.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
vo.setLocales(locales);
vo.setBgColor(tag.getBgColor() == null || tag.getBgColor().isBlank() ? "#E5484D" : tag.getBgColor());
vo.setSort(tag.getSort());
vo.setStatus(tag.getStatus());
return vo;
}
/** 按 id 批量取出标签,供短剧列表带名称和背景色。 */
public Map<Long, ContentTag> findByIds(Collection<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
Map<Long, ContentTag> result = new HashMap<>();
for (ContentTag tag : tagMapper.selectBatchIds(ids)) {
if (tag != null && tag.getId() != null) {
result.put(tag.getId(), tag);
}
}
return result;
}
/** 按 id 批量取出标签语言表,供短剧列表拼卡片。 */
public Map<Long, Map<String, String>> localeMap(Collection<Long> ids) {
if (ids == null || ids.isEmpty()) {
return Map.of();
}
Map<Long, Map<String, String>> result = new HashMap<>();
for (ContentTag tag : tagMapper.selectBatchIds(ids)) {
if (tag == null || tag.getId() == null) {
continue;
}
result.put(tag.getId(), ContentLocaleTexts.read(
tag.getNameLocales(), tag.getName(), tag.getNameEn(), tag.getNameId()));
}
return result;
}
}
@@ -14,6 +14,7 @@ import com.fruitshorts.content.vo.DramaCategorySaveReqVO;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
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;
@@ -30,21 +31,15 @@ public class DramaCategoryService {
Map<Long, Integer> counts = countDramasByCategory(); Map<Long, Integer> counts = countDramasByCategory();
return dramaCategoryMapper.selectList( return dramaCategoryMapper.selectList(
Wrappers.<DramaCategory>lambdaQuery().orderByAsc(DramaCategory::getSort)) Wrappers.<DramaCategory>lambdaQuery().orderByAsc(DramaCategory::getSort))
.stream().map(category -> { .stream().map(category -> toResp(category, counts.getOrDefault(category.getId(), 0)))
DramaCategoryRespVO vo = new DramaCategoryRespVO(); .toList();
vo.setId(category.getId());
vo.setName(category.getName());
vo.setSort(category.getSort());
vo.setStatus(category.getStatus());
vo.setDramaCount(counts.getOrDefault(category.getId(), 0));
return vo;
}).toList();
} }
public Long create(DramaCategorySaveReqVO req) { public Long create(DramaCategorySaveReqVO req) {
ensureNameAvailable(req.getName(), null); Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), null);
DramaCategory category = new DramaCategory(); DramaCategory category = new DramaCategory();
category.setName(req.getName().trim()); writeNames(category, locales);
Long count = dramaCategoryMapper.selectCount(null); Long count = dramaCategoryMapper.selectCount(null);
category.setSort(req.getSort() == null category.setSort(req.getSort() == null
? (count == null ? 0 : count.intValue()) + 1 ? (count == null ? 0 : count.intValue()) + 1
@@ -61,20 +56,14 @@ public class DramaCategoryService {
public List<DramaCategoryRespVO> listBasic() { public List<DramaCategoryRespVO> listBasic() {
return dramaCategoryMapper.selectList( return dramaCategoryMapper.selectList(
Wrappers.<DramaCategory>lambdaQuery().orderByAsc(DramaCategory::getSort)) Wrappers.<DramaCategory>lambdaQuery().orderByAsc(DramaCategory::getSort))
.stream().map(category -> { .stream().map(category -> toResp(category, null)).toList();
DramaCategoryRespVO vo = new DramaCategoryRespVO();
vo.setId(category.getId());
vo.setName(category.getName());
vo.setSort(category.getSort());
vo.setStatus(category.getStatus());
return vo;
}).toList();
} }
public void update(Long id, DramaCategorySaveReqVO req) { public void update(Long id, DramaCategorySaveReqVO req) {
DramaCategory category = getExisting(id); DramaCategory category = getExisting(id);
ensureNameAvailable(req.getName(), id); Map<String, String> locales = namesOf(req);
category.setName(req.getName().trim()); ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), id);
writeNames(category, locales);
if (req.getSort() != null) { if (req.getSort() != null) {
category.setSort(req.getSort()); category.setSort(req.getSort());
} }
@@ -126,4 +115,55 @@ public class DramaCategoryService {
return dramaCategoryMapper.selectList(null).stream() return dramaCategoryMapper.selectList(null).stream()
.collect(Collectors.toMap(DramaCategory::getId, DramaCategory::getName, (a, b) -> a)); .collect(Collectors.toMap(DramaCategory::getId, DramaCategory::getName, (a, b) -> a));
} }
/** 类型 id 到已选语言名称。C 端卡片按当前语言取其中一项。 */
public Map<Long, Map<String, String>> localeMap() {
Map<Long, Map<String, String>> result = new HashMap<>();
for (DramaCategory category : dramaCategoryMapper.selectList(null)) {
result.put(category.getId(), readLocales(category));
}
return result;
}
/** 一部短剧选中的类型,按保存顺序返回语言表。 */
public List<Map<String, String>> localesForDrama(Drama drama, Map<Long, Map<String, String>> localesById) {
List<Map<String, String>> result = new ArrayList<>();
for (Long id : DramaMultiTagSupport.parseCategoryIds(drama)) {
Map<String, String> locales = localesById.get(id);
if (locales != null && !locales.isEmpty()) {
result.add(locales);
}
}
return result;
}
private DramaCategoryRespVO toResp(DramaCategory category, Integer dramaCount) {
Map<String, String> locales = readLocales(category);
DramaCategoryRespVO vo = new DramaCategoryRespVO();
vo.setId(category.getId());
vo.setName(ContentLocaleTexts.value(locales, ContentLocaleTexts.ZH));
vo.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
vo.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
vo.setLocales(locales);
vo.setSort(category.getSort());
vo.setStatus(category.getStatus());
vo.setDramaCount(dramaCount);
return vo;
}
private Map<String, String> namesOf(DramaCategorySaveReqVO req) {
return ContentLocaleTexts.names(req.getLocales(), req.getName(), req.getNameEn(), req.getNameId());
}
private void writeNames(DramaCategory category, Map<String, String> locales) {
category.setName(locales.get(ContentLocaleTexts.ZH));
category.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
category.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
category.setNameLocales(ContentLocaleTexts.json(locales));
}
private Map<String, String> readLocales(DramaCategory category) {
return ContentLocaleTexts.read(
category.getNameLocales(), category.getName(), category.getNameEn(), category.getNameId());
}
} }
@@ -0,0 +1,254 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaClassification;
import com.fruitshorts.content.dal.entity.DramaClassificationDrama;
import com.fruitshorts.content.dal.mapper.DramaClassificationDramaMapper;
import com.fruitshorts.content.dal.mapper.DramaClassificationMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaClassificationRespVO;
import com.fruitshorts.content.vo.DramaClassificationSaveReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 运营分类服务。分类是独立于「短剧类型(drama_category)」的一套概念,
* 由运营自定义增删,并通过关联表挂载任意多部短剧。
*/
@Service
@RequiredArgsConstructor
public class DramaClassificationService {
private final DramaClassificationMapper classificationMapper;
private final DramaClassificationDramaMapper classificationDramaMapper;
private final DramaMapper dramaMapper;
public List<DramaClassificationRespVO> list() {
Map<Long, Integer> counts = countDramas();
return classificationMapper.selectList(Wrappers.<DramaClassification>lambdaQuery()
.orderByAsc(DramaClassification::getSort)
.orderByDesc(DramaClassification::getId))
.stream().map(item -> {
DramaClassificationRespVO vo = new DramaClassificationRespVO();
vo.setId(item.getId());
Map<String, String> locales = ContentLocaleTexts.read(
item.getNameLocales(), item.getName(), item.getNameEn(), item.getNameId());
vo.setName(locales.get(ContentLocaleTexts.ZH));
vo.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
vo.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
vo.setLocales(locales);
vo.setSort(item.getSort());
vo.setStatus(item.getStatus());
vo.setUpdatedAt(item.getUpdatedAt());
vo.setDramaCount(counts.getOrDefault(item.getId(), 0));
return vo;
}).toList();
}
public Long create(DramaClassificationSaveReqVO req) {
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), null);
DramaClassification entity = new DramaClassification();
writeNames(entity, locales);
Long count = classificationMapper.selectCount(null);
entity.setSort(req.getSort() == null
? (count == null ? 0 : count.intValue()) + 1
: req.getSort());
entity.setStatus(req.getStatus() == null ? 1 : req.getStatus());
classificationMapper.insert(entity);
return entity.getId();
}
public void update(Long id, DramaClassificationSaveReqVO req) {
DramaClassification entity = getExisting(id);
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), id);
writeNames(entity, locales);
if (req.getSort() != null) {
entity.setSort(req.getSort());
}
if (req.getStatus() != null) {
entity.setStatus(req.getStatus());
}
classificationMapper.updateById(entity);
}
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
getExisting(id);
classificationDramaMapper.delete(Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, id));
classificationMapper.deleteById(id);
}
/** 分类下已关联的短剧(分页)。 */
public PageResult<DramaBriefVO> pageDramas(Long id, String keyword,
int pageIndex, int pageSize) {
return pageDramas(id, keyword, pageIndex, pageSize, true);
}
/** 尚未关联到该分类的短剧(分页),供「添加短剧」多选。 */
public PageResult<DramaBriefVO> pageCandidates(Long id, String keyword,
int pageIndex, int pageSize) {
return pageDramas(id, keyword, pageIndex, pageSize, false);
}
/** 批量关联短剧;已关联的自动跳过。 */
@Transactional(rollbackFor = Exception.class)
public int bindDramas(Long id, List<Long> dramaIds) {
getExisting(id);
if (dramaIds == null || dramaIds.isEmpty()) {
return 0;
}
int added = 0;
for (Long dramaId : dramaIds) {
if (dramaId == null || dramaMapper.selectById(dramaId) == null) {
continue;
}
Long exists = classificationDramaMapper.selectCount(
Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, id)
.eq(DramaClassificationDrama::getDramaId, dramaId));
if (exists != null && exists > 0) {
continue;
}
DramaClassificationDrama relation = new DramaClassificationDrama();
relation.setClassificationId(id);
relation.setDramaId(dramaId);
classificationDramaMapper.insert(relation);
added++;
}
return added;
}
/** 移出分类;短剧本身不受影响。 */
public void unbindDrama(Long id, Long dramaId) {
getExisting(id);
classificationDramaMapper.delete(Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, id)
.eq(DramaClassificationDrama::getDramaId, dramaId));
}
private PageResult<DramaBriefVO> pageDramas(Long id, String keyword,
int pageIndex, int pageSize, boolean bound) {
getExisting(id);
Page<Drama> page = new Page<>(Math.max(1, pageIndex), Math.max(1, Math.min(pageSize, 100)));
LambdaQueryWrapper<Drama> wrapper = Wrappers.<Drama>lambdaQuery()
.like(StringUtils.hasText(keyword), Drama::getTitle, keyword)
.orderByDesc(Drama::getSort)
.orderByDesc(Drama::getId);
String subQuery = "SELECT drama_id FROM drama_classification_drama WHERE classification_id = " + id;
if (bound) {
wrapper.inSql(Drama::getId, subQuery);
} else {
wrapper.notInSql(Drama::getId, subQuery);
}
IPage<Drama> result = dramaMapper.selectPage(page, wrapper);
return new PageResult<>(result.getTotal(),
result.getRecords().stream().map(this::toBrief).toList());
}
private Map<Long, Integer> countDramas() {
Map<Long, Integer> counts = new HashMap<>();
classificationDramaMapper.selectMaps(new QueryWrapper<DramaClassificationDrama>()
.select("classification_id AS cid", "COUNT(*) AS cnt")
.groupBy("classification_id"))
.forEach(row -> {
Object cid = row.get("cid");
Object cnt = row.get("cnt");
if (cid instanceof Number c && cnt instanceof Number n) {
counts.put(c.longValue(), n.intValue());
}
});
return counts;
}
private DramaClassification getExisting(Long id) {
DramaClassification entity = id == null ? null : classificationMapper.selectById(id);
if (entity == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "分类不存在");
}
return entity;
}
private Map<String, String> namesOf(DramaClassificationSaveReqVO req) {
return ContentLocaleTexts.names(req.getLocales(), req.getName(), req.getNameEn(), req.getNameId());
}
private void writeNames(DramaClassification entity, Map<String, String> locales) {
entity.setName(locales.get(ContentLocaleTexts.ZH));
entity.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
entity.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
entity.setNameLocales(ContentLocaleTexts.json(locales));
}
private void ensureNameAvailable(String name, Long excludeId) {
Long count = classificationMapper.selectCount(Wrappers.<DramaClassification>lambdaQuery()
.eq(DramaClassification::getName, name.trim())
.ne(excludeId != null, DramaClassification::getId, excludeId));
if (count != null && count > 0) {
throw new ServiceException(ErrorCode.DATA_EXISTS, "分类名称已存在");
}
}
// ========== C 端只读视图 ==========
/** C 端:只返回已启用(status=1)的分类,按 sort 升序。 */
public List<DramaClassification> listEnabled() {
return classificationMapper.selectList(Wrappers.<DramaClassification>lambdaQuery()
.eq(DramaClassification::getStatus, 1)
.orderByAsc(DramaClassification::getSort)
.orderByAsc(DramaClassification::getId));
}
/** C 端:校验分类存在且启用。 */
public DramaClassification getEnabledById(Long id) {
DramaClassification entity = getExisting(id);
if (entity.getStatus() != 1) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "分类不存在或已下架");
}
return entity;
}
/** C 端:分类下关联的全部 dramaId(按关联创建时间 desc)。 */
public List<Long> listDramaIdsByClassification(Long classificationId) {
return classificationDramaMapper.selectList(
Wrappers.<DramaClassificationDrama>lambdaQuery()
.eq(DramaClassificationDrama::getClassificationId, classificationId)
.orderByDesc(DramaClassificationDrama::getCreatedAt)
.orderByDesc(DramaClassificationDrama::getId))
.stream()
.map(DramaClassificationDrama::getDramaId)
.collect(Collectors.toList());
}
private DramaBriefVO toBrief(Drama drama) {
DramaBriefVO vo = new DramaBriefVO();
vo.setId(drama.getId());
vo.setTitle(drama.getTitle());
vo.setCover(drama.getCoverUrl());
vo.setStatus(drama.getStatus());
vo.setTotalEpisodes(drama.getTotalEpisodes());
vo.setSort(drama.getSort());
vo.setUpdatedAt(drama.getUpdatedAt());
return vo;
}
}
@@ -52,6 +52,11 @@ final class DramaMultiTagSupport {
drama.setCategoryIds(String.join(",", values.stream().map(String::valueOf).toList())); drama.setCategoryIds(String.join(",", values.stream().map(String::valueOf).toList()));
return; return;
} }
if (req.getCategoryIds() != null) {
drama.setCategoryId(0L);
drama.setCategoryIds("");
return;
}
if (drama.getCategoryId() == null) { if (drama.getCategoryId() == null) {
drama.setCategoryId(0L); drama.setCategoryId(0L);
} }
@@ -0,0 +1,265 @@
// Author: fruit.com.cn
package com.fruitshorts.content.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fruitshorts.common.exception.ErrorCode;
import com.fruitshorts.common.exception.ServiceException;
import com.fruitshorts.common.pojo.PageResult;
import com.fruitshorts.content.dal.entity.Drama;
import com.fruitshorts.content.dal.entity.DramaPlaylistCategory;
import com.fruitshorts.content.dal.entity.DramaPlaylistCategoryDrama;
import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaPlaylistCategoryDramaMapper;
import com.fruitshorts.content.dal.mapper.DramaPlaylistCategoryMapper;
import com.fruitshorts.content.vo.DramaBriefVO;
import com.fruitshorts.content.vo.DramaPlaylistCategoryRespVO;
import com.fruitshorts.content.vo.DramaPlaylistCategorySaveReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 剧单分类服务:分类直接关联短剧,没有「剧单」这一层。
* 这套分类与「类型」「分类管理」都不是同一套数据。
*/
@Service
@RequiredArgsConstructor
public class DramaPlaylistCategoryService {
private final DramaPlaylistCategoryMapper categoryMapper;
private final DramaPlaylistCategoryDramaMapper categoryDramaMapper;
private final DramaMapper dramaMapper;
public List<DramaPlaylistCategoryRespVO> list() {
Map<Long, Integer> counts = countDramas();
return categoryMapper.selectList(Wrappers.<DramaPlaylistCategory>lambdaQuery()
.orderByAsc(DramaPlaylistCategory::getSort)
.orderByDesc(DramaPlaylistCategory::getId))
.stream().map(item -> {
DramaPlaylistCategoryRespVO vo = new DramaPlaylistCategoryRespVO();
vo.setId(item.getId());
Map<String, String> locales = ContentLocaleTexts.read(
item.getNameLocales(), item.getName(), item.getNameEn(), item.getNameId());
Map<String, String> descriptions = ContentLocaleTexts.read(
item.getDescriptionLocales(), item.getDescription(),
item.getDescriptionEn(), item.getDescriptionId());
vo.setName(locales.get(ContentLocaleTexts.ZH));
vo.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
vo.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
vo.setLocales(locales);
vo.setDescription(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.ZH));
vo.setDescriptionEn(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.EN));
vo.setDescriptionId(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.ID));
vo.setDescriptionLocales(descriptions);
vo.setSort(item.getSort());
vo.setStatus(item.getStatus());
vo.setDramaCount(counts.getOrDefault(item.getId(), 0));
return vo;
}).toList();
}
public Long create(DramaPlaylistCategorySaveReqVO req) {
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), null);
DramaPlaylistCategory entity = new DramaPlaylistCategory();
writeText(entity, req, locales);
Long count = categoryMapper.selectCount(null);
entity.setSort(req.getSort() == null
? (count == null ? 0 : count.intValue()) + 1
: req.getSort());
entity.setStatus(req.getStatus() == null ? 1 : req.getStatus());
categoryMapper.insert(entity);
return entity.getId();
}
public void update(Long id, DramaPlaylistCategorySaveReqVO req) {
DramaPlaylistCategory entity = getExisting(id);
Map<String, String> locales = namesOf(req);
ensureNameAvailable(locales.get(ContentLocaleTexts.ZH), id);
writeText(entity, req, locales);
if (req.getSort() != null) {
entity.setSort(req.getSort());
}
if (req.getStatus() != null) {
entity.setStatus(req.getStatus());
}
categoryMapper.updateById(entity);
}
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
getExisting(id);
categoryDramaMapper.delete(Wrappers.<DramaPlaylistCategoryDrama>lambdaQuery()
.eq(DramaPlaylistCategoryDrama::getCategoryId, id));
categoryMapper.deleteById(id);
}
/** 分类下已关联的短剧(分页)。 */
public PageResult<DramaBriefVO> pageDramas(Long id, String keyword,
int pageIndex, int pageSize) {
return pageDramas(id, keyword, pageIndex, pageSize, true);
}
/** 尚未关联到该分类的短剧(分页),供「选择短剧」多选。 */
public PageResult<DramaBriefVO> pageCandidates(Long id, String keyword,
int pageIndex, int pageSize) {
return pageDramas(id, keyword, pageIndex, pageSize, false);
}
/** 批量把短剧加入分类;已关联的自动跳过。 */
@Transactional(rollbackFor = Exception.class)
public int bindDramas(Long id, List<Long> dramaIds) {
getExisting(id);
if (dramaIds == null || dramaIds.isEmpty()) {
return 0;
}
int added = 0;
for (Long dramaId : dramaIds) {
if (dramaId == null || dramaMapper.selectById(dramaId) == null) {
continue;
}
Long exists = categoryDramaMapper.selectCount(
Wrappers.<DramaPlaylistCategoryDrama>lambdaQuery()
.eq(DramaPlaylistCategoryDrama::getCategoryId, id)
.eq(DramaPlaylistCategoryDrama::getDramaId, dramaId));
if (exists != null && exists > 0) {
continue;
}
DramaPlaylistCategoryDrama relation = new DramaPlaylistCategoryDrama();
relation.setCategoryId(id);
relation.setDramaId(dramaId);
categoryDramaMapper.insert(relation);
added++;
}
return added;
}
/** 把短剧移出分类;短剧本身不受影响。 */
public void unbindDrama(Long id, Long dramaId) {
getExisting(id);
categoryDramaMapper.delete(Wrappers.<DramaPlaylistCategoryDrama>lambdaQuery()
.eq(DramaPlaylistCategoryDrama::getCategoryId, id)
.eq(DramaPlaylistCategoryDrama::getDramaId, dramaId));
}
private PageResult<DramaBriefVO> pageDramas(Long id, String keyword,
int pageIndex, int pageSize, boolean bound) {
getExisting(id);
Page<Drama> page = new Page<>(Math.max(1, pageIndex), Math.max(1, Math.min(pageSize, 100)));
LambdaQueryWrapper<Drama> wrapper = Wrappers.<Drama>lambdaQuery()
.like(StringUtils.hasText(keyword), Drama::getTitle, keyword)
.orderByDesc(Drama::getSort)
.orderByDesc(Drama::getId);
String subQuery = "SELECT drama_id FROM drama_playlist_category_drama WHERE category_id = " + id;
if (bound) {
wrapper.inSql(Drama::getId, subQuery);
} else {
wrapper.notInSql(Drama::getId, subQuery);
}
IPage<Drama> result = dramaMapper.selectPage(page, wrapper);
return new PageResult<>(result.getTotal(),
result.getRecords().stream().map(this::toBrief).toList());
}
private Map<Long, Integer> countDramas() {
Map<Long, Integer> counts = new HashMap<>();
categoryDramaMapper.selectMaps(new QueryWrapper<DramaPlaylistCategoryDrama>()
.select("category_id AS cid", "COUNT(*) AS cnt")
.groupBy("category_id"))
.forEach(row -> {
Object cid = row.get("cid");
Object cnt = row.get("cnt");
if (cid instanceof Number c && cnt instanceof Number n) {
counts.put(c.longValue(), n.intValue());
}
});
return counts;
}
/** C 端用:已启用剧单,按排序升序、再按 id 倒序。 */
public List<DramaPlaylistCategory> listEnabled() {
return categoryMapper.selectList(Wrappers.<DramaPlaylistCategory>lambdaQuery()
.eq(DramaPlaylistCategory::getStatus, 1)
.orderByAsc(DramaPlaylistCategory::getSort)
.orderByDesc(DramaPlaylistCategory::getId));
}
/** C 端用:只返回已启用(status=1)的剧单。 */
public DramaPlaylistCategory getEnabledById(Long id) {
DramaPlaylistCategory entity = getExisting(id);
if (entity.getStatus() == null || entity.getStatus() != 1) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "剧单不存在或已下架");
}
return entity;
}
/** C 端用:剧单下关联的全部 dramaId(按 created_at desc)。 */
public List<Long> listDramaIdsByCategory(Long categoryId) {
return categoryDramaMapper.selectList(Wrappers.<DramaPlaylistCategoryDrama>lambdaQuery()
.eq(DramaPlaylistCategoryDrama::getCategoryId, categoryId)
.orderByDesc(DramaPlaylistCategoryDrama::getCreatedAt)
.orderByDesc(DramaPlaylistCategoryDrama::getId))
.stream()
.map(DramaPlaylistCategoryDrama::getDramaId)
.collect(Collectors.toList());
}
private DramaPlaylistCategory getExisting(Long id) {
DramaPlaylistCategory entity = id == null ? null : categoryMapper.selectById(id);
if (entity == null) {
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "剧单分类不存在");
}
return entity;
}
private Map<String, String> namesOf(DramaPlaylistCategorySaveReqVO req) {
return ContentLocaleTexts.names(req.getLocales(), req.getName(), req.getNameEn(), req.getNameId());
}
private void writeText(DramaPlaylistCategory entity, DramaPlaylistCategorySaveReqVO req,
Map<String, String> locales) {
Map<String, String> descriptions = ContentLocaleTexts.descriptions(
req.getDescriptionLocales(), locales,
req.getDescription(), req.getDescriptionEn(), req.getDescriptionId());
entity.setName(locales.get(ContentLocaleTexts.ZH));
entity.setNameEn(ContentLocaleTexts.value(locales, ContentLocaleTexts.EN));
entity.setNameId(ContentLocaleTexts.value(locales, ContentLocaleTexts.ID));
entity.setNameLocales(ContentLocaleTexts.json(locales));
entity.setDescription(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.ZH));
entity.setDescriptionEn(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.EN));
entity.setDescriptionId(ContentLocaleTexts.value(descriptions, ContentLocaleTexts.ID));
entity.setDescriptionLocales(ContentLocaleTexts.json(descriptions));
}
private void ensureNameAvailable(String name, Long excludeId) {
Long count = categoryMapper.selectCount(Wrappers.<DramaPlaylistCategory>lambdaQuery()
.eq(DramaPlaylistCategory::getName, name.trim())
.ne(excludeId != null, DramaPlaylistCategory::getId, excludeId));
if (count != null && count > 0) {
throw new ServiceException(ErrorCode.DATA_EXISTS, "剧单分类名称已存在");
}
}
private DramaBriefVO toBrief(Drama drama) {
DramaBriefVO vo = new DramaBriefVO();
vo.setId(drama.getId());
vo.setTitle(drama.getTitle());
vo.setCover(drama.getCoverUrl());
vo.setStatus(drama.getStatus());
vo.setTotalEpisodes(drama.getTotalEpisodes());
vo.setSort(drama.getSort());
vo.setUpdatedAt(drama.getUpdatedAt());
return vo;
}
}
@@ -10,9 +10,11 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.pojo.PageResult; import com.fruitshorts.common.pojo.PageResult;
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.dal.entity.DramaReviewRecord; import com.fruitshorts.content.dal.entity.DramaReviewRecord;
import com.fruitshorts.content.dal.mapper.ContentTagMapper;
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper; import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.content.dal.mapper.DramaMapper; import com.fruitshorts.content.dal.mapper.DramaMapper;
import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper; import com.fruitshorts.content.dal.mapper.DramaReviewRecordMapper;
@@ -28,20 +30,27 @@ import org.springframework.util.StringUtils;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class DramaService { public class DramaService {
private static final DateTimeFormatter CODE_DATE = DateTimeFormatter.ofPattern("yyyyMMdd"); private static final DateTimeFormatter CODE_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
/** 全部短剧单页上限,与分类频道分页一致。 */
private static final int PUBLISHED_PAGE_SIZE_MAX = 50;
private final DramaMapper dramaMapper; private final DramaMapper dramaMapper;
private final DramaEpisodeMapper dramaEpisodeMapper; private final DramaEpisodeMapper dramaEpisodeMapper;
private final DramaReviewRecordMapper dramaReviewRecordMapper; private final DramaReviewRecordMapper dramaReviewRecordMapper;
private final DramaCategoryService dramaCategoryService; private final DramaCategoryService dramaCategoryService;
private final ContentTagMapper contentTagMapper;
private final ContentTagService contentTagService;
private final EpisodePriceSync episodePriceSync; private final EpisodePriceSync episodePriceSync;
public PageResult<DramaRespVO> page(DramaPageReqVO req) { public PageResult<DramaRespVO> page(DramaPageReqVO req) {
@@ -122,6 +131,11 @@ public class DramaService {
} }
dramaMapper.updateById(drama); dramaMapper.updateById(drama);
episodePriceSync.syncByDramaRule(drama); episodePriceSync.syncByDramaRule(drama);
if (req.getTagId() != null && req.getTagId() <= 0L) {
dramaMapper.update(null, Wrappers.<Drama>lambdaUpdate()
.eq(Drama::getId, drama.getId())
.set(Drama::getTagId, null));
}
} }
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
@@ -226,6 +240,75 @@ public class DramaService {
return dramaMapper.selectPage(page, wrapper).getRecords(); return dramaMapper.selectPage(page, wrapper).getRecords();
} }
/** C 端全部短剧:类型、分类、标签多选。 */
public PageResult<Drama> pagePublishedLibrary(List<Long> categoryIds, List<Long> classificationIds,
List<Long> tagIds, int pageIndex, int pageSize) {
int safeIndex = Math.max(1, pageIndex);
int safeSize = Math.max(1, Math.min(pageSize, PUBLISHED_PAGE_SIZE_MAX));
Page<Drama> page = new Page<>(safeIndex, safeSize);
LambdaQueryWrapper<Drama> wrapper = Wrappers.<Drama>lambdaQuery()
.eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode());
applyLibraryFilters(wrapper, categoryIds, classificationIds, tagIds);
wrapper.orderByDesc(Drama::getSort).orderByDesc(Drama::getId);
IPage<Drama> result = dramaMapper.selectPage(page, wrapper);
return new PageResult<>(result.getTotal(), result.getRecords());
}
private void applyLibraryFilters(LambdaQueryWrapper<Drama> wrapper, List<Long> categoryIds,
List<Long> classificationIds, List<Long> tagIds) {
List<Long> types = positiveIds(categoryIds);
if (!types.isEmpty()) {
DramaMultiTagSupport.applyCategoryIdTokens(wrapper, types);
}
List<Long> tags = positiveIds(tagIds);
if (!tags.isEmpty()) {
wrapper.in(Drama::getTagId, tags);
}
List<Long> classes = positiveIds(classificationIds);
if (!classes.isEmpty()) {
wrapper.apply(classificationInClause(classes.size()), classes.toArray());
}
}
/**
* 分类关联用占位符,id 不拼进 SQL。
*/
static String classificationInClause(int size) {
StringBuilder sql = new StringBuilder(
"id IN (SELECT drama_id FROM drama_classification_drama WHERE classification_id IN (");
for (int index = 0; index < size; index++) {
if (index > 0) {
sql.append(',');
}
sql.append('{').append(index).append('}');
}
sql.append("))");
return sql.toString();
}
private List<Long> positiveIds(List<Long> ids) {
if (ids == null || ids.isEmpty()) {
return List.of();
}
return ids.stream().filter(id -> id != null && id > 0L).distinct().toList();
}
/** C 端分类频道:按分类分页查已上线短剧,含 total。 */
public PageResult<Drama> pagePublishedByCategory(Long categoryId, int pageIndex, int pageSize) {
int safeIndex = Math.max(1, pageIndex);
int safeSize = Math.max(1, Math.min(pageSize, PUBLISHED_PAGE_SIZE_MAX));
Page<Drama> page = new Page<>(safeIndex, safeSize);
LambdaQueryWrapper<Drama> wrapper = Wrappers.<Drama>lambdaQuery()
.eq(Drama::getStatus, ContentStatus.PUBLISHED.getCode());
if (categoryId != null && categoryId > 0) {
DramaMultiTagSupport.applyCategoryIdTokens(wrapper, List.of(categoryId));
}
wrapper.orderByDesc(Drama::getSort).orderByDesc(Drama::getViewCount)
.orderByDesc(Drama::getId);
IPage<Drama> result = dramaMapper.selectPage(page, wrapper);
return new PageResult<>(result.getTotal(), result.getRecords());
}
/** 已上线短剧,按上线时间倒序 */ /** 已上线短剧,按上线时间倒序 */
public List<Drama> listPublishedLatest(long limit) { public List<Drama> listPublishedLatest(long limit) {
Page<Drama> page = new Page<>(1, Math.max(1, limit)); Page<Drama> page = new Page<>(1, Math.max(1, limit));
@@ -353,7 +436,13 @@ public class DramaService {
* 避免编辑表单没带 sort / language / trailerUrl 时把已有数据清掉。 * 避免编辑表单没带 sort / language / trailerUrl 时把已有数据清掉。
*/ */
private void apply(Drama drama, DramaSaveReqVO req, boolean isNew) { private void apply(Drama drama, DramaSaveReqVO req, boolean isNew) {
if (req.getTitleLocales() != null) {
Map<String, String> titles = ContentLocaleTexts.titles(req.getTitleLocales(), req.getTitle());
drama.setTitle(titles.get(ContentLocaleTexts.ZH));
drama.setTitleLocales(ContentLocaleTexts.json(titles));
} else if (isNew || req.getTitle() != null) {
drama.setTitle(req.getTitle()); drama.setTitle(req.getTitle());
}
if (isNew || req.getSubtitle() != null) { if (isNew || req.getSubtitle() != null) {
drama.setSubtitle(req.getSubtitle() == null ? "" : req.getSubtitle()); drama.setSubtitle(req.getSubtitle() == null ? "" : req.getSubtitle());
} }
@@ -363,7 +452,13 @@ public class DramaService {
if (isNew || req.getGenre() != null) { if (isNew || req.getGenre() != null) {
drama.setGenre(req.getGenre() == null ? "" : req.getGenre()); drama.setGenre(req.getGenre() == null ? "" : req.getGenre());
} }
if (isNew || req.getDescription() != null) { if (req.getSynopsisLocales() != null) {
Map<String, String> titles = ContentLocaleTexts.titles(req.getTitleLocales(), req.getTitle());
Map<String, String> synopses = ContentLocaleTexts.synopses(
req.getSynopsisLocales(), titles, req.getDescription());
drama.setSynopsis(ContentLocaleTexts.value(synopses, ContentLocaleTexts.ZH));
drama.setSynopsisLocales(ContentLocaleTexts.json(synopses));
} else if (isNew || req.getDescription() != null) {
drama.setSynopsis(req.getDescription() == null ? "" : req.getDescription()); drama.setSynopsis(req.getDescription() == null ? "" : req.getDescription());
} }
if (isNew || req.getCover() != null) { if (isNew || req.getCover() != null) {
@@ -379,6 +474,10 @@ public class DramaService {
if (isNew || req.getDramaTypes() != null || req.getDramaType() != null) { if (isNew || req.getDramaTypes() != null || req.getDramaType() != null) {
DramaMultiTagSupport.applyDramaTypes(drama, req); DramaMultiTagSupport.applyDramaTypes(drama, req);
} }
if (isNew || req.getTagId() != null) {
contentTagService.requireEnabled(req.getTagId());
drama.setTagId(req.getTagId() != null && req.getTagId() > 0L ? req.getTagId() : null);
}
if (isNew || req.getFreeEpisodes() != null) { if (isNew || req.getFreeEpisodes() != null) {
drama.setFreeEpisodes(req.getFreeEpisodes() == null ? 3 : req.getFreeEpisodes()); drama.setFreeEpisodes(req.getFreeEpisodes() == null ? 3 : req.getFreeEpisodes());
} }
@@ -404,11 +503,10 @@ public class DramaService {
return List.of(); return List.of();
} }
Map<Long, String> categories = dramaCategoryService.nameMap(); Map<Long, String> categories = dramaCategoryService.nameMap();
Map<Long, ContentTag> tags = loadTags(dramas);
return dramas.stream().map(drama -> { return dramas.stream().map(drama -> {
List<Long> categoryIds = DramaMultiTagSupport.parseCategoryIds(drama); List<Long> categoryIds = DramaMultiTagSupport.parseCategoryIds(drama);
Long primaryCategoryId = categoryIds.isEmpty() Long primaryCategoryId = categoryIds.isEmpty() ? null : categoryIds.get(0);
? (drama.getCategoryId() == null ? 0L : drama.getCategoryId())
: categoryIds.get(0);
List<String> categoryNames = List<String> categoryNames =
DramaMultiTagSupport.categoryNames(drama, categoryIds, categories); DramaMultiTagSupport.categoryNames(drama, categoryIds, categories);
List<String> dramaTypes = DramaMultiTagSupport.parseDramaTypes(drama); List<String> dramaTypes = DramaMultiTagSupport.parseDramaTypes(drama);
@@ -416,19 +514,28 @@ public class DramaService {
vo.setId(drama.getId()); vo.setId(drama.getId());
vo.setCode(drama.getCode()); vo.setCode(drama.getCode());
vo.setTitle(drama.getTitle()); vo.setTitle(drama.getTitle());
vo.setSubtitle(drama.getSubtitle()); Map<String, String> titles = ContentLocaleTexts.read(
drama.getTitleLocales(), drama.getTitle(), null, null);
Map<String, String> synopses = ContentLocaleTexts.read(
drama.getSynopsisLocales(), drama.getSynopsis(), null, null);
vo.setTitle(ContentLocaleTexts.value(titles, ContentLocaleTexts.ZH));
vo.setTitleLocales(titles);
vo.setCategoryId(primaryCategoryId); vo.setCategoryId(primaryCategoryId);
vo.setCategoryIds(categoryIds); vo.setCategoryIds(categoryIds);
vo.setCategoryNames(categoryNames); vo.setCategoryNames(categoryNames);
vo.setCategory(categories.getOrDefault(primaryCategoryId, "")); vo.setCategory(primaryCategoryId == null ? "" : categories.getOrDefault(primaryCategoryId, ""));
vo.setGenre(drama.getGenre()); vo.setGenre(drama.getGenre());
vo.setDescription(drama.getSynopsis()); vo.setDescription(drama.getSynopsis());
vo.setDescription(ContentLocaleTexts.value(synopses, ContentLocaleTexts.ZH));
vo.setSynopsisLocales(synopses);
vo.setSubtitle(drama.getSubtitle());
vo.setCover(drama.getCoverUrl()); vo.setCover(drama.getCoverUrl());
vo.setTrailerUrl(drama.getTrailerUrl()); vo.setTrailerUrl(drama.getTrailerUrl());
vo.setLanguage(drama.getLanguage()); vo.setLanguage(drama.getLanguage());
vo.setDramaType(dramaTypes.get(0)); vo.setDramaType(dramaTypes.get(0));
vo.setDramaTypes(dramaTypes); vo.setDramaTypes(dramaTypes);
vo.setEpisodes(drama.getTotalEpisodes()); vo.setEpisodes(drama.getTotalEpisodes());
fillTag(vo, drama.getTagId() == null ? null : tags.get(drama.getTagId()));
vo.setFreeEpisodes(drama.getFreeEpisodes()); vo.setFreeEpisodes(drama.getFreeEpisodes());
vo.setUnlockCoin(drama.getUnlockCoin()); vo.setUnlockCoin(drama.getUnlockCoin());
vo.setIsHot(drama.getIsHot() != null && drama.getIsHot() == 1); vo.setIsHot(drama.getIsHot() != null && drama.getIsHot() == 1);
@@ -464,6 +571,29 @@ public class DramaService {
} }
} }
private Map<Long, ContentTag> loadTags(List<Drama> dramas) {
List<Long> ids = dramas.stream()
.map(Drama::getTagId)
.filter(id -> id != null && id > 0L)
.distinct()
.toList();
if (ids.isEmpty()) {
return new HashMap<>();
}
return contentTagMapper.selectBatchIds(ids).stream()
.collect(Collectors.toMap(ContentTag::getId, Function.identity(), (left, right) -> left));
}
private void fillTag(DramaRespVO vo, ContentTag tag) {
if (tag == null) {
return;
}
vo.setTagId(tag.getId());
vo.setTagName(tag.getName());
vo.setTagNameEn(tag.getNameEn());
vo.setTagNameId(tag.getNameId());
}
private Long nonNegativeOrZero(Long value, String fieldName) { private Long nonNegativeOrZero(Long value, String fieldName) {
return value == null ? 0L : nonNegative(value, fieldName); return value == null ? 0L : nonNegative(value, fieldName);
} }
@@ -15,6 +15,9 @@ import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
import com.fruitshorts.content.enums.ContentStatus; import com.fruitshorts.content.enums.ContentStatus;
import com.fruitshorts.content.vo.EpisodeRespVO; import com.fruitshorts.content.vo.EpisodeRespVO;
import com.fruitshorts.content.vo.EpisodeSaveReqVO; import com.fruitshorts.content.vo.EpisodeSaveReqVO;
import com.fruitshorts.media.service.EpisodeTranscodeBindingService;
import com.fruitshorts.media.service.EpisodeTranscodeCompletionPort;
import com.fruitshorts.media.service.EpisodeVideoSourcePort;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -29,7 +32,7 @@ import java.util.Objects;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class EpisodeService { public class EpisodeService implements EpisodeTranscodeCompletionPort, EpisodeVideoSourcePort {
private static final int DEFAULT_PAGE_INDEX = 1; private static final int DEFAULT_PAGE_INDEX = 1;
private static final int DEFAULT_PAGE_SIZE = 100; private static final int DEFAULT_PAGE_SIZE = 100;
@@ -37,6 +40,37 @@ public class EpisodeService {
private final DramaEpisodeMapper dramaEpisodeMapper; private final DramaEpisodeMapper dramaEpisodeMapper;
private final DramaService dramaService; private final DramaService dramaService;
private final EpisodeTranscodeBindingService transcodeBindingService;
@Override
public java.util.Optional<EpisodeVideoSource> resolveByVideoUrl(String videoUrl) {
if (!StringUtils.hasText(videoUrl)) {
return java.util.Optional.empty();
}
DramaEpisode episode = dramaEpisodeMapper.selectOne(Wrappers.<DramaEpisode>lambdaQuery()
.eq(DramaEpisode::getVideoUrl, videoUrl)
.last("limit 1"));
return episode == null
? java.util.Optional.empty()
: java.util.Optional.of(toVideoSource(episode));
}
private EpisodeVideoSource toVideoSource(DramaEpisode episode) {
return new EpisodeVideoSource(
episode.getId(), episode.getDramaId(), episode.getVideoAssetId(),
episode.getVideoUrl(), episode.getDurationSec());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void link(Long episodeId, Long mediaAssetId) {
if (episodeId == null || episodeId <= 0 || mediaAssetId == null || mediaAssetId <= 0) {
return;
}
dramaEpisodeMapper.update(null, Wrappers.<DramaEpisode>lambdaUpdate()
.eq(DramaEpisode::getId, episodeId)
.set(DramaEpisode::getVideoAssetId, mediaAssetId));
}
/** 后台:按短剧分页查询分集,status 在 SQL 层过滤;排序稳定(sort、ep_no)。 */ /** 后台:按短剧分页查询分集,status 在 SQL 层过滤;排序稳定(sort、ep_no)。 */
public PageResult<EpisodeRespVO> pageByDrama(Long dramaId, String status, public PageResult<EpisodeRespVO> pageByDrama(Long dramaId, String status,
@@ -135,6 +169,7 @@ public class EpisodeService {
episode.setLikeCount(nonNegativeOrZero(req.getLikeCount())); episode.setLikeCount(nonNegativeOrZero(req.getLikeCount()));
episode.setVideoAssetId(0L); episode.setVideoAssetId(0L);
dramaEpisodeMapper.insert(episode); dramaEpisodeMapper.insert(episode);
bindTranscodeTask(episode);
dramaService.syncTotalEpisodes(req.getDramaId()); dramaService.syncTotalEpisodes(req.getDramaId());
return episode.getId(); return episode.getId();
} }
@@ -152,6 +187,7 @@ public class EpisodeService {
episode.setStatus(req.getStatus()); episode.setStatus(req.getStatus());
} }
dramaEpisodeMapper.updateById(episode); dramaEpisodeMapper.updateById(episode);
bindTranscodeTask(episode);
if (!req.getDramaId().equals(episode.getDramaId())) { if (!req.getDramaId().equals(episode.getDramaId())) {
dramaService.syncTotalEpisodes(req.getDramaId()); dramaService.syncTotalEpisodes(req.getDramaId());
} }
@@ -252,6 +288,32 @@ public class EpisodeService {
episode.setSort(req.getSort() == null ? (req.getNumber() == null ? 0 : req.getNumber()) : req.getSort()); episode.setSort(req.getSort() == null ? (req.getNumber() == null ? 0 : req.getNumber()) : req.getSort());
} }
private void bindTranscodeTask(DramaEpisode episode) {
Long assetId = transcodeBindingService.bind(
episode.getId(), episode.getDramaId(), episode.getVideoUrl());
if (assetId != null && assetId > 0
&& !Objects.equals(assetId, episode.getVideoAssetId())) {
episode.setVideoAssetId(assetId);
dramaEpisodeMapper.updateById(episode);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void markEpisodeReady(Long episodeId, String hlsUrl, Integer durationSec) {
if (episodeId == null || episodeId <= 0 || !StringUtils.hasText(hlsUrl)) {
return;
}
var update = Wrappers.<DramaEpisode>lambdaUpdate()
.eq(DramaEpisode::getId, episodeId)
.set(DramaEpisode::getHlsUrl, hlsUrl)
.set(DramaEpisode::getTranscodeStatus, "success");
if (durationSec != null && durationSec > 0) {
update.set(DramaEpisode::getDurationSec, durationSec);
}
dramaEpisodeMapper.update(null, update);
}
private EpisodeRespVO toResp(DramaEpisode episode) { private EpisodeRespVO toResp(DramaEpisode episode) {
EpisodeRespVO vo = new EpisodeRespVO(); EpisodeRespVO vo = new EpisodeRespVO();
vo.setId(episode.getId()); vo.setId(episode.getId());
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more