Compare commits
21
Commits
15b540cdd6
...
v0.9.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
272aa62434 | ||
|
|
a41ab18636 | ||
|
|
8999ff395d | ||
|
|
229f1d0198 | ||
|
|
2dadca6288 | ||
|
|
2cf8f9a1c3 | ||
|
|
d9a1670a72 | ||
|
|
5ff4626b33 | ||
|
|
6bbde0b100 | ||
|
|
884324b8fd | ||
|
|
7baaeddf26 | ||
|
|
99d49a1765 | ||
|
|
92f7606f65 | ||
|
|
c2ba3df47c | ||
|
|
226dc275bb | ||
|
|
7a2ff3f80e | ||
|
|
23321a0b0c | ||
|
|
5d44ac239b | ||
|
|
848c746505 | ||
|
|
4b0fbd73d3 | ||
|
|
2fe24b9db7 |
No files matched your search
@@ -19,3 +19,4 @@ data/uploads/*
|
||||
|
||||
# 部署用的真实环境变量(含密钥),只提交 .env.example
|
||||
.env
|
||||
dump.rdb
|
||||
+120
-21
@@ -115,6 +115,8 @@ POST /app/auth/register
|
||||
| 密码强度 | 8–64 位,且**同时包含字母与数字**(不强制特殊字符:低端机输入成本高,拦机器注册靠频控) |
|
||||
| 注册频控 | 同 IP / 同设备 24h 默认上限分别为 5 / 3 个,超出返回 `429`(`TOO_MANY_REQUESTS`) |
|
||||
| 邮箱验证状态 | 免码注册时 `app_user_credential.verified = 0`(保留"待验证"),**不阻塞登录**;只有**验证码登录**会把 `verified` 置 1,密码登录不改变该状态 |
|
||||
| 国家 / 语言 / 时区 / 币种 | 优先按客户端 IP(`X-Forwarded-For` / `X-Real-IP`,离线 ip2region)解析国家;内网或解析失败才用请求体 `countryCode`(ISO-2),最后兜底 `ID`。`language` / `timezone` / `currency` 随国家映射,不再写死 `id-ID` / `IDR` |
|
||||
| 登录时修正国家 | `/app/auth/login`、`/app/auth/google` 会用 IP 重新解析国家并更新 `country_code` / `region_code`(历史账号下次登录即自愈);`language` / `timezone` / `currency` 只在仍是旧国家映射值时才同步,用户自己改过就保留 |
|
||||
|
||||
频控口径落库在 `app_user.register_ip` / `app_user.register_device_id` 上(按 24h 计数,不新建计数表)。
|
||||
|
||||
@@ -286,7 +288,8 @@ app.register.max-per-device-per-day
|
||||
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/app/episodes/{id}/play` | 可选 | 签发播放票据与签名地址 |
|
||||
| GET | `/app/episodes/{id}/play` | 免费集可选;锁定集必须登录 | 签发播放票据与签名地址 |
|
||||
| GET | `/app/episodes/{id}/stats` | 可选 | 播放页轻量计数快照,不签发地址、不写票据缓存 |
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -310,8 +313,10 @@ app.register.max-per-device-per-day
|
||||
}
|
||||
```
|
||||
|
||||
`accessType` 取值:`FREE`(免费集)、`ENTITLED`(已购权益)、`COIN_REQUIRED`(需解锁,
|
||||
此时 `playUrl` 为空、`unlockCoin` 有值)、`NO_MEDIA`(还没上传片源或未转码完成)。
|
||||
`accessType` 取值:`FREE`(免费集)、`ENTITLED`(已购权益)、`COIN_REQUIRED`(已登录但
|
||||
尚未解锁,此时 `playUrl` 为空、`unlockCoin` 有值)、`NO_MEDIA`(已登录用户访问的剧集还
|
||||
没上传片源或未转码完成)。未登录请求锁定集在查询片源前直接返回 `UNAUTHORIZED`,不会
|
||||
按设备身份取票或降级为匿名播放。
|
||||
|
||||
**判定顺序由服务端决定,客户端不得自行推断可否播放。** 签名默认 15 分钟有效;
|
||||
开启 `fruitshorts.media.signature-required` 后,`/files/episode/**` 没带有效签名会返回 403。
|
||||
@@ -320,23 +325,86 @@ app.register.max-per-device-per-day
|
||||
`sprite_XXX.jpg#xywh=x,y,w,h`。有 READY `media_thumbnail` 时返回签名地址,
|
||||
无产物时为 `null`;该字段不影响 `playUrl`、`qualities` 和 HLS/原文件回落。
|
||||
|
||||
**`GET /app/episodes/{id}/stats`(播放页计数刷新)**
|
||||
|
||||
只读返回本集点赞数、本集未删除评论数、所属剧收藏数,以及当前用户对
|
||||
本集/所属剧的互动状态。已登录时按账号读取;匿名请求时按 `X-Device-Id`
|
||||
读取设备互动状态,未带设备号时 `liked`、`favorited` 均为 `false`。
|
||||
接口不生成播放签名地址、不写 `playback_ticket` 缓存,计数变化后立即可读。
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"data": {
|
||||
"episodeId": "12",
|
||||
"dramaId": "5",
|
||||
"likeCount": "45",
|
||||
"commentCount": "8",
|
||||
"favoriteCount": "1800",
|
||||
"liked": true,
|
||||
"favorited": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`likeCount`、`commentCount`、`favoriteCount` 与其他计数一样按 Long 字符串下发。
|
||||
|
||||
### 1.5 观看记录与收藏(已实现)
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/app/watch/progress` | 上报进度(建议每 10s 一次,切集时补一次) |
|
||||
| GET | `/app/watch/progress?dramaId=` | 某剧续看位置 |
|
||||
| GET | `/app/watch/recent` | 最近观看分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
|
||||
| DELETE | `/app/watch/progress/{dramaId}` | 删除某剧记录 |
|
||||
| DELETE | `/app/watch/progress` | 清空记录 |
|
||||
| POST | `/app/favorites/toggle` | 收藏/取消收藏,返回切换后状态 |
|
||||
| GET | `/app/favorites` | 收藏分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
|
||||
| DELETE | `/app/favorites/{dramaId}` | 取消收藏 |
|
||||
| POST | `/app/favorites/remove` | 批量取消收藏,请求体 `{ "dramaIds": ["12", "15"] }` |
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| POST | `/app/watch/progress` | 可选登录 | 上报进度;匿名按 `X-Device-Id`,建议每 10s 一次,切集时补一次 |
|
||||
| GET | `/app/watch/progress?dramaId=` | 可选登录 | 某剧续看位置,匿名按设备读取 |
|
||||
| GET | `/app/watch/recent` | 可选登录 | 最近观看分页;`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
|
||||
| DELETE | `/app/watch/progress/{dramaId}` | 可选登录 | 删除当前账号或设备的某剧记录 |
|
||||
| DELETE | `/app/watch/progress` | 可选登录 | 清空当前账号或设备的记录 |
|
||||
| POST | `/app/favorites/toggle` | 可选登录 | 收藏/取消收藏,返回切换后状态;匿名按 `X-Device-Id` |
|
||||
| GET | `/app/favorites` | 可选登录 | 收藏分页;匿名按设备读取,`pageIndex` 默认 1,`pageSize` 默认 20、上限 100 |
|
||||
| DELETE | `/app/favorites/{dramaId}` | 可选登录 | 取消收藏;匿名按 `X-Device-Id` |
|
||||
| POST | `/app/favorites/remove` | 可选登录 | 批量取消收藏;匿名按 `X-Device-Id`,返回实际删除数量 |
|
||||
|
||||
进度合并规则:同一集内只前进不后退;换集直接采纳新集;`finished` 只在接近片尾或客户端显式上报时置位。
|
||||
这样用户换设备不会看到进度倒退。
|
||||
|
||||
收藏与观看数据的身份解析顺序统一为登录 `userId` → `X-Device-Id` → 请求参数或请求体
|
||||
`deviceId`,全部缺失时返回业务码 `200007`。匿名读取不按设备限流;上报、删除和清空等写操作
|
||||
沿用设备级限流。登录或注册成功后,同一事务会把设备收藏、观看进度和观看流水合并到账号:
|
||||
同一部剧的进度先比较集号,同集再比较播放位置,最后用更新时间兜底,只保留更靠前的一条;
|
||||
观看流水按剧集去重并保留更靠后的位置。`playCount` 只取最终保留记录,不重复累加。
|
||||
|
||||
#### 批量取消收藏
|
||||
|
||||
`POST /app/favorites/remove`
|
||||
|
||||
```json
|
||||
{
|
||||
"dramaIds": ["12", "15"],
|
||||
"deviceId": "optional-device-id"
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `dramaIds` | array<Long> | 是 | 待取消的短剧 ID,最多 200 条,服务端去重后删除 |
|
||||
| `deviceId` | string | 否 | 未登录且未携带 `X-Device-Id` 时的设备号兜底 |
|
||||
|
||||
身份解析优先登录用户,其次 `X-Device-Id`,最后请求体 `deviceId`。登录用户按
|
||||
`user_id` 删除,匿名用户按 `device_id` 删除;匿名写操作沿用设备级限流。
|
||||
所有删除和剧级收藏数回退在单一事务内完成,其中任一步失败会整体回滚。
|
||||
|
||||
响应 `data` 为实际删除的收藏关系数:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 0,
|
||||
"message": "ok",
|
||||
"data": 2
|
||||
}
|
||||
```
|
||||
|
||||
空列表返回业务码 `400`;超过 200 条同样返回 `400`。
|
||||
|
||||
#### 收藏分页
|
||||
|
||||
`GET /app/favorites?pageIndex=1&pageSize=20`
|
||||
@@ -446,13 +514,22 @@ app.register.max-per-device-per-day
|
||||
|
||||
| 方法 | 路径 | 鉴权 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| POST | `/app/comments` | 登录 | 发表评论/回复:过敏感词后按策略发布或转待审 |
|
||||
| POST | `/app/comments` | 可选登录 | 发表评论/回复;匿名按 `X-Device-Id`,过敏感词后按策略发布或转待审 |
|
||||
| GET | `/app/comments?dramaId=&cursor=&size=` | 匿名 | 游标翻页;不传 `rootId` 返回顶层评论,传了返回该楼层回复 |
|
||||
| GET | `/app/comments/count?dramaId=&episodeId=` | 匿名 | 传 `episodeId` 返回该集评论数;仅传 `dramaId` 返回全剧兼容汇总 |
|
||||
| DELETE | `/app/comments/{id}` | 登录 | 删除自己的评论(逻辑置为 `deleted`) |
|
||||
| POST | `/app/likes/toggle` | 登录 | 点赞/取消点赞,`targetType` 支持 `DRAMA` / `EPISODE` / `COMMENT`;新客户端点赞按集 |
|
||||
| DELETE | `/app/comments/{id}` | 可选登录 | 删除自己的评论(匿名按设备);逻辑置为 `deleted` |
|
||||
| POST | `/app/likes/toggle` | 可选登录 | 点赞/取消点赞,`targetType` 支持 `DRAMA` / `EPISODE` / `COMMENT`;匿名按 `X-Device-Id` |
|
||||
| POST | `/app/reports` | 登录 | 举报评论/用户/短剧;同一目标只保留一条待处理工单 |
|
||||
|
||||
**非付费互动身份与合并**:点赞、收藏、评论的身份解析顺序为登录 `userId` →
|
||||
`X-Device-Id` → 请求体 `deviceId`。三者都没有时返回业务码 `200007`。匿名写入按设备号
|
||||
每分钟限流;评论同时做长度、空白、短时间重复内容和频率校验。登录或注册成功后,服务端
|
||||
在同一登录事务内把该设备未归属的点赞、收藏、评论、观看进度和观看流水迁移到账号;
|
||||
账号已有同内容时保留账号记录并删除设备重复记录,计数同步回退,不重复累加。
|
||||
|
||||
匿名评论展示为「游客」,头像为空占位。解锁、金币/VIP 权益、锁定集正片票据不在本规则内,
|
||||
仍必须登录。
|
||||
|
||||
**敏感词三档处置**:`BLOCK` 直接拒绝并返回原因、`REPLACE` 替换后放行、`REVIEW` 转人工待审。
|
||||
审核策略由 `fruitshorts.interaction.comment-audit-mode` 控制:
|
||||
`MACHINE_FIRST`(机审通过即发布,当前默认)或 `PRE_REVIEW`(全部先审后发,生产建议)。
|
||||
@@ -788,15 +865,36 @@ GET /app/notices?pageIndex=1&pageSize=20
|
||||
|
||||
| 方法 | 路径 | 权限点 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource |
|
||||
| GET | `/admin/app-users/page` | `app-user:list` | 检索:keyword(uid/昵称/手机号/邮箱)、status、countryCode、registerSource、platform(ANDROID/IOS,按用户**最近一次**会话平台筛选) |
|
||||
| GET | `/admin/app-users/{id}` | `app-user:list` | 详情 |
|
||||
| GET | `/admin/app-users/{id}/ban-records` | `app-user:list` | 封禁与申诉记录 |
|
||||
| GET | `/admin/app-users/{id}/watch-history` | `app-user:list` | 观看流水明细(带剧名/集号,客服核对用) |
|
||||
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime |
|
||||
| GET | `/admin/watch-history/page` | `watch-history:list` | 跨用户观看记录分页:keyword、userId、dramaTitle、dramaId、episodeId、source、finished、startTime、endTime、platform(ANDROID/IOS,按**最近一次会话**) |
|
||||
| GET | `/admin/favorites/page` | `favorite:list` | 收藏只读分页,含游客;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
|
||||
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标;支持 platform 筛选(ANDROID/IOS,按**最近一次会话**) |
|
||||
| PUT | `/admin/app-users/{id}/status` | `app-user:update` | 改状态:normal/limited/banned |
|
||||
|
||||
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
|
||||
|
||||
收藏和点赞分页参数:`pageIndex` 默认 1,`pageSize` 默认 10、最大 100;
|
||||
`keyword` 模糊匹配 uid/昵称,`userId`、`deviceId`、`dramaId` 精确匹配,
|
||||
`dramaTitle` 模糊匹配;`startTime/endTime` 按创建时间闭区间过滤,
|
||||
格式 `yyyy-MM-dd HH:mm:ss`。点赞另支持 `targetType`(DRAMA/EPISODE/COMMENT)、
|
||||
`targetId` 和 `episodeId` 精确过滤,短剧和剧集过滤会解析评论及剧集所属关系。
|
||||
按 `createdAt DESC, id DESC` 排序,用户/短剧预检索无结果返回 total=0、list=[]。
|
||||
|
||||
点赞的三种目标语义:客户端点赞按钮作用于当前播放剧集,落库为 `targetType=EPISODE`;
|
||||
`DRAMA` 是早期按整部剧点赞的历史数据;`COMMENT` 为评论点赞。筛选行为:
|
||||
`dramaTitle` / `dramaId` 同时命中「该剧本身的点赞」与「该剧下各集的点赞」,
|
||||
`episodeId` 只命中「该集本身的点赞」与该集下的评论点赞,**不包含对短剧本身的点赞**;
|
||||
不传 `episodeId` 时不受此限制。
|
||||
|
||||
收藏行字段:`id,userId,uid,nickname,deviceId,anonymous,dramaId,dramaTitle,dramaCover,
|
||||
dramaStatus,dramaPublished,createdAt`。点赞行字段:`id,userId,uid,nickname,deviceId,
|
||||
anonymous,targetType,targetId,dramaId,dramaTitle,dramaCover,episodeId,episodeNo,episodeTitle,
|
||||
commentSummary,createdAt`。游客的 userId 为空、anonymous 为 true;评论摘要最多 30 字。
|
||||
关联资料逻辑删除后展示字段为空,不排除原始互动记录。
|
||||
|
||||
### 2.4 下载管理(已实现)
|
||||
|
||||
| 方法 | 路径 | 权限点 | 说明 |
|
||||
@@ -1001,8 +1099,9 @@ GET /app/notices?pageIndex=1&pageSize=20
|
||||
只接受 `bizType=EPISODE` 且状态为 `ready` / `uploaded` 的产物。
|
||||
|
||||
**收费配置**:`previewSeconds` 落在 `drama_episode.preview_seconds`(0 = 不限制),
|
||||
与 `is_free` / `unlock_coin` 一起就是播放与下载付费判定读的字段,**改完立即生效**(实测:未登录请求付费集返回
|
||||
`{"accessType":"COIN_REQUIRED","unlockCoin":50,"previewSeconds":15}`;免费集直接返回签名播放地址)。
|
||||
与 `is_free` / `unlock_coin` 一起就是播放与下载付费判定读的字段,**改完立即生效**(实测:未登录请求锁定集直接
|
||||
返回 `UNAUTHORIZED`;已登录未解锁用户返回 `{"accessType":"COIN_REQUIRED","unlockCoin":50,"previewSeconds":15}`;
|
||||
免费集直接返回签名播放地址)。
|
||||
定价沿用「可编辑状态」口径:`draft` / `offline` 可改,已上线要改价需先申请下线(避免创作者悄悄改已上线内容的价格);
|
||||
`dramaId` 以路径为准,body 里传别人的剧 id 无效,列表里带别人的 `episodeId` 会被忽略(只作用于自己剧的分集)。
|
||||
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.config;
|
||||
|
||||
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 后台接口的时间格式统一成 `yyyy-MM-dd HH:mm:ss`。
|
||||
*
|
||||
* <p>application.yml 里的 `spring.jackson.date-format` 只作用于 java.util.Date,
|
||||
* LocalDateTime 仍会输出 ISO 的 `2026-10-27T14:14:12.644`,后台表格里会露出一串带 T 的原文。
|
||||
* 该配置只放在 admin-api,C 端保持 ISO,避免影响客户端解析。
|
||||
*/
|
||||
@Configuration
|
||||
public class AdminJacksonTimeConfig {
|
||||
|
||||
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Bean
|
||||
public Jackson2ObjectMapperBuilderCustomizer adminLocalDateTimeFormat() {
|
||||
return builder -> builder.serializers(new LocalDateTimeSerializer(DATE_TIME));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -32,12 +32,13 @@ import java.util.List;
|
||||
public class AuthController {
|
||||
|
||||
private final AuthService authService;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
@Operation(summary = "管理端登录")
|
||||
@PostMapping("/login")
|
||||
@OperationLog(module = "认证", action = "登录")
|
||||
public Result<LoginRespVO> login(@Valid @RequestBody LoginReqVO req, HttpServletRequest request) {
|
||||
return Result.ok(authService.login(req, WebUtils.getClientIp(request)));
|
||||
return Result.ok(authService.login(req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
/** 当前用户的菜单路由树,结构与前端 element-plus-admin 的动态路由一致。 */
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.controller;
|
||||
|
||||
import com.fruitshorts.admin.service.FavoriteAdminService;
|
||||
import com.fruitshorts.admin.vo.AdminFavoriteVO;
|
||||
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** 后台收藏只读查询入口。 */
|
||||
@Tag(name = "后台-收藏列表")
|
||||
@RestController
|
||||
@RequestMapping("/admin/favorites")
|
||||
@RequiredArgsConstructor
|
||||
public class FavoriteAdminController {
|
||||
private final FavoriteAdminService service;
|
||||
|
||||
/** 按用户、设备、内容和时间分页查询收藏。 */
|
||||
@Operation(summary = "收藏列表分页查询")
|
||||
@GetMapping("/page")
|
||||
@PreAuthorize("@ss.hasPermission('favorite:list')")
|
||||
public Result<PageResult<AdminFavoriteVO>> page(@Valid FavoriteQueryReqVO req) {
|
||||
return Result.ok(service.page(req));
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.controller;
|
||||
|
||||
import com.fruitshorts.admin.service.LikeAdminService;
|
||||
import com.fruitshorts.admin.vo.AdminLikeVO;
|
||||
import com.fruitshorts.admin.vo.LikeQueryReqVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** 后台点赞只读查询入口。 */
|
||||
@Tag(name = "后台-点赞列表")
|
||||
@RestController
|
||||
@RequestMapping("/admin/likes")
|
||||
@RequiredArgsConstructor
|
||||
public class LikeAdminController {
|
||||
private final LikeAdminService service;
|
||||
|
||||
/** 按用户、设备、内容和时间分页查询点赞。 */
|
||||
@Operation(summary = "点赞列表分页查询")
|
||||
@GetMapping("/page")
|
||||
@PreAuthorize("@ss.hasPermission('like:list')")
|
||||
public Result<PageResult<AdminLikeVO>> page(@Valid LikeQueryReqVO req) {
|
||||
return Result.ok(service.page(req));
|
||||
}
|
||||
}
|
||||
+52
-1
@@ -3,7 +3,9 @@
|
||||
package com.fruitshorts.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -13,16 +15,19 @@ import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 按用户最近会话解析系统。同一设备优先,否则用仍有效的最近一次登录。
|
||||
* 按设备画像解析系统,缺画像时回退到用户最近会话。
|
||||
* 设备画像不依赖登录态,游客行为也能显示系统。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AppSessionSystemService {
|
||||
|
||||
private final AppUserSessionMapper sessionMapper;
|
||||
private final AppDeviceProfileMapper profileMapper;
|
||||
|
||||
/** 按用户分组,组内按最近活跃倒序。 */
|
||||
public Map<Long, List<AppUserSession>> groupByUser(Collection<Long> userIds) {
|
||||
@@ -31,6 +36,9 @@ public class AppSessionSystemService {
|
||||
return grouped;
|
||||
}
|
||||
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
||||
.select(AppUserSession::getId, AppUserSession::getUserId, AppUserSession::getDeviceId,
|
||||
AppUserSession::getPlatform, AppUserSession::getOsVersion,
|
||||
AppUserSession::getRevokedAt, AppUserSession::getLastActiveAt)
|
||||
.in(AppUserSession::getUserId, userIds)
|
||||
.orderByDesc(AppUserSession::getLastActiveAt)
|
||||
.orderByDesc(AppUserSession::getId));
|
||||
@@ -40,6 +48,49 @@ public class AppSessionSystemService {
|
||||
return grouped;
|
||||
}
|
||||
|
||||
/** 按 device_id 批量取设备画像,未建档的设备不出现在结果里。 */
|
||||
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
|
||||
Map<String, AppDeviceProfile> result = new HashMap<>();
|
||||
if (deviceIds == null || deviceIds.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
List<String> keys = deviceIds.stream()
|
||||
.filter(StringUtils::hasText).map(String::trim).distinct().toList();
|
||||
if (keys.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (AppDeviceProfile profile : profileMapper.selectList(
|
||||
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))) {
|
||||
result.put(profile.getDeviceId(), profile);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台筛选的命中范围:设备平台直接给 device_id;登录用户的行为行不带 device_id,
|
||||
* 只能按该用户登录会话的平台判定,两者取并集。
|
||||
*/
|
||||
public record PlatformScope(List<String> deviceIds, List<Long> userIds) {
|
||||
public boolean empty() {
|
||||
return deviceIds.isEmpty() && userIds.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
|
||||
public PlatformScope platformScope(String platform) {
|
||||
if (!StringUtils.hasText(platform)) {
|
||||
return null;
|
||||
}
|
||||
String value = platform.trim().toUpperCase(Locale.ROOT);
|
||||
List<String> deviceIds = profileMapper.selectList(Wrappers.<AppDeviceProfile>lambdaQuery()
|
||||
.select(AppDeviceProfile::getDeviceId)
|
||||
.eq(AppDeviceProfile::getPlatform, value))
|
||||
.stream().map(AppDeviceProfile::getDeviceId).toList();
|
||||
// 只认「最近一次登录」的平台,与列表里展示的系统保持一致
|
||||
List<Long> userIds = sessionMapper.selectUserIdsByLatestPlatform(value);
|
||||
return new PlatformScope(deviceIds, userIds);
|
||||
}
|
||||
|
||||
/** 观看记录优先匹配同一设备,其次取未吊销会话。 */
|
||||
public AppUserSession match(List<AppUserSession> sessions, String deviceId) {
|
||||
if (sessions == null || sessions.isEmpty()) {
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fruitshorts.admin.vo.EngagementQueryReqVO;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.mapper.DramaMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.entity.AppUser;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** 后台互动列表的分页、预检索及批量资料读取。 */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class EngagementAdminLookup {
|
||||
private static final int DEFAULT_PAGE_SIZE = 10;
|
||||
private static final int MAX_PAGE_SIZE = 100;
|
||||
/**
|
||||
* 关键词预检索的 ID 上限:命中过多时 IN 列表会超出数据库参数上限,
|
||||
* 也说明关键词过于宽泛,直接提示使用者补充条件而不是截断结果。
|
||||
*/
|
||||
private static final int MAX_LOOKUP_SIZE = 2000;
|
||||
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
|
||||
private final AppUserMapper userMapper;
|
||||
private final DramaMapper dramaMapper;
|
||||
private final AppDeviceProfileMapper deviceProfileMapper;
|
||||
private final AppUserSessionMapper sessionMapper;
|
||||
private final AppSessionSystemService sessionSystem;
|
||||
|
||||
/** 规范化页码和页大小。 */
|
||||
public <T> Page<T> page(EngagementQueryReqVO req) {
|
||||
int index = req.getPageIndex() == null ? 1 : Math.max(1, req.getPageIndex());
|
||||
int size = req.getPageSize() == null || req.getPageSize() < 1
|
||||
? DEFAULT_PAGE_SIZE : Math.min(MAX_PAGE_SIZE, req.getPageSize());
|
||||
return new Page<>(index, size);
|
||||
}
|
||||
|
||||
/** 按 uid 或昵称预检索,未传关键词时不限制用户。 */
|
||||
public List<Long> userIds(String keyword) {
|
||||
if (!StringUtils.hasText(keyword)) {
|
||||
return null;
|
||||
}
|
||||
String value = keyword.trim();
|
||||
List<Long> ids = userMapper.selectList(Wrappers.<AppUser>lambdaQuery().select(AppUser::getId)
|
||||
.and(q -> q.like(AppUser::getUid, value).or().like(AppUser::getNickname, value))
|
||||
.last("LIMIT " + LOOKUP_PROBE))
|
||||
.stream().map(AppUser::getId).toList();
|
||||
return ensureLookupSize(ids, "uid / 昵称");
|
||||
}
|
||||
|
||||
/** 按剧名预检索,未传剧名时不限制短剧。 */
|
||||
public List<Long> dramaIds(String title) {
|
||||
if (!StringUtils.hasText(title)) {
|
||||
return null;
|
||||
}
|
||||
List<Long> ids = dramaMapper.selectList(Wrappers.<Drama>lambdaQuery().select(Drama::getId)
|
||||
.like(Drama::getTitle, title.trim())
|
||||
.last("LIMIT " + LOOKUP_PROBE)).stream().map(Drama::getId).toList();
|
||||
return ensureLookupSize(ids, "短剧名称");
|
||||
}
|
||||
|
||||
/** 命中数量超限时给出可操作的提示,避免把整张表拉进 IN 条件。 */
|
||||
private List<Long> ensureLookupSize(List<Long> ids, String field) {
|
||||
if (ids.size() > MAX_LOOKUP_SIZE) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST,
|
||||
field + "命中超过 " + MAX_LOOKUP_SIZE + " 条,请使用更精确的筛选条件");
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/** 区分无筛选和有筛选但无匹配。 */
|
||||
public boolean noMatch(List<Long> ids) {
|
||||
return ids != null && ids.isEmpty();
|
||||
}
|
||||
|
||||
/** 按非空去重 ID 批量读取用户,避免游客触发空 IN。 */
|
||||
public Map<Long, AppUser> users(Collection<Long> ids) {
|
||||
List<Long> keys = keys(ids);
|
||||
return keys.isEmpty() ? Map.of() : userMapper.selectBatchIds(keys).stream()
|
||||
.collect(Collectors.toMap(AppUser::getId, Function.identity()));
|
||||
}
|
||||
|
||||
/** 按非空去重 ID 批量读取短剧。 */
|
||||
public Map<Long, Drama> dramas(Collection<Long> ids) {
|
||||
List<Long> keys = keys(ids);
|
||||
return keys.isEmpty() ? Map.of() : dramaMapper.selectBatchIds(keys).stream()
|
||||
.collect(Collectors.toMap(Drama::getId, Function.identity()));
|
||||
}
|
||||
|
||||
/** 按 device_id 批量读取设备画像;游客也有记录,没建档的不返回。 */
|
||||
public Map<String, AppDeviceProfile> deviceProfiles(Collection<String> deviceIds) {
|
||||
List<String> keys = deviceIds.stream().filter(StringUtils::hasText)
|
||||
.map(String::trim).distinct().toList();
|
||||
return keys.isEmpty() ? Map.of() : deviceProfileMapper.selectList(
|
||||
Wrappers.<AppDeviceProfile>lambdaQuery().in(AppDeviceProfile::getDeviceId, keys))
|
||||
.stream().collect(Collectors.toMap(AppDeviceProfile::getDeviceId,
|
||||
Function.identity(), (first, second) -> first));
|
||||
}
|
||||
|
||||
/**
|
||||
* 每个用户取最近一次登录会话。
|
||||
* 已登录用户的互动行 device_id 为空(写入时会清空),只能退回会话取系统。
|
||||
*/
|
||||
public Map<Long, AppUserSession> latestSessions(Collection<Long> userIds) {
|
||||
List<Long> keys = keys(userIds);
|
||||
if (keys.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, AppUserSession> result = new HashMap<>();
|
||||
for (AppUserSession session : sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
||||
.select(AppUserSession::getId, AppUserSession::getUserId,
|
||||
AppUserSession::getPlatform)
|
||||
.in(AppUserSession::getUserId, keys)
|
||||
.orderByDesc(AppUserSession::getLastActiveAt)
|
||||
.orderByDesc(AppUserSession::getId))) {
|
||||
result.putIfAbsent(session.getUserId(), session);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 按平台解析命中范围;未传平台返回 null 表示不限制。 */
|
||||
public AppSessionSystemService.PlatformScope platformScope(String platform) {
|
||||
return sessionSystem.platformScope(platform);
|
||||
}
|
||||
|
||||
private List<Long> keys(Collection<Long> ids) {
|
||||
return ids.stream().filter(Objects::nonNull).distinct().toList();
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fruitshorts.admin.vo.AdminFavoriteVO;
|
||||
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.enums.ContentStatus;
|
||||
import com.fruitshorts.playback.dal.entity.UserFavorite;
|
||||
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.entity.AppUser;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 后台收藏只读分页及跨域资料装配。 */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class FavoriteAdminService {
|
||||
private final UserFavoriteMapper favoriteMapper;
|
||||
private final EngagementAdminLookup lookup;
|
||||
|
||||
/** 分页查询收藏,预检索无匹配时直接返回空页。 */
|
||||
public PageResult<AdminFavoriteVO> page(FavoriteQueryReqVO req) {
|
||||
List<Long> userIds = lookup.userIds(req.getKeyword());
|
||||
if (lookup.noMatch(userIds)) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
List<Long> dramaIds = lookup.dramaIds(req.getDramaTitle());
|
||||
if (lookup.noMatch(dramaIds)) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
var scope = lookup.platformScope(req.getPlatform());
|
||||
if (scope != null && scope.empty()) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
var query = Wrappers.<UserFavorite>lambdaQuery()
|
||||
.eq(req.getUserId() != null, UserFavorite::getUserId, req.getUserId())
|
||||
.in(userIds != null, UserFavorite::getUserId, userIds)
|
||||
.eq(StringUtils.hasText(req.getDeviceId()), UserFavorite::getDeviceId, req.getDeviceId())
|
||||
.eq(req.getDramaId() != null, UserFavorite::getDramaId, req.getDramaId())
|
||||
.in(dramaIds != null, UserFavorite::getDramaId, dramaIds)
|
||||
.ge(req.getStartTime() != null, UserFavorite::getCreatedAt, req.getStartTime())
|
||||
.le(req.getEndTime() != null, UserFavorite::getCreatedAt, req.getEndTime());
|
||||
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
|
||||
if (scope != null) {
|
||||
query.and(inner -> {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.in(UserFavorite::getDeviceId, scope.deviceIds());
|
||||
}
|
||||
if (!scope.userIds().isEmpty()) {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.or();
|
||||
}
|
||||
inner.in(UserFavorite::getUserId, scope.userIds());
|
||||
}
|
||||
});
|
||||
}
|
||||
query.orderByDesc(UserFavorite::getCreatedAt, UserFavorite::getId);
|
||||
var result = favoriteMapper.selectPage(lookup.page(req), query);
|
||||
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
||||
}
|
||||
|
||||
private List<AdminFavoriteVO> assemble(List<UserFavorite> rows) {
|
||||
if (rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<Long, AppUser> users = lookup.users(rows.stream().map(UserFavorite::getUserId).toList());
|
||||
Map<Long, Drama> dramas = lookup.dramas(rows.stream().map(UserFavorite::getDramaId).toList());
|
||||
Map<String, AppDeviceProfile> profiles =
|
||||
lookup.deviceProfiles(rows.stream().map(UserFavorite::getDeviceId).toList());
|
||||
Map<Long, AppUserSession> sessions =
|
||||
lookup.latestSessions(rows.stream().map(UserFavorite::getUserId).toList());
|
||||
return rows.stream().map(row -> toVo(row, row.getUserId() == null ? null : users.get(row.getUserId()),
|
||||
row.getDramaId() == null ? null : dramas.get(row.getDramaId()),
|
||||
row.getDeviceId() == null ? null : profiles.get(row.getDeviceId()),
|
||||
row.getUserId() == null ? null : sessions.get(row.getUserId())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private AdminFavoriteVO toVo(UserFavorite row, AppUser user, Drama drama,
|
||||
AppDeviceProfile profile, AppUserSession session) {
|
||||
AdminFavoriteVO vo = new AdminFavoriteVO();
|
||||
vo.setId(row.getId());
|
||||
vo.setUserId(row.getUserId());
|
||||
vo.setDeviceId(row.getDeviceId());
|
||||
vo.setAnonymous(row.getUserId() == null);
|
||||
if (profile != null) {
|
||||
vo.setPlatform(profile.getPlatform());
|
||||
}
|
||||
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
|
||||
if (!StringUtils.hasText(vo.getPlatform()) && session != null) {
|
||||
vo.setPlatform(session.getPlatform());
|
||||
}
|
||||
vo.setDramaId(row.getDramaId());
|
||||
vo.setCreatedAt(row.getCreatedAt());
|
||||
if (user != null) {
|
||||
vo.setUid(user.getUid());
|
||||
vo.setNickname(user.getNickname());
|
||||
}
|
||||
if (drama != null) {
|
||||
vo.setDramaTitle(drama.getTitle());
|
||||
vo.setDramaCover(drama.getCoverUrl());
|
||||
vo.setDramaStatus(drama.getStatus());
|
||||
vo.setDramaPublished(ContentStatus.PUBLISHED.getCode().equals(drama.getStatus()));
|
||||
}
|
||||
// 短剧读不到(已删除或数据异常)时保持 dramaPublished 为 null,
|
||||
// 与「未发布」区分开,前端只在明确 false 时才展示未发布标记。
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fruitshorts.admin.vo.AdminLikeVO;
|
||||
import com.fruitshorts.admin.vo.LikeQueryReqVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
|
||||
import com.fruitshorts.interaction.dal.entity.ContentComment;
|
||||
import com.fruitshorts.interaction.dal.entity.ContentLike;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.entity.AppUser;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** 后台点赞只读分页及多态目标批量装配。 */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LikeAdminService {
|
||||
private static final String DRAMA = "DRAMA";
|
||||
private static final String EPISODE = "EPISODE";
|
||||
private static final String COMMENT = "COMMENT";
|
||||
private static final int SUMMARY_LENGTH = 30;
|
||||
/**
|
||||
* 点赞目标是多态列(target_type + target_id),按短剧/剧集筛选必须跨表回溯,
|
||||
* 无法用 LambdaQueryWrapper 表达,只能写原生片段。
|
||||
* 维护约定:表名、逻辑删除列与 {@code drama_episode} / {@code content_comment}
|
||||
* 实体上的 @TableName / @TableLogic 保持一致,改表结构时需要同步修改这里。
|
||||
*/
|
||||
private static final String DRAMA_MATCH =
|
||||
"(target_type = 'DRAMA' AND target_id = {0}) OR "
|
||||
+ "(target_type = 'EPISODE' AND EXISTS (SELECT 1 FROM drama_episode e "
|
||||
+ "WHERE e.id = target_id AND e.deleted = 0 AND e.drama_id = {0})) OR "
|
||||
+ "(target_type = 'COMMENT' AND EXISTS (SELECT 1 FROM content_comment c "
|
||||
+ "WHERE c.id = target_id AND c.deleted = 0 AND c.drama_id = {0}))";
|
||||
private static final String EPISODE_MATCH =
|
||||
"(target_type = 'EPISODE' AND target_id = {0}) OR "
|
||||
+ "(target_type = 'COMMENT' AND EXISTS (SELECT 1 FROM content_comment c "
|
||||
+ "WHERE c.id = target_id AND c.deleted = 0 AND c.episode_id = {0}))";
|
||||
|
||||
private final ContentLikeMapper likeMapper;
|
||||
private final ContentCommentMapper commentMapper;
|
||||
private final DramaEpisodeMapper episodeMapper;
|
||||
private final EngagementAdminLookup lookup;
|
||||
|
||||
/** 分页查询点赞;短剧及剧集条件在分页之前作用于各类目标。 */
|
||||
public PageResult<AdminLikeVO> page(LikeQueryReqVO req) {
|
||||
List<Long> users = lookup.userIds(req.getKeyword());
|
||||
if (lookup.noMatch(users)) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
List<Long> dramas = lookup.dramaIds(req.getDramaTitle());
|
||||
if (lookup.noMatch(dramas)) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
var query = buildQuery(req, users);
|
||||
var scope = lookup.platformScope(req.getPlatform());
|
||||
if (scope != null && scope.empty()) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
if (scope != null) {
|
||||
query.and(inner -> {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.in(ContentLike::getDeviceId, scope.deviceIds());
|
||||
}
|
||||
if (!scope.userIds().isEmpty()) {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.or();
|
||||
}
|
||||
inner.in(ContentLike::getUserId, scope.userIds());
|
||||
}
|
||||
});
|
||||
}
|
||||
if (req.getDramaId() != null) {
|
||||
query.and(q -> q.apply(DRAMA_MATCH, req.getDramaId()));
|
||||
}
|
||||
if (dramas != null) {
|
||||
query.and(q -> {
|
||||
for (Long id : dramas) {
|
||||
q.or().apply(DRAMA_MATCH, id);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (req.getEpisodeId() != null) {
|
||||
query.and(q -> q.apply(EPISODE_MATCH, req.getEpisodeId()));
|
||||
}
|
||||
// orderBy 必须最后追加,否则条件会被拼到 ORDER BY 后面
|
||||
query.orderByDesc(ContentLike::getCreatedAt, ContentLike::getId);
|
||||
var result = likeMapper.selectPage(lookup.page(req), query);
|
||||
return new PageResult<>(result.getTotal(), assemble(result.getRecords()));
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<ContentLike> buildQuery(LikeQueryReqVO req, List<Long> users) {
|
||||
return Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(req.getUserId() != null, ContentLike::getUserId, req.getUserId())
|
||||
.in(users != null, ContentLike::getUserId, users)
|
||||
.eq(StringUtils.hasText(req.getDeviceId()), ContentLike::getDeviceId, req.getDeviceId())
|
||||
.eq(StringUtils.hasText(req.getTargetType()), ContentLike::getTargetType, req.getTargetType())
|
||||
.eq(req.getTargetId() != null, ContentLike::getTargetId, req.getTargetId())
|
||||
.ge(req.getStartTime() != null, ContentLike::getCreatedAt, req.getStartTime())
|
||||
.le(req.getEndTime() != null, ContentLike::getCreatedAt, req.getEndTime());
|
||||
}
|
||||
|
||||
private List<AdminLikeVO> assemble(List<ContentLike> rows) {
|
||||
if (rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<Long, AppUser> users = lookup.users(rows.stream().map(ContentLike::getUserId).toList());
|
||||
Map<Long, ContentComment> comments = comments(targetIds(rows, COMMENT));
|
||||
List<Long> episodeIds = new ArrayList<>(targetIds(rows, EPISODE));
|
||||
comments.values().stream().map(ContentComment::getEpisodeId).filter(Objects::nonNull)
|
||||
.forEach(episodeIds::add);
|
||||
Map<Long, DramaEpisode> episodes = episodes(episodeIds);
|
||||
List<Long> dramaIds = new ArrayList<>(targetIds(rows, DRAMA));
|
||||
comments.values().stream().map(ContentComment::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
||||
episodes.values().stream().map(DramaEpisode::getDramaId).filter(Objects::nonNull).forEach(dramaIds::add);
|
||||
Map<Long, Drama> dramas = lookup.dramas(dramaIds);
|
||||
Map<String, AppDeviceProfile> profiles =
|
||||
lookup.deviceProfiles(rows.stream().map(ContentLike::getDeviceId).toList());
|
||||
Map<Long, AppUserSession> sessions =
|
||||
lookup.latestSessions(rows.stream().map(ContentLike::getUserId).toList());
|
||||
return rows.stream()
|
||||
.map(row -> toVo(row, users, comments, episodes, dramas, profiles, sessions))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private List<Long> targetIds(List<ContentLike> rows, String type) {
|
||||
return rows.stream().filter(row -> type.equals(row.getTargetType())).map(ContentLike::getTargetId)
|
||||
.filter(Objects::nonNull).distinct().toList();
|
||||
}
|
||||
|
||||
private Map<Long, ContentComment> comments(Collection<Long> ids) {
|
||||
return ids.isEmpty() ? Map.of() : commentMapper.selectBatchIds(ids).stream()
|
||||
.collect(Collectors.toMap(ContentComment::getId, Function.identity()));
|
||||
}
|
||||
|
||||
private Map<Long, DramaEpisode> episodes(Collection<Long> ids) {
|
||||
List<Long> keys = ids.stream().filter(Objects::nonNull).distinct().toList();
|
||||
return keys.isEmpty() ? Map.of() : episodeMapper.selectBatchIds(keys).stream()
|
||||
.collect(Collectors.toMap(DramaEpisode::getId, Function.identity()));
|
||||
}
|
||||
|
||||
private AdminLikeVO toVo(ContentLike row, Map<Long, AppUser> users, Map<Long, ContentComment> comments,
|
||||
Map<Long, DramaEpisode> episodes, Map<Long, Drama> dramas,
|
||||
Map<String, AppDeviceProfile> profiles,
|
||||
Map<Long, AppUserSession> sessions) {
|
||||
AdminLikeVO vo = new AdminLikeVO();
|
||||
vo.setId(row.getId());
|
||||
vo.setUserId(row.getUserId());
|
||||
vo.setDeviceId(row.getDeviceId());
|
||||
vo.setAnonymous(row.getUserId() == null);
|
||||
AppDeviceProfile profile = row.getDeviceId() == null ? null : profiles.get(row.getDeviceId());
|
||||
if (profile != null) {
|
||||
vo.setPlatform(profile.getPlatform());
|
||||
}
|
||||
// 已登录用户的互动行不带 device_id,设备平台查不到时退回最近一次登录会话
|
||||
if (!StringUtils.hasText(vo.getPlatform()) && row.getUserId() != null) {
|
||||
AppUserSession session = sessions.get(row.getUserId());
|
||||
if (session != null) {
|
||||
vo.setPlatform(session.getPlatform());
|
||||
}
|
||||
}
|
||||
vo.setTargetType(row.getTargetType());
|
||||
vo.setTargetId(row.getTargetId());
|
||||
vo.setCreatedAt(row.getCreatedAt());
|
||||
AppUser user = row.getUserId() == null ? null : users.get(row.getUserId());
|
||||
if (user != null) {
|
||||
vo.setUid(user.getUid());
|
||||
vo.setNickname(user.getNickname());
|
||||
}
|
||||
ContentComment comment = COMMENT.equals(row.getTargetType()) ? comments.get(row.getTargetId()) : null;
|
||||
Long episodeId = EPISODE.equals(row.getTargetType()) ? row.getTargetId()
|
||||
: comment == null ? null : comment.getEpisodeId();
|
||||
DramaEpisode episode = episodeId == null ? null : episodes.get(episodeId);
|
||||
Long dramaId = DRAMA.equals(row.getTargetType()) ? row.getTargetId()
|
||||
: comment != null ? comment.getDramaId() : episode == null ? null : episode.getDramaId();
|
||||
vo.setEpisodeId(episodeId);
|
||||
vo.setDramaId(dramaId);
|
||||
if (comment != null && comment.getContent() != null) {
|
||||
String content = comment.getContent();
|
||||
int count = content.codePointCount(0, content.length());
|
||||
vo.setCommentSummary(content.substring(0, content.offsetByCodePoints(0, Math.min(count, SUMMARY_LENGTH))));
|
||||
}
|
||||
if (episode != null) {
|
||||
vo.setEpisodeNo(episode.getEpNo());
|
||||
vo.setEpisodeTitle(episode.getTitle());
|
||||
}
|
||||
Drama drama = dramaId == null ? null : dramas.get(dramaId);
|
||||
if (drama != null) {
|
||||
vo.setDramaTitle(drama.getTitle());
|
||||
vo.setDramaCover(drama.getCoverUrl());
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+76
-15
@@ -8,6 +8,8 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fruitshorts.admin.vo.AdminWatchHistoryVO;
|
||||
import com.fruitshorts.admin.vo.WatchHistoryQueryReqVO;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
@@ -16,6 +18,7 @@ import com.fruitshorts.content.dal.mapper.DramaMapper;
|
||||
import com.fruitshorts.content.enums.ContentStatus;
|
||||
import com.fruitshorts.playback.dal.entity.WatchHistory;
|
||||
import com.fruitshorts.playback.dal.mapper.WatchHistoryMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.entity.AppUser;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||
@@ -27,6 +30,7 @@ import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 后台观看记录分页与跨域装配。
|
||||
@@ -42,6 +46,8 @@ public class WatchHistoryAdminService {
|
||||
private static final int DEFAULT_PAGE_SIZE = 10;
|
||||
private static final int MAX_PAGE_SIZE = 100;
|
||||
private static final long FINISHED_TOLERANCE_MS = 1000L;
|
||||
private static final int MAX_LOOKUP_SIZE = 2000;
|
||||
private static final int LOOKUP_PROBE = MAX_LOOKUP_SIZE + 1;
|
||||
|
||||
private final WatchHistoryMapper watchHistoryMapper;
|
||||
private final AppUserMapper appUserMapper;
|
||||
@@ -65,14 +71,19 @@ public class WatchHistoryAdminService {
|
||||
if (matchedDramaIds != null && matchedDramaIds.isEmpty()) {
|
||||
return emptyPage();
|
||||
}
|
||||
var scope = sessionSystem.platformScope(req.getPlatform());
|
||||
if (scope != null && scope.empty()) {
|
||||
return emptyPage();
|
||||
}
|
||||
IPage<WatchHistory> result = watchHistoryMapper.selectPage(new Page<>(pageIndex, pageSize),
|
||||
buildQuery(req, matchedUserIds, matchedDramaIds));
|
||||
buildQuery(req, matchedUserIds, matchedDramaIds, scope));
|
||||
return new PageResult<>(result.getTotal(), toVoList(result.getRecords()));
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<WatchHistory> buildQuery(WatchHistoryQueryReqVO req,
|
||||
List<Long> matchedUserIds,
|
||||
List<Long> matchedDramaIds) {
|
||||
List<Long> matchedDramaIds,
|
||||
AppSessionSystemService.PlatformScope scope) {
|
||||
LambdaQueryWrapper<WatchHistory> wrapper = Wrappers.<WatchHistory>lambdaQuery()
|
||||
.eq(req.getUserId() != null, WatchHistory::getUserId, req.getUserId())
|
||||
.in(matchedUserIds != null, WatchHistory::getUserId, matchedUserIds)
|
||||
@@ -82,6 +93,19 @@ public class WatchHistoryAdminService {
|
||||
.eq(StringUtils.hasText(req.getSource()), WatchHistory::getSource, req.getSource())
|
||||
.ge(req.getStartTime() != null, WatchHistory::getWatchedAt, req.getStartTime())
|
||||
.le(req.getEndTime() != null, WatchHistory::getWatchedAt, req.getEndTime());
|
||||
if (scope != null) {
|
||||
wrapper.and(inner -> {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.in(WatchHistory::getDeviceId, scope.deviceIds());
|
||||
}
|
||||
if (!scope.userIds().isEmpty()) {
|
||||
if (!scope.deviceIds().isEmpty()) {
|
||||
inner.or();
|
||||
}
|
||||
inner.in(WatchHistory::getUserId, scope.userIds());
|
||||
}
|
||||
});
|
||||
}
|
||||
applyFinished(wrapper, req.getFinished());
|
||||
return wrapper.orderByDesc(WatchHistory::getWatchedAt)
|
||||
.orderByDesc(WatchHistory::getId);
|
||||
@@ -100,24 +124,37 @@ public class WatchHistoryAdminService {
|
||||
|
||||
private List<Long> searchUserIds(String keyword) {
|
||||
String value = keyword.trim();
|
||||
return appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
||||
List<Long> ids = appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
||||
.select(AppUser::getId)
|
||||
.and(query -> query.like(AppUser::getUid, value)
|
||||
.or()
|
||||
.like(AppUser::getNickname, value)))
|
||||
.like(AppUser::getNickname, value))
|
||||
.last("LIMIT " + LOOKUP_PROBE))
|
||||
.stream()
|
||||
.map(AppUser::getId)
|
||||
.toList();
|
||||
return ensureLookupSize(ids, "uid / 昵称");
|
||||
}
|
||||
|
||||
private List<Long> searchDramaIds(String dramaTitle) {
|
||||
String value = dramaTitle.trim();
|
||||
return dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
||||
List<Long> ids = dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
||||
.select(Drama::getId)
|
||||
.like(Drama::getTitle, value))
|
||||
.like(Drama::getTitle, value)
|
||||
.last("LIMIT " + LOOKUP_PROBE))
|
||||
.stream()
|
||||
.map(Drama::getId)
|
||||
.toList();
|
||||
return ensureLookupSize(ids, "短剧名称");
|
||||
}
|
||||
|
||||
/** 关键词命中过多时直接提示收窄条件,避免把整张表塞进 IN。 */
|
||||
private List<Long> ensureLookupSize(List<Long> ids, String field) {
|
||||
if (ids.size() > MAX_LOOKUP_SIZE) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST,
|
||||
field + "命中超过 " + MAX_LOOKUP_SIZE + " 条,请使用更精确的筛选条件");
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private List<AdminWatchHistoryVO> toVoList(List<WatchHistory> rows) {
|
||||
@@ -129,19 +166,28 @@ public class WatchHistoryAdminService {
|
||||
Map<Long, DramaEpisode> episodes = loadEpisodes(rows);
|
||||
Map<Long, List<AppUserSession>> sessions = sessionSystem.groupByUser(
|
||||
rows.stream().map(WatchHistory::getUserId).distinct().toList());
|
||||
Map<String, AppDeviceProfile> profiles = sessionSystem.deviceProfiles(
|
||||
rows.stream().map(WatchHistory::getDeviceId).toList());
|
||||
List<AdminWatchHistoryVO> list = new ArrayList<>(rows.size());
|
||||
for (WatchHistory row : rows) {
|
||||
list.add(toVo(row, users.get(row.getUserId()), dramas.get(row.getDramaId()),
|
||||
episodes.get(row.getEpisodeId()),
|
||||
sessionSystem.match(sessions.get(row.getUserId()), row.getDeviceId())));
|
||||
sessionSystem.match(sessions.get(row.getUserId()), row.getDeviceId()),
|
||||
profiles.get(row.getDeviceId())));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<Long, AppUser> loadUsers(List<WatchHistory> rows) {
|
||||
Map<Long, AppUser> result = new HashMap<>();
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getUserId).distinct().toList();
|
||||
for (AppUser user : appUserMapper.selectBatchIds(ids)) {
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getUserId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
// 列表只需要身份展示字段,避免把整行用户资料拉回来
|
||||
for (AppUser user : appUserMapper.selectList(Wrappers.<AppUser>lambdaQuery()
|
||||
.select(AppUser::getId, AppUser::getUid, AppUser::getNickname)
|
||||
.in(AppUser::getId, ids))) {
|
||||
result.put(user.getId(), user);
|
||||
}
|
||||
return result;
|
||||
@@ -149,8 +195,13 @@ public class WatchHistoryAdminService {
|
||||
|
||||
private Map<Long, Drama> loadDramas(List<WatchHistory> rows) {
|
||||
Map<Long, Drama> result = new HashMap<>();
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getDramaId).distinct().toList();
|
||||
for (Drama drama : dramaMapper.selectBatchIds(ids)) {
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getDramaId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (Drama drama : dramaMapper.selectList(Wrappers.<Drama>lambdaQuery()
|
||||
.select(Drama::getId, Drama::getTitle, Drama::getStatus)
|
||||
.in(Drama::getId, ids))) {
|
||||
result.put(drama.getId(), drama);
|
||||
}
|
||||
return result;
|
||||
@@ -158,15 +209,22 @@ public class WatchHistoryAdminService {
|
||||
|
||||
private Map<Long, DramaEpisode> loadEpisodes(List<WatchHistory> rows) {
|
||||
Map<Long, DramaEpisode> result = new HashMap<>();
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).distinct().toList();
|
||||
for (DramaEpisode episode : dramaEpisodeMapper.selectBatchIds(ids)) {
|
||||
List<Long> ids = rows.stream().map(WatchHistory::getEpisodeId).filter(Objects::nonNull).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (DramaEpisode episode : dramaEpisodeMapper.selectList(Wrappers.<DramaEpisode>lambdaQuery()
|
||||
.select(DramaEpisode::getId, DramaEpisode::getDramaId,
|
||||
DramaEpisode::getEpNo, DramaEpisode::getTitle)
|
||||
.in(DramaEpisode::getId, ids))) {
|
||||
result.put(episode.getId(), episode);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private AdminWatchHistoryVO toVo(WatchHistory row, AppUser user, Drama drama,
|
||||
DramaEpisode episode, AppUserSession session) {
|
||||
DramaEpisode episode, AppUserSession session,
|
||||
AppDeviceProfile profile) {
|
||||
AdminWatchHistoryVO vo = new AdminWatchHistoryVO();
|
||||
vo.setId(row.getId());
|
||||
vo.setUserId(row.getUserId());
|
||||
@@ -177,7 +235,10 @@ public class WatchHistoryAdminService {
|
||||
vo.setSource(row.getSource());
|
||||
vo.setDeviceId(row.getDeviceId());
|
||||
vo.setWatchedAt(row.getWatchedAt());
|
||||
if (session != null) {
|
||||
// 设备平台不依赖登录态,优先;没有记录(老数据)再回退到登录会话
|
||||
if (profile != null && StringUtils.hasText(profile.getPlatform())) {
|
||||
vo.setPlatform(profile.getPlatform());
|
||||
} else if (session != null) {
|
||||
vo.setPlatform(session.getPlatform());
|
||||
vo.setOsVersion(session.getOsVersion());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 后台收藏只读列表行,保留游客设备信息。 */
|
||||
@Data
|
||||
public class AdminFavoriteVO {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String uid;
|
||||
private String nickname;
|
||||
private String deviceId;
|
||||
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||
private String platform;
|
||||
private Boolean anonymous;
|
||||
private Long dramaId;
|
||||
private String dramaTitle;
|
||||
private String dramaCover;
|
||||
private String dramaStatus;
|
||||
/** true=已发布,false=未发布,null=短剧已不存在(不代表未发布)。 */
|
||||
private Boolean dramaPublished;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 后台点赞只读列表行,保留游客设备信息。 */
|
||||
@Data
|
||||
public class AdminLikeVO {
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String uid;
|
||||
private String nickname;
|
||||
private String deviceId;
|
||||
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||
private String platform;
|
||||
private Boolean anonymous;
|
||||
private Long dramaId;
|
||||
private String dramaTitle;
|
||||
private String dramaCover;
|
||||
private String targetType;
|
||||
private Long targetId;
|
||||
private Long episodeId;
|
||||
private Integer episodeNo;
|
||||
private String episodeTitle;
|
||||
private String commentSummary;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 收藏与点赞列表的公共检索条件。 */
|
||||
@Data
|
||||
public class EngagementQueryReqVO {
|
||||
private static final int DEFAULT_PAGE_SIZE = 10;
|
||||
private static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
|
||||
private Integer pageIndex = 1;
|
||||
private Integer pageSize = DEFAULT_PAGE_SIZE;
|
||||
private String keyword;
|
||||
private Long userId;
|
||||
private String deviceId;
|
||||
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
|
||||
private String platform;
|
||||
private String dramaTitle;
|
||||
private Long dramaId;
|
||||
@DateTimeFormat(pattern = TIME_PATTERN)
|
||||
private LocalDateTime startTime;
|
||||
@DateTimeFormat(pattern = TIME_PATTERN)
|
||||
private LocalDateTime endTime;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/** 后台收藏分页检索条件。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class FavoriteQueryReqVO extends EngagementQueryReqVO {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.vo;
|
||||
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/** 后台点赞分页检索条件。 */
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class LikeQueryReqVO extends EngagementQueryReqVO {
|
||||
@Pattern(regexp = "DRAMA|EPISODE|COMMENT", message = "目标类型必须为 DRAMA、EPISODE 或 COMMENT")
|
||||
private String targetType;
|
||||
private Long targetId;
|
||||
private Long episodeId;
|
||||
}
|
||||
+2
@@ -20,6 +20,8 @@ public class WatchHistoryQueryReqVO {
|
||||
private String dramaTitle;
|
||||
private Long dramaId;
|
||||
private Long episodeId;
|
||||
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制。 */
|
||||
private String platform;
|
||||
private String source;
|
||||
private Boolean finished;
|
||||
|
||||
|
||||
@@ -40,6 +40,11 @@ mybatis-plus:
|
||||
datacenter-id: 1
|
||||
|
||||
fruitshorts:
|
||||
web:
|
||||
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
|
||||
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
|
||||
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
|
||||
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
|
||||
media:
|
||||
# 媒资目录:容器里指向挂载卷;本地默认 ./data/uploads
|
||||
root-dir: ${MEDIA_ROOT_DIR:./data/uploads}
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.controller;
|
||||
|
||||
import com.fruitshorts.admin.service.FavoriteAdminService;
|
||||
import com.fruitshorts.admin.service.LikeAdminService;
|
||||
import com.fruitshorts.admin.support.ControllerContractSupport;
|
||||
import com.fruitshorts.admin.vo.AdminFavoriteVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/** 收藏和点赞分页路由及响应契约。 */
|
||||
class EngagementControllerContractTest {
|
||||
@Test
|
||||
void should_return_guest_fields_for_favorites() throws Exception {
|
||||
FavoriteAdminService service = mock(FavoriteAdminService.class);
|
||||
AdminFavoriteVO guest = new AdminFavoriteVO();
|
||||
guest.setId(1L);
|
||||
guest.setDeviceId("guest");
|
||||
guest.setAnonymous(true);
|
||||
when(service.page(any())).thenReturn(new PageResult<>(1L, List.of(guest)));
|
||||
ControllerContractSupport.mockMvcOf(new FavoriteAdminController(service))
|
||||
.perform(get("/admin/favorites/page"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.total").value(1))
|
||||
.andExpect(jsonPath("$.data.list[0].deviceId").value("guest"))
|
||||
.andExpect(jsonPath("$.data.list[0].anonymous").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_like_page() throws Exception {
|
||||
LikeAdminService service = mock(LikeAdminService.class);
|
||||
when(service.page(any())).thenReturn(PageResult.empty());
|
||||
ControllerContractSupport.mockMvcOf(new LikeAdminController(service))
|
||||
.perform(get("/admin/likes/page").param("targetType", "COMMENT"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.total").value(0))
|
||||
.andExpect(jsonPath("$.data.list").isEmpty());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
/** 观看记录匹配登录系统。 */
|
||||
class AppSessionSystemServiceTest {
|
||||
|
||||
private final AppSessionSystemService service = new AppSessionSystemService(null);
|
||||
private final AppSessionSystemService service = new AppSessionSystemService(null, null);
|
||||
|
||||
@Test
|
||||
void should_use_same_device_session_when_watch_history_has_device() {
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fruitshorts.admin.vo.FavoriteQueryReqVO;
|
||||
import com.fruitshorts.admin.vo.LikeQueryReqVO;
|
||||
import com.fruitshorts.content.dal.mapper.DramaEpisodeMapper;
|
||||
import com.fruitshorts.interaction.dal.entity.ContentLike;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
|
||||
import com.fruitshorts.playback.dal.entity.UserFavorite;
|
||||
import com.fruitshorts.playback.dal.mapper.UserFavoriteMapper;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** 收藏及点赞分页的游客、空结果和多态目标检验。 */
|
||||
class EngagementAdminServiceTest {
|
||||
@BeforeAll
|
||||
static void initMetadata() {
|
||||
MybatisConfiguration config = new MybatisConfiguration();
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(config, "");
|
||||
TableInfoHelper.initTableInfo(assistant, UserFavorite.class);
|
||||
TableInfoHelper.initTableInfo(assistant, ContentLike.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_enable_logic_delete_for_both_interaction_entities() {
|
||||
assertThat(TableInfoHelper.getTableInfo(UserFavorite.class).isWithLogicDelete()).isTrue();
|
||||
assertThat(TableInfoHelper.getTableInfo(ContentLike.class).isWithLogicDelete()).isTrue();
|
||||
assertThat(TableInfoHelper.getTableInfo(UserFavorite.class).getLogicDeleteSql(true, true))
|
||||
.contains("deleted").contains("0");
|
||||
assertThat(TableInfoHelper.getTableInfo(ContentLike.class).getLogicDeleteSql(true, true))
|
||||
.contains("deleted").contains("0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_without_query_when_keyword_has_no_match() {
|
||||
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
|
||||
UserFavoriteMapper mapper = mock(UserFavoriteMapper.class);
|
||||
when(lookup.userIds("missing")).thenReturn(List.of());
|
||||
when(lookup.noMatch(List.of())).thenReturn(true);
|
||||
FavoriteQueryReqVO req = new FavoriteQueryReqVO();
|
||||
req.setKeyword("missing");
|
||||
var result = new FavoriteAdminService(mapper, lookup).page(req);
|
||||
assertThat(result.getTotal()).isZero();
|
||||
assertThat(result.getList()).isEmpty();
|
||||
verifyNoInteractions(mapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_keep_drama_published_unknown_when_drama_missing() {
|
||||
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
|
||||
UserFavoriteMapper mapper = mock(UserFavoriteMapper.class);
|
||||
when(lookup.page(any())).thenReturn(new Page<>(1, 10));
|
||||
UserFavorite row = new UserFavorite();
|
||||
row.setId(1L);
|
||||
row.setDeviceId("guest-device");
|
||||
row.setDramaId(2L);
|
||||
Page<UserFavorite> page = new Page<>(1, 10);
|
||||
page.setTotal(1);
|
||||
page.setRecords(List.of(row));
|
||||
when(mapper.selectPage(any(Page.class), any(Wrapper.class))).thenReturn(page);
|
||||
when(lookup.users(any())).thenReturn(Map.of());
|
||||
when(lookup.dramas(any())).thenReturn(Map.of());
|
||||
var result = new FavoriteAdminService(mapper, lookup).page(new FavoriteQueryReqVO());
|
||||
assertThat(result.getList().get(0).getAnonymous()).isTrue();
|
||||
assertThat(result.getList().get(0).getDeviceId()).isEqualTo("guest-device");
|
||||
// 短剧已不存在时不能误报成「未发布」
|
||||
assertThat(result.getList().get(0).getDramaPublished()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_preserve_guest_drama_like_without_episode() {
|
||||
EngagementAdminLookup lookup = mock(EngagementAdminLookup.class);
|
||||
ContentLikeMapper mapper = mock(ContentLikeMapper.class);
|
||||
when(lookup.page(any())).thenReturn(new Page<>(1, 10));
|
||||
ContentLike row = new ContentLike();
|
||||
row.setId(1L);
|
||||
row.setTargetType("DRAMA");
|
||||
row.setTargetId(2L);
|
||||
row.setDeviceId("guest-device");
|
||||
Page<ContentLike> page = new Page<>(1, 10);
|
||||
page.setTotal(1);
|
||||
page.setRecords(List.of(row));
|
||||
when(mapper.selectPage(any(Page.class), any(Wrapper.class))).thenReturn(page);
|
||||
when(lookup.users(any())).thenReturn(Map.of());
|
||||
when(lookup.dramas(any())).thenReturn(Map.of());
|
||||
var service = new LikeAdminService(mapper, mock(ContentCommentMapper.class),
|
||||
mock(DramaEpisodeMapper.class), lookup);
|
||||
var result = service.page(new LikeQueryReqVO());
|
||||
assertThat(result.getList().get(0).getAnonymous()).isTrue();
|
||||
assertThat(result.getList().get(0).getDramaId()).isEqualTo(2L);
|
||||
assertThat(result.getList().get(0).getEpisodeId()).isNull();
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -199,9 +199,10 @@ class WatchHistoryAdminServiceTest {
|
||||
}
|
||||
|
||||
private void stubBatchData() {
|
||||
given(appUserMapper.selectBatchIds(any())).willReturn(List.of(user(7L, "Alice")));
|
||||
given(dramaMapper.selectBatchIds(any())).willReturn(List.of(drama(5L, "Signal")));
|
||||
given(dramaEpisodeMapper.selectBatchIds(any())).willReturn(List.of(episode(11L)));
|
||||
// 装配阶段按需列查询,而不是 selectBatchIds,桩法要跟着改
|
||||
given(appUserMapper.selectList(any())).willReturn(List.of(user(7L, "Alice")));
|
||||
given(dramaMapper.selectList(any())).willReturn(List.of(drama(5L, "Signal")));
|
||||
given(dramaEpisodeMapper.selectList(any())).willReturn(List.of(episode(11L)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
+3
-1
@@ -30,7 +30,9 @@ public final class ControllerContractSupport {
|
||||
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
||||
@SuppressWarnings("unchecked")
|
||||
public static MockMvc mockMvcOf(Object controller) {
|
||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class));
|
||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(
|
||||
Mockito.mock(ObjectProvider.class),
|
||||
Mockito.mock(ObjectProvider.class));
|
||||
return MockMvcBuilders.standaloneSetup(controller)
|
||||
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
||||
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
||||
|
||||
+26
-5
@@ -24,6 +24,7 @@ import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/** 客户端账号:验证码、注册、登录、刷新、登出。 */
|
||||
@Tag(name = "客户端-账号")
|
||||
@@ -34,13 +35,14 @@ public class AppAuthController {
|
||||
|
||||
private final AppOtpService otpService;
|
||||
private final AppAuthService authService;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
/** 发送验证码。频控在服务端,客户端不需要自己限流。 */
|
||||
@Operation(summary = "发送验证码(频控在服务端)")
|
||||
@RateLimit(limit = 20, windowSeconds = 60, key = "otp")
|
||||
@PostMapping("/otp")
|
||||
public Result<Void> sendOtp(@Valid @RequestBody OtpSendReqVO req, HttpServletRequest request) {
|
||||
otpService.send(req, WebUtils.getClientIp(request));
|
||||
otpService.send(req, webUtils.clientIp(request));
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
@@ -48,7 +50,8 @@ public class AppAuthController {
|
||||
@PostMapping("/register")
|
||||
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
|
||||
HttpServletRequest request) {
|
||||
return Result.ok(authService.register(req, WebUtils.getClientIp(request)));
|
||||
applyHeaderDeviceId(req, request);
|
||||
return Result.ok(authService.register(req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "登录(验证码或密码)")
|
||||
@@ -56,13 +59,19 @@ public class AppAuthController {
|
||||
@PostMapping("/login")
|
||||
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
|
||||
HttpServletRequest request) {
|
||||
return Result.ok(authService.login(req, WebUtils.getClientIp(request)));
|
||||
applyHeaderDeviceId(req, request);
|
||||
return Result.ok(authService.login(req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
|
||||
@PostMapping("/google")
|
||||
public Result<TokenRespVO> google(@Valid @RequestBody GoogleLoginReqVO req) {
|
||||
return Result.ok(authService.googleLogin(req.getIdToken()));
|
||||
public Result<TokenRespVO> google(@Valid @RequestBody GoogleLoginReqVO req,
|
||||
HttpServletRequest request) {
|
||||
String headerDeviceId = request.getHeader("X-Device-Id");
|
||||
String deviceId = StringUtils.hasText(headerDeviceId)
|
||||
? headerDeviceId : req.getDeviceId();
|
||||
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId,
|
||||
webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
|
||||
@@ -78,4 +87,16 @@ public class AppAuthController {
|
||||
authService.logout(SecurityUtils.getUserIdOrNull(), req == null ? new LogoutReqVO() : req);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
private void applyHeaderDeviceId(RegisterReqVO req, HttpServletRequest request) {
|
||||
if (!StringUtils.hasText(req.getDeviceId())) {
|
||||
req.setDeviceId(request.getHeader("X-Device-Id"));
|
||||
}
|
||||
}
|
||||
|
||||
private void applyHeaderDeviceId(LoginReqVO req, HttpServletRequest request) {
|
||||
if (!StringUtils.hasText(req.getDeviceId())) {
|
||||
req.setDeviceId(request.getHeader("X-Device-Id"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-7
@@ -6,6 +6,9 @@ import com.fruitshorts.common.pojo.CursorResult;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.framework.security.SecurityUtils;
|
||||
import com.fruitshorts.framework.web.WebUtils;
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
@@ -33,7 +36,7 @@ import java.util.List;
|
||||
*
|
||||
* <p>列表走游标翻页:`cursor` 传上一页最后一条的 id,返回 `nextCursor` 与 `hasMore`。
|
||||
* 不传 `rootId` 时返回顶层评论,传了则返回该楼层的回复。
|
||||
* 列表允许匿名浏览;发布与删除需要登录。
|
||||
* 列表允许匿名浏览;发布与删除支持登录用户或设备身份。
|
||||
*/
|
||||
@Tag(name = "客户端-评论")
|
||||
@RestController
|
||||
@@ -43,13 +46,21 @@ public class AppCommentController {
|
||||
|
||||
private final CommentService commentService;
|
||||
private final EpisodeService episodeService;
|
||||
private final InteractionIdentityResolver identityResolver;
|
||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
@Operation(summary = "发布评论")
|
||||
@PostMapping
|
||||
public Result<CommentRespVO> publish(@Valid @RequestBody CommentPublishReqVO req,
|
||||
HttpServletRequest request) {
|
||||
return Result.ok(commentService.publish(SecurityUtils.getAppUserId(), req,
|
||||
WebUtils.getClientIp(request), request.getHeader("X-Device-Id")));
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "comment");
|
||||
return Result.ok(commentService.publish(
|
||||
identity, req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "评论列表(游标翻页,可匿名浏览)")
|
||||
@@ -58,14 +69,18 @@ public class AppCommentController {
|
||||
@RequestParam(required = false) Long episodeId,
|
||||
@RequestParam(required = false) Long rootId,
|
||||
@RequestParam(required = false) Long cursor,
|
||||
@RequestParam(required = false) Integer size) {
|
||||
@RequestParam(required = false) Integer size,
|
||||
HttpServletRequest request) {
|
||||
CommentQueryReqVO query = new CommentQueryReqVO();
|
||||
query.setDramaId(dramaId);
|
||||
query.setEpisodeId(episodeId);
|
||||
query.setRootId(rootId);
|
||||
query.setCursor(cursor);
|
||||
query.setSize(size);
|
||||
return Result.ok(commentService.page(SecurityUtils.getUserIdOrNull(), query));
|
||||
return Result.ok(commentService.page(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
query));
|
||||
}
|
||||
|
||||
@Operation(summary = "评论总数:传 episodeId 按集统计,仅 dramaId 时全剧统计(可匿名访问)")
|
||||
@@ -85,8 +100,13 @@ public class AppCommentController {
|
||||
|
||||
@Operation(summary = "删除自己的评论")
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> delete(@PathVariable Long id) {
|
||||
commentService.delete(SecurityUtils.getAppUserId(), id);
|
||||
public Result<Void> delete(@PathVariable Long id, HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
"");
|
||||
anonymousRateLimiter.check(identity, "comment");
|
||||
commentService.delete(identity, id);
|
||||
return Result.ok();
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -3,7 +3,9 @@
|
||||
package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fruitshorts.app.service.AppCatalogService;
|
||||
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
||||
import com.fruitshorts.app.vo.AppDramaDetailVO;
|
||||
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
@@ -34,6 +36,8 @@ public class AppDramaController {
|
||||
private final PlaybackService playbackService;
|
||||
private final EpisodeService episodeService;
|
||||
private final CommentService commentService;
|
||||
private final AppEpisodeStatsService appEpisodeStatsService;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
|
||||
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
|
||||
@@ -53,10 +57,21 @@ public class AppDramaController {
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
id,
|
||||
request.getHeader("X-Device-Id"),
|
||||
WebUtils.getClientIp(request));
|
||||
webUtils.clientIp(request));
|
||||
DramaEpisode episode = episodeService.getExisting(id);
|
||||
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
|
||||
vo.setCommentCount(commentService.countByEpisodes(List.of(id)).getOrDefault(id, 0L));
|
||||
return Result.ok(vo);
|
||||
}
|
||||
|
||||
/** 轻量计数快照:只读互动状态,不签发播放地址、不写票据缓存。 */
|
||||
@Operation(summary = "播放页轻量计数与当前用户互动状态")
|
||||
@GetMapping("/episodes/{id}/stats")
|
||||
public Result<AppEpisodeStatsVO> stats(
|
||||
@PathVariable Long id, HttpServletRequest request) {
|
||||
return Result.ok(appEpisodeStatsService.get(
|
||||
id,
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id")));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -25,11 +25,12 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AppEventController {
|
||||
|
||||
private final AppEventService eventService;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
@Operation(summary = "埋点事件批量上报")
|
||||
@PostMapping("/events")
|
||||
public Result<Void> report(@Valid @RequestBody AppEventReqVO req, HttpServletRequest request) {
|
||||
eventService.save(req, SecurityUtils.getUserIdOrNull(), WebUtils.getClientIp(request));
|
||||
eventService.save(req, SecurityUtils.getUserIdOrNull(), webUtils.clientIp(request));
|
||||
return Result.ok();
|
||||
}
|
||||
}
|
||||
+48
-6
@@ -6,6 +6,9 @@ import com.fruitshorts.app.service.AppCatalogService;
|
||||
import com.fruitshorts.app.vo.AppDramaCardVO;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.framework.security.SecurityUtils;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
@@ -14,6 +17,7 @@ import com.fruitshorts.playback.vo.FavoriteToggleReqVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -33,12 +37,21 @@ public class AppFavoriteController {
|
||||
|
||||
private final FavoriteService favoriteService;
|
||||
private final AppCatalogService appCatalogService;
|
||||
private final InteractionIdentityResolver identityResolver;
|
||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||
|
||||
/** 切换收藏,返回切换后的状态:true 为已收藏。 */
|
||||
@Operation(summary = "切换收藏(返回切换后的状态)")
|
||||
@PostMapping("/toggle")
|
||||
public Result<Boolean> toggle(@Valid @RequestBody FavoriteToggleReqVO req) {
|
||||
return Result.ok(favoriteService.toggle(SecurityUtils.getAppUserId(), req.getDramaId()));
|
||||
public Result<Boolean> toggle(
|
||||
@Valid @RequestBody FavoriteToggleReqVO req,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "favorite");
|
||||
return Result.ok(favoriteService.toggle(identity, req.getDramaId()));
|
||||
}
|
||||
|
||||
/** 收藏列表,卡片结构与首页一致。 */
|
||||
@@ -46,17 +59,46 @@ public class AppFavoriteController {
|
||||
@GetMapping
|
||||
public Result<PageResult<AppDramaCardVO>> list(
|
||||
@RequestParam(defaultValue = "1") int pageIndex,
|
||||
@RequestParam(defaultValue = "20") int pageSize) {
|
||||
@RequestParam(defaultValue = "20") int pageSize,
|
||||
@RequestParam(required = false) String deviceId,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
deviceId);
|
||||
PageResult<Drama> page = favoriteService.page(
|
||||
SecurityUtils.getAppUserId(), pageIndex, pageSize);
|
||||
identity, pageIndex, pageSize);
|
||||
return Result.ok(new PageResult<>(
|
||||
page.getTotal(), appCatalogService.toCards(page.getList())));
|
||||
}
|
||||
|
||||
@Operation(summary = "取消收藏")
|
||||
@DeleteMapping("/{dramaId}")
|
||||
public Result<Void> remove(@PathVariable Long dramaId) {
|
||||
favoriteService.remove(SecurityUtils.getAppUserId(), dramaId);
|
||||
public Result<Void> remove(@PathVariable Long dramaId, HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
"");
|
||||
anonymousRateLimiter.check(identity, "favorite");
|
||||
if (identity.authenticated()) {
|
||||
favoriteService.remove(identity.userId(), dramaId);
|
||||
} else {
|
||||
favoriteService.removeDevice(identity.deviceId(), dramaId);
|
||||
}
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 批量取消收藏,返回实际删除的关系数。 */
|
||||
@Operation(summary = "批量取消收藏")
|
||||
@PostMapping("/remove")
|
||||
public Result<Integer> removeBatch(
|
||||
@Valid @RequestBody FavoriteRemoveReqVO req,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "favorite");
|
||||
return Result.ok(favoriteService.removeBatch(identity, req.getDramaIds()));
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -3,7 +3,10 @@
|
||||
package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.framework.security.SecurityUtils;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.interaction.service.ReportService;
|
||||
import com.fruitshorts.interaction.vo.LikeToggleReqVO;
|
||||
@@ -12,6 +15,7 @@ import com.fruitshorts.interaction.vo.ReportCreateReqVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
@@ -27,12 +31,21 @@ public class AppInteractionController {
|
||||
|
||||
private final LikeService likeService;
|
||||
private final ReportService reportService;
|
||||
private final InteractionIdentityResolver identityResolver;
|
||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||
|
||||
/** 点赞/取消点赞,返回切换后的状态与最新计数。 */
|
||||
@Operation(summary = "点赞 / 取消点赞")
|
||||
@PostMapping("/likes/toggle")
|
||||
public Result<LikeToggleRespVO> toggleLike(@Valid @RequestBody LikeToggleReqVO req) {
|
||||
return Result.ok(likeService.toggle(SecurityUtils.getAppUserId(), req));
|
||||
public Result<LikeToggleRespVO> toggleLike(
|
||||
@Valid @RequestBody LikeToggleReqVO req,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "like");
|
||||
return Result.ok(likeService.toggle(identity, req));
|
||||
}
|
||||
|
||||
/** 提交举报:同一用户对同一目标只保留一条待处理工单。 */
|
||||
|
||||
+50
-10
@@ -4,6 +4,9 @@ package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.pojo.Result;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.framework.security.SecurityUtils;
|
||||
import com.fruitshorts.playback.service.WatchProgressService;
|
||||
import com.fruitshorts.playback.vo.ProgressRespVO;
|
||||
@@ -11,6 +14,7 @@ import com.fruitshorts.playback.vo.ProgressSaveReqVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -29,19 +33,34 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AppWatchController {
|
||||
|
||||
private final WatchProgressService progressService;
|
||||
private final InteractionIdentityResolver identityResolver;
|
||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||
|
||||
/** 上报进度:客户端每 10 秒一次,切集时立即上报一次。 */
|
||||
@Operation(summary = "上报观看进度(客户端每 10 秒一次)")
|
||||
@PostMapping("/progress")
|
||||
public Result<ProgressRespVO> save(@Valid @RequestBody ProgressSaveReqVO req) {
|
||||
return Result.ok(progressService.save(SecurityUtils.getAppUserId(), req));
|
||||
public Result<ProgressRespVO> save(@Valid @RequestBody ProgressSaveReqVO req,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "watch");
|
||||
return Result.ok(progressService.save(identity, req));
|
||||
}
|
||||
|
||||
/** 某部剧的续看位置,进详情页时用它决定"续看第 N 集"。 */
|
||||
@Operation(summary = "某部剧的续看位置")
|
||||
@GetMapping("/progress")
|
||||
public Result<ProgressRespVO> ofDrama(@RequestParam Long dramaId) {
|
||||
return Result.ok(progressService.ofDrama(SecurityUtils.getAppUserId(), dramaId));
|
||||
public Result<ProgressRespVO> ofDrama(
|
||||
@RequestParam Long dramaId,
|
||||
@RequestParam(required = false) String deviceId,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
deviceId);
|
||||
return Result.ok(progressService.ofDrama(identity, dramaId));
|
||||
}
|
||||
|
||||
/** 最近观看分页,契约与 /app/favorites 一致:pageIndex/pageSize。 */
|
||||
@@ -49,22 +68,43 @@ public class AppWatchController {
|
||||
@GetMapping("/recent")
|
||||
public Result<PageResult<ProgressRespVO>> recent(
|
||||
@RequestParam(defaultValue = "1") int pageIndex,
|
||||
@RequestParam(defaultValue = "20") int pageSize) {
|
||||
@RequestParam(defaultValue = "20") int pageSize,
|
||||
@RequestParam(required = false) String deviceId,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
deviceId);
|
||||
return Result.ok(progressService.recentPage(
|
||||
SecurityUtils.getAppUserId(), pageIndex, pageSize));
|
||||
identity, pageIndex, pageSize));
|
||||
}
|
||||
|
||||
@Operation(summary = "删除某部剧的观看记录")
|
||||
@DeleteMapping("/progress/{dramaId}")
|
||||
public Result<Void> remove(@PathVariable Long dramaId) {
|
||||
progressService.remove(SecurityUtils.getAppUserId(), dramaId);
|
||||
public Result<Void> remove(
|
||||
@PathVariable Long dramaId,
|
||||
@RequestParam(required = false) String deviceId,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
deviceId);
|
||||
anonymousRateLimiter.check(identity, "watch");
|
||||
progressService.remove(identity, dramaId);
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
@Operation(summary = "清空观看记录")
|
||||
@DeleteMapping("/progress")
|
||||
public Result<Void> clear() {
|
||||
progressService.clear(SecurityUtils.getAppUserId());
|
||||
public Result<Void> clear(
|
||||
@RequestParam(required = false) String deviceId,
|
||||
HttpServletRequest request) {
|
||||
InteractionIdentity identity = identityResolver.resolve(
|
||||
SecurityUtils.getUserIdOrNull(),
|
||||
request.getHeader("X-Device-Id"),
|
||||
deviceId);
|
||||
anonymousRateLimiter.check(identity, "watch");
|
||||
progressService.clear(identity);
|
||||
return Result.ok();
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.framework.redis.RedisService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/** 未登录非付费互动的设备级固定窗口限流。 */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AnonymousInteractionRateLimiter {
|
||||
|
||||
private final RedisService redisService;
|
||||
|
||||
@Value("${fruitshorts.interaction.anonymous-write-per-minute:30}")
|
||||
private int writesPerMinute = 30;
|
||||
|
||||
public void check(InteractionIdentity identity, String action) {
|
||||
if (identity.authenticated()) {
|
||||
return;
|
||||
}
|
||||
long count = redisService.increment(
|
||||
"app:anonymous-interaction:" + action + ":" + identity.deviceId(),
|
||||
Duration.ofMinutes(1));
|
||||
if (count > writesPerMinute) {
|
||||
throw new ServiceException(ErrorCode.TOO_MANY_REQUESTS, "操作过于频繁,请稍后再试");
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** 播放页只读计数快照;固定维度批量查询,不签发播放地址或票据。 */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AppEpisodeStatsService {
|
||||
|
||||
private final EpisodeService episodeService;
|
||||
private final DramaService dramaService;
|
||||
private final CommentService commentService;
|
||||
private final LikeService likeService;
|
||||
private final FavoriteService favoriteService;
|
||||
|
||||
public AppEpisodeStatsVO get(Long episodeId, Long userId, String deviceId) {
|
||||
Map<Long, AppEpisodeStatsVO> stats = batch(List.of(episodeId), userId, deviceId);
|
||||
AppEpisodeStatsVO result = stats.get(episodeId);
|
||||
if (result == null) {
|
||||
throw new ServiceException(ErrorCode.DATA_NOT_FOUND, "剧集不存在或未上线");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public AppEpisodeStatsVO get(Long episodeId, Long userId) {
|
||||
return get(episodeId, userId, "");
|
||||
}
|
||||
|
||||
/** 每类数据只查一次,供后续多集统计复用。 */
|
||||
public Map<Long, AppEpisodeStatsVO> batch(Collection<Long> episodeIds, Long userId) {
|
||||
return batch(episodeIds, userId, "");
|
||||
}
|
||||
|
||||
public Map<Long, AppEpisodeStatsVO> batch(
|
||||
Collection<Long> episodeIds, Long userId, String deviceId) {
|
||||
if (episodeIds == null || episodeIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<DramaEpisode> episodes = episodeService.listPublishedByIds(episodeIds);
|
||||
if (episodes.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<Long> normalizedIds = episodes.stream().map(DramaEpisode::getId).toList();
|
||||
List<Long> dramaIds = episodes.stream().map(DramaEpisode::getDramaId).distinct().toList();
|
||||
Map<Long, Long> commentCounts = commentService.countByEpisodes(normalizedIds);
|
||||
Map<Long, Drama> dramas = new HashMap<>();
|
||||
for (Drama drama : dramaService.listPublishedByIds(dramaIds)) {
|
||||
dramas.put(drama.getId(), drama);
|
||||
}
|
||||
Set<Long> likedIds = likeService.likedTargetIds(
|
||||
userId, deviceId, LikeService.TYPE_EPISODE, normalizedIds);
|
||||
Set<Long> favoriteDramaIds = favoriteService.favoriteDramaIds(
|
||||
userId, deviceId, dramaIds);
|
||||
|
||||
Map<Long, AppEpisodeStatsVO> result = new HashMap<>();
|
||||
for (DramaEpisode episode : episodes) {
|
||||
Drama drama = dramas.get(episode.getDramaId());
|
||||
if (drama == null) {
|
||||
continue;
|
||||
}
|
||||
AppEpisodeStatsVO vo = new AppEpisodeStatsVO();
|
||||
vo.setEpisodeId(episode.getId());
|
||||
vo.setDramaId(episode.getDramaId());
|
||||
vo.setLikeCount(episode.getLikeCount() == null ? 0L : episode.getLikeCount());
|
||||
vo.setCommentCount(commentCounts.getOrDefault(episode.getId(), 0L));
|
||||
vo.setFavoriteCount(drama.getFavoriteCount() == null ? 0L : drama.getFavoriteCount());
|
||||
vo.setLiked(likedIds.contains(episode.getId()));
|
||||
vo.setFavorited(favoriteDramaIds.contains(episode.getDramaId()));
|
||||
result.put(episode.getId(), vo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.user.event.AppInteractionMergeRequested;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.event.TransactionPhase;
|
||||
import org.springframework.transaction.event.TransactionalEventListener;
|
||||
|
||||
/** 在登录事务提交前执行合并,任一步失败都会整体回滚登录。 */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class InteractionAccountMergeListener {
|
||||
|
||||
private final InteractionAccountMergeService mergeService;
|
||||
|
||||
@TransactionalEventListener(
|
||||
phase = TransactionPhase.BEFORE_COMMIT,
|
||||
fallbackExecution = false)
|
||||
public void onMergeRequested(AppInteractionMergeRequested event) {
|
||||
mergeService.merge(event.userId(), event.deviceId());
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import com.fruitshorts.playback.service.WatchProgressService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/** 登录后的设备互动归并;三项迁移共享一个数据库事务。 */
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class InteractionAccountMergeService {
|
||||
|
||||
private final LikeService likeService;
|
||||
private final FavoriteService favoriteService;
|
||||
private final CommentService commentService;
|
||||
private final WatchProgressService watchProgressService;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void merge(Long userId, String deviceId) {
|
||||
LikeService.MergeResult likes = likeService.mergeDeviceIntoUser(userId, deviceId);
|
||||
FavoriteService.MergeResult favorites =
|
||||
favoriteService.mergeDeviceIntoUser(userId, deviceId);
|
||||
CommentService.MergeResult comments =
|
||||
commentService.mergeDeviceIntoUser(userId, deviceId);
|
||||
WatchProgressService.MergeResult watch =
|
||||
watchProgressService.mergeDeviceIntoUser(userId, deviceId);
|
||||
log.info(
|
||||
"interaction-merge userId={} deviceId={} "
|
||||
+ "likeMigrated={} likeDuplicates={} "
|
||||
+ "favoriteMigrated={} favoriteDuplicates={} "
|
||||
+ "commentMigrated={} commentDuplicates={} "
|
||||
+ "watchProgressMigrated={} watchProgressIgnored={} "
|
||||
+ "watchHistoryMigrated={} watchHistoryIgnored={}",
|
||||
userId,
|
||||
deviceId,
|
||||
likes.migrated(),
|
||||
likes.duplicates(),
|
||||
favorites.migrated(),
|
||||
favorites.duplicates(),
|
||||
comments.migrated(),
|
||||
comments.duplicates(),
|
||||
watch.progressMigrated(),
|
||||
watch.progressIgnored(),
|
||||
watch.historyMigrated(),
|
||||
watch.historyIgnored());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 播放页轻量计数快照,不触发票据签发。 */
|
||||
@Data
|
||||
public class AppEpisodeStatsVO {
|
||||
|
||||
private Long episodeId;
|
||||
private Long dramaId;
|
||||
private Long likeCount;
|
||||
private Long commentCount;
|
||||
private Long favoriteCount;
|
||||
private Boolean liked;
|
||||
private Boolean favorited;
|
||||
}
|
||||
@@ -11,4 +11,7 @@ public class GoogleLoginReqVO {
|
||||
|
||||
@NotBlank(message = "缺少 Google idToken")
|
||||
private String idToken;
|
||||
|
||||
/** 旧客户端未统一发送请求头时,仍可用于合并设备互动。 */
|
||||
private String deviceId;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.web;
|
||||
|
||||
import com.fruitshorts.user.service.DeviceProfileService;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 收集客户端上报的平台(iOS / Android)。
|
||||
*
|
||||
* <p>客户端在请求头带 `X-Client-Platform`,这里按 device_id 建档,
|
||||
* 后台列表据此区分两端;游客请求同样入库,这是与旧会话方案的关键差异。
|
||||
* 同一设备 60 秒内只写一次,避免每个请求都打库。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceProfileFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final long THROTTLE_MS = 60_000L;
|
||||
private static final int MAX_TRACKED_DEVICES = 20_000;
|
||||
|
||||
private final DeviceProfileService deviceProfileService;
|
||||
private final Map<String, Long> lastWriteAt = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
try {
|
||||
collect(request);
|
||||
} catch (RuntimeException ex) {
|
||||
// 画像只服务于后台展示,任何异常都不能影响业务请求
|
||||
log.warn("device-profile collect failed reason={}", ex.getMessage());
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void collect(HttpServletRequest request) {
|
||||
String deviceId = request.getHeader("X-Device-Id");
|
||||
if (!StringUtils.hasText(deviceId)) {
|
||||
return;
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
Long last = lastWriteAt.get(deviceId);
|
||||
if (last != null && now - last < THROTTLE_MS) {
|
||||
return;
|
||||
}
|
||||
if (lastWriteAt.size() > MAX_TRACKED_DEVICES) {
|
||||
lastWriteAt.clear();
|
||||
}
|
||||
lastWriteAt.put(deviceId, now);
|
||||
deviceProfileService.touch(deviceId, request.getHeader("X-Client-Platform"));
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,11 @@ springdoc:
|
||||
path: /v3/api-docs
|
||||
|
||||
fruitshorts:
|
||||
web:
|
||||
# 可信代理 CIDR 列表(逗号分隔)。默认空 = 永不解析 XFF,直接用 request.getRemoteAddr()。
|
||||
# 配了反代(Nginx/K8s ingress)时填上其 IP 段,才会从 XFF 取最右侧可信一跳。
|
||||
# 生产若开启了 Tomcat RemoteIpValve(prod profile 已配),保持空即可。
|
||||
trusted-proxies: ${FRUITSHORTS_TRUSTED_PROXIES:}
|
||||
auth:
|
||||
# 仅作 sys_config 缺失/非法时的兜底;运行时优先读取后台「系统配置」
|
||||
register-max-per-ip-per-day: ${REGISTER_MAX_PER_IP_PER_DAY:5}
|
||||
|
||||
+4
-1
@@ -4,6 +4,7 @@ package com.fruitshorts.app.controller;
|
||||
import com.fruitshorts.app.support.ControllerContractSupport;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.framework.web.WebUtils;
|
||||
import com.fruitshorts.user.service.AppAuthService;
|
||||
import com.fruitshorts.user.service.AppOtpService;
|
||||
import com.fruitshorts.user.vo.TokenRespVO;
|
||||
@@ -32,13 +33,15 @@ class AppAuthControllerContractTest {
|
||||
|
||||
private AppOtpService otpService;
|
||||
private AppAuthService authService;
|
||||
private WebUtils webUtils;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
otpService = mock(AppOtpService.class);
|
||||
authService = mock(AppAuthService.class);
|
||||
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService));
|
||||
webUtils = mock(WebUtils.class);
|
||||
mockMvc = ControllerContractSupport.mockMvcOf(new AppAuthController(otpService, authService, webUtils));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-1
@@ -2,6 +2,7 @@
|
||||
package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fruitshorts.app.service.AppCatalogService;
|
||||
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
||||
import com.fruitshorts.app.support.ControllerContractSupport;
|
||||
import com.fruitshorts.app.vo.AppBannerVO;
|
||||
import com.fruitshorts.app.vo.AppCategoryVO;
|
||||
@@ -49,7 +50,9 @@ class AppCatalogControllerContractTest {
|
||||
catalogMvc = ControllerContractSupport.mockMvcOf(new AppCatalogController(catalogService));
|
||||
dramaMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppDramaController(catalogService, mock(PlaybackService.class),
|
||||
mock(EpisodeService.class), mock(CommentService.class)));
|
||||
mock(EpisodeService.class), mock(CommentService.class),
|
||||
mock(AppEpisodeStatsService.class),
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+8
-1
@@ -6,6 +6,8 @@ import com.fruitshorts.app.support.ControllerContractSupport;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
@@ -32,7 +34,12 @@ class AppCommentControllerContractTest {
|
||||
commentService = mock(CommentService.class);
|
||||
episodeService = mock(EpisodeService.class);
|
||||
mockMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppCommentController(commentService, episodeService));
|
||||
new AppCommentController(
|
||||
commentService,
|
||||
episodeService,
|
||||
mock(InteractionIdentityResolver.class),
|
||||
mock(AnonymousInteractionRateLimiter.class),
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+231
-3
@@ -3,9 +3,21 @@
|
||||
package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
||||
import com.fruitshorts.app.service.AppCatalogService;
|
||||
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.pojo.CursorResult;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import com.fruitshorts.playback.service.PlaybackService;
|
||||
import com.fruitshorts.playback.service.WatchProgressService;
|
||||
import com.fruitshorts.playback.vo.ProgressRespVO;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.framework.log.AccessDeniedRecorder;
|
||||
import com.fruitshorts.framework.security.JwtAuthenticationFilter;
|
||||
import com.fruitshorts.framework.security.JwtTokenProvider;
|
||||
@@ -34,8 +46,12 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@@ -52,12 +68,39 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
private CommentService commentService;
|
||||
@Autowired
|
||||
private AppCatalogService catalogService;
|
||||
@Autowired
|
||||
private AppEpisodeStatsService episodeStatsService;
|
||||
@Autowired
|
||||
private FavoriteService favoriteService;
|
||||
@Autowired
|
||||
private WatchProgressService watchProgressService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
given(commentService.countByDrama(7L)).willReturn(9L);
|
||||
given(catalogService.feed("ANIME", null, null, 20))
|
||||
.willReturn(new CursorResult<>(List.of(), null, false));
|
||||
AppEpisodeStatsVO stats = new AppEpisodeStatsVO();
|
||||
stats.setEpisodeId(11L);
|
||||
stats.setDramaId(7L);
|
||||
stats.setLikeCount(12L);
|
||||
stats.setCommentCount(3L);
|
||||
stats.setFavoriteCount(8L);
|
||||
stats.setLiked(true);
|
||||
stats.setFavorited(false);
|
||||
given(episodeStatsService.get(11L, null, "device-a")).willReturn(stats);
|
||||
given(favoriteService.page(any(InteractionIdentity.class), any(Integer.class), any(Integer.class)))
|
||||
.willReturn(new PageResult<>(0L, List.of()));
|
||||
given(favoriteService.removeBatch(any(InteractionIdentity.class), anyList()))
|
||||
.willReturn(1);
|
||||
given(catalogService.toCards(List.of())).willReturn(List.of());
|
||||
given(watchProgressService.recentPage(
|
||||
any(InteractionIdentity.class), any(Integer.class), any(Integer.class)))
|
||||
.willReturn(new PageResult<>(0L, List.of()));
|
||||
given(watchProgressService.ofDrama(any(InteractionIdentity.class), any(Long.class)))
|
||||
.willReturn(null);
|
||||
given(watchProgressService.save(any(InteractionIdentity.class), any()))
|
||||
.willReturn(new ProgressRespVO());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -78,6 +121,93 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
.andExpect(jsonPath("$.data.list").isArray());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_allow_anonymous_non_paid_interactions_through_security_chain() throws Exception {
|
||||
mockMvc.perform(post("/app/likes/toggle")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.contentType("application/json")
|
||||
.content("{\"targetType\":\"EPISODE\",\"targetId\":\"11\"}"))
|
||||
.andExpect(status().isOk());
|
||||
mockMvc.perform(post("/app/favorites/toggle")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaId\":\"7\"}"))
|
||||
.andExpect(status().isOk());
|
||||
mockMvc.perform(post("/app/comments")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaId\":\"7\",\"content\":\"hello\"}"))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_allow_anonymous_episode_stats_through_security_chain() throws Exception {
|
||||
mockMvc.perform(get("/app/episodes/11/stats")
|
||||
.header("X-Device-Id", "device-a"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data.episodeId").value(11))
|
||||
.andExpect(jsonPath("$.data.liked").value(true))
|
||||
.andExpect(jsonPath("$.data.favoriteCount").value(8));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_allow_anonymous_library_and_watch_operations() throws Exception {
|
||||
mockMvc.perform(get("/app/favorites").header("X-Device-Id", "device-a"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
mockMvc.perform(get("/app/watch/recent").header("X-Device-Id", "device-a"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
mockMvc.perform(get("/app/watch/progress")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.param("dramaId", "7"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
mockMvc.perform(post("/app/watch/progress")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.contentType("application/json")
|
||||
.content("{\"episodeId\":11,\"positionMs\":1000}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
mockMvc.perform(delete("/app/watch/progress/7")
|
||||
.header("X-Device-Id", "device-a"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
mockMvc.perform(delete("/app/watch/progress")
|
||||
.header("X-Device-Id", "device-a"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_allow_anonymous_favorite_batch_removal_through_security_chain()
|
||||
throws Exception {
|
||||
mockMvc.perform(post("/app/favorites/remove")
|
||||
.header("X-Device-Id", "device-a")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaIds\":[\"7\"]}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_keep_paid_and_entitlement_operations_login_required() throws Exception {
|
||||
mockMvc.perform(post("/app/episodes/11/unlock"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||
mockMvc.perform(get("/app/wallet"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||
mockMvc.perform(post("/app/orders"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||
mockMvc.perform(get("/app/orders"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(ErrorCode.UNAUTHORIZED.getCode()));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@EnableWebSecurity
|
||||
@@ -90,8 +220,105 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppCommentController appCommentController(CommentService commentService) {
|
||||
return new AppCommentController(commentService, mock(EpisodeService.class));
|
||||
EpisodeService episodeService() {
|
||||
return mock(EpisodeService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppCommentController appCommentController(
|
||||
CommentService commentService,
|
||||
EpisodeService episodeService,
|
||||
InteractionIdentityResolver identityResolver,
|
||||
AnonymousInteractionRateLimiter rateLimiter) {
|
||||
return new AppCommentController(
|
||||
commentService,
|
||||
episodeService,
|
||||
identityResolver,
|
||||
rateLimiter,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||
}
|
||||
|
||||
@Bean
|
||||
LikeService likeService() {
|
||||
return mock(LikeService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
FavoriteService favoriteService() {
|
||||
return mock(FavoriteService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
WatchProgressService watchProgressService() {
|
||||
return mock(WatchProgressService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppInteractionController appInteractionController(
|
||||
LikeService likeService,
|
||||
InteractionIdentityResolver identityResolver,
|
||||
AnonymousInteractionRateLimiter rateLimiter) {
|
||||
return new AppInteractionController(
|
||||
likeService,
|
||||
mock(com.fruitshorts.interaction.service.ReportService.class),
|
||||
identityResolver,
|
||||
rateLimiter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppFavoriteController appFavoriteController(
|
||||
FavoriteService favoriteService,
|
||||
InteractionIdentityResolver identityResolver,
|
||||
AnonymousInteractionRateLimiter rateLimiter) {
|
||||
return new AppFavoriteController(
|
||||
favoriteService,
|
||||
mock(AppCatalogService.class),
|
||||
identityResolver,
|
||||
rateLimiter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppWatchController appWatchController(
|
||||
WatchProgressService watchProgressService,
|
||||
InteractionIdentityResolver identityResolver,
|
||||
AnonymousInteractionRateLimiter rateLimiter) {
|
||||
return new AppWatchController(
|
||||
watchProgressService,
|
||||
identityResolver,
|
||||
rateLimiter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppEpisodeStatsService appEpisodeStatsService() {
|
||||
return mock(AppEpisodeStatsService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
AppDramaController appDramaController(
|
||||
AppCatalogService appCatalogService,
|
||||
EpisodeService episodeService,
|
||||
CommentService commentService,
|
||||
AppEpisodeStatsService appEpisodeStatsService) {
|
||||
return new AppDramaController(
|
||||
appCatalogService,
|
||||
mock(PlaybackService.class),
|
||||
episodeService,
|
||||
commentService,
|
||||
appEpisodeStatsService,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||
}
|
||||
|
||||
@Bean
|
||||
InteractionIdentityResolver identityResolver() {
|
||||
return new InteractionIdentityResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
AnonymousInteractionRateLimiter anonymousInteractionRateLimiter() {
|
||||
AnonymousInteractionRateLimiter limiter =
|
||||
mock(AnonymousInteractionRateLimiter.class);
|
||||
Mockito.doNothing().when(limiter).check(Mockito.any(), Mockito.anyString());
|
||||
return limiter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -115,7 +342,7 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
RestAuthEntryPoint restAuthEntryPoint(ObjectMapper objectMapper) {
|
||||
return new RestAuthEntryPoint(
|
||||
objectMapper,
|
||||
new AccessDeniedRecorder(mock(ObjectProvider.class)));
|
||||
new AccessDeniedRecorder(mock(ObjectProvider.class), mock(ObjectProvider.class)));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -132,4 +359,5 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+64
-13
@@ -6,8 +6,11 @@ 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.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.framework.security.LoginUser;
|
||||
import com.fruitshorts.framework.interaction.InteractionIdentityResolver;
|
||||
import com.fruitshorts.app.service.AnonymousInteractionRateLimiter;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import com.fruitshorts.playback.service.WatchProgressService;
|
||||
import com.fruitshorts.playback.vo.ProgressRespVO;
|
||||
@@ -19,12 +22,16 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
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.status;
|
||||
|
||||
@@ -44,10 +51,17 @@ class AppLibraryPagingContractTest {
|
||||
favoriteService = mock(FavoriteService.class);
|
||||
catalogService = mock(AppCatalogService.class);
|
||||
progressService = mock(WatchProgressService.class);
|
||||
InteractionIdentityResolver identityResolver = new InteractionIdentityResolver();
|
||||
AnonymousInteractionRateLimiter rateLimiter =
|
||||
mock(AnonymousInteractionRateLimiter.class);
|
||||
favoriteMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppFavoriteController(favoriteService, catalogService));
|
||||
new AppFavoriteController(
|
||||
favoriteService,
|
||||
catalogService,
|
||||
identityResolver,
|
||||
rateLimiter));
|
||||
watchMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppWatchController(progressService));
|
||||
new AppWatchController(progressService, identityResolver, rateLimiter));
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new UsernamePasswordAuthenticationToken(
|
||||
new LoginUser(USER_ID, "app-user", "APP_USER", List.of()),
|
||||
@@ -66,9 +80,9 @@ class AppLibraryPagingContractTest {
|
||||
Drama first = drama(101L, "收藏一");
|
||||
Drama second = drama(102L, "收藏二");
|
||||
Drama third = drama(103L, "收藏三");
|
||||
given(favoriteService.page(USER_ID, 1, 20))
|
||||
given(favoriteService.page(any(InteractionIdentity.class), eq(1), eq(20)))
|
||||
.willReturn(new PageResult<>(21L, List.of(first, second)));
|
||||
given(favoriteService.page(USER_ID, 2, 20))
|
||||
given(favoriteService.page(any(InteractionIdentity.class), eq(2), eq(20)))
|
||||
.willReturn(new PageResult<>(21L, List.of(third)));
|
||||
given(catalogService.toCards(List.of(first, second)))
|
||||
.willReturn(List.of(card(101L), card(102L)));
|
||||
@@ -89,8 +103,8 @@ class AppLibraryPagingContractTest {
|
||||
.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);
|
||||
verify(favoriteService).page(any(InteractionIdentity.class), eq(1), eq(20));
|
||||
verify(favoriteService).page(any(InteractionIdentity.class), eq(2), eq(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,9 +112,9 @@ class AppLibraryPagingContractTest {
|
||||
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))
|
||||
given(progressService.recentPage(any(InteractionIdentity.class), eq(1), eq(20)))
|
||||
.willReturn(new PageResult<>(23L, List.of(first, second)));
|
||||
given(progressService.recentPage(USER_ID, 2, 20))
|
||||
given(progressService.recentPage(any(InteractionIdentity.class), eq(2), eq(20)))
|
||||
.willReturn(new PageResult<>(23L, List.of(third)));
|
||||
|
||||
watchMvc.perform(get("/app/watch/recent"))
|
||||
@@ -120,14 +134,51 @@ class AppLibraryPagingContractTest {
|
||||
.andExpect(jsonPath("$.data.list[0].dramaId").value("14"))
|
||||
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名三"));
|
||||
|
||||
verify(progressService).recentPage(USER_ID, 1, 20);
|
||||
verify(progressService).recentPage(USER_ID, 2, 20);
|
||||
verify(progressService).recentPage(any(InteractionIdentity.class), eq(1), eq(20));
|
||||
verify(progressService).recentPage(any(InteractionIdentity.class), eq(2), eq(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_remove_favorite_batch_for_signed_in_user() throws Exception {
|
||||
given(favoriteService.removeBatch(any(InteractionIdentity.class), eq(List.of(7L, 8L))))
|
||||
.willReturn(2);
|
||||
|
||||
favoriteMvc.perform(post("/app/favorites/remove")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaIds\":[\"7\",\"8\"]}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(0))
|
||||
.andExpect(jsonPath("$.data").value(2));
|
||||
|
||||
verify(favoriteService).removeBatch(any(InteractionIdentity.class), eq(List.of(7L, 8L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_empty_favorite_batch() throws Exception {
|
||||
favoriteMvc.perform(post("/app/favorites/remove")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaIds\":[]}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(400))
|
||||
.andExpect(jsonPath("$.message").value("dramaIds 不能为空"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_favorite_batch_over_limit() throws Exception {
|
||||
String dramaIds = String.join(",", Collections.nCopies(201, "\"7\""));
|
||||
|
||||
favoriteMvc.perform(post("/app/favorites/remove")
|
||||
.contentType("application/json")
|
||||
.content("{\"dramaIds\":[" + dramaIds + "]}"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(400))
|
||||
.andExpect(jsonPath("$.message").value("dramaIds 最多 200 条"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_keep_total_and_return_empty_list_when_watch_page_is_out_of_range()
|
||||
throws Exception {
|
||||
given(progressService.recentPage(USER_ID, 9, 20))
|
||||
given(progressService.recentPage(any(InteractionIdentity.class), eq(9), eq(20)))
|
||||
.willReturn(new PageResult<>(23L, List.of()));
|
||||
|
||||
watchMvc.perform(get("/app/watch/recent").param("pageIndex", "9"))
|
||||
@@ -140,7 +191,7 @@ class AppLibraryPagingContractTest {
|
||||
@Test
|
||||
void should_ignore_removed_limit_and_still_return_page_result() throws Exception {
|
||||
// limit 已从契约移除:即使客户端误传,也应走分页并返回 PageResult。
|
||||
given(progressService.recentPage(USER_ID, 1, 20))
|
||||
given(progressService.recentPage(any(InteractionIdentity.class), eq(1), eq(20)))
|
||||
.willReturn(new PageResult<>(3L, List.of(progress(12L, 88L, 6, "剧名一", 68))));
|
||||
|
||||
watchMvc.perform(get("/app/watch/recent").param("limit", "5"))
|
||||
@@ -150,7 +201,7 @@ class AppLibraryPagingContractTest {
|
||||
.andExpect(jsonPath("$.data.list.length()").value(1))
|
||||
.andExpect(jsonPath("$.data.list[0].dramaTitle").value("剧名一"));
|
||||
|
||||
verify(progressService).recentPage(USER_ID, 1, 20);
|
||||
verify(progressService).recentPage(any(InteractionIdentity.class), eq(1), eq(20));
|
||||
}
|
||||
|
||||
private Drama drama(Long id, String title) {
|
||||
|
||||
+32
-1
@@ -2,6 +2,8 @@
|
||||
package com.fruitshorts.app.controller;
|
||||
|
||||
import com.fruitshorts.app.service.AppCatalogService;
|
||||
import com.fruitshorts.app.service.AppEpisodeStatsService;
|
||||
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
|
||||
import com.fruitshorts.app.support.ControllerContractSupport;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
@@ -37,6 +39,7 @@ class AppPlaybackContractTest {
|
||||
private PlaybackService playbackService;
|
||||
private EpisodeService episodeService;
|
||||
private CommentService commentService;
|
||||
private AppEpisodeStatsService episodeStatsService;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@BeforeEach
|
||||
@@ -44,13 +47,15 @@ class AppPlaybackContractTest {
|
||||
playbackService = mock(PlaybackService.class);
|
||||
episodeService = mock(EpisodeService.class);
|
||||
commentService = mock(CommentService.class);
|
||||
episodeStatsService = mock(AppEpisodeStatsService.class);
|
||||
DramaEpisode episode = new DramaEpisode();
|
||||
episode.setLikeCount(88L);
|
||||
given(episodeService.getExisting(any())).willReturn(episode);
|
||||
given(commentService.countByEpisodes(any())).willReturn(Map.of());
|
||||
mockMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppDramaController(mock(AppCatalogService.class), playbackService,
|
||||
episodeService, commentService));
|
||||
episodeService, commentService, episodeStatsService,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -102,6 +107,32 @@ class AppPlaybackContractTest {
|
||||
verify(playbackService).play(isNull(), eq(13L), eq("device-9"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_episode_stats_without_play_ticket() throws Exception {
|
||||
AppEpisodeStatsVO stats = new AppEpisodeStatsVO();
|
||||
stats.setEpisodeId(11L);
|
||||
stats.setDramaId(7L);
|
||||
stats.setLikeCount(88L);
|
||||
stats.setCommentCount(8L);
|
||||
stats.setFavoriteCount(1800L);
|
||||
stats.setLiked(true);
|
||||
stats.setFavorited(false);
|
||||
given(episodeStatsService.get(11L, null, null)).willReturn(stats);
|
||||
|
||||
mockMvc.perform(get("/app/episodes/11/stats"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.episodeId").value("11"))
|
||||
.andExpect(jsonPath("$.data.dramaId").value("7"))
|
||||
.andExpect(jsonPath("$.data.likeCount").value("88"))
|
||||
.andExpect(jsonPath("$.data.commentCount").value("8"))
|
||||
.andExpect(jsonPath("$.data.favoriteCount").value("1800"))
|
||||
.andExpect(jsonPath("$.data.liked").value(true))
|
||||
.andExpect(jsonPath("$.data.favorited").value(false));
|
||||
|
||||
verify(episodeStatsService).get(11L, null, null);
|
||||
verify(playbackService, org.mockito.Mockito.never()).play(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
private PlayRespVO ticket(Long episodeId, boolean accessible, String accessType,
|
||||
String playUrl, String thumbnailsUrl) {
|
||||
PlayRespVO vo = new PlayRespVO();
|
||||
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.framework.redis.RedisService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class AnonymousInteractionRateLimiterTest {
|
||||
|
||||
@Test
|
||||
void should_reject_anonymous_device_after_per_minute_limit() {
|
||||
RedisService redisService = mock(RedisService.class);
|
||||
given(redisService.increment(anyString(), any())).willReturn(31L);
|
||||
AnonymousInteractionRateLimiter limiter =
|
||||
new AnonymousInteractionRateLimiter(redisService);
|
||||
ReflectionTestUtils.setField(limiter, "writesPerMinute", 30);
|
||||
|
||||
assertThatThrownBy(() -> limiter.check(
|
||||
new InteractionIdentity(null, "device-a"),
|
||||
"like"))
|
||||
.isInstanceOfSatisfying(ServiceException.class, error ->
|
||||
org.assertj.core.api.Assertions.assertThat(error.getCode())
|
||||
.isEqualTo(ErrorCode.TOO_MANY_REQUESTS.getCode()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_not_rate_limit_authenticated_user() {
|
||||
RedisService redisService = mock(RedisService.class);
|
||||
AnonymousInteractionRateLimiter limiter =
|
||||
new AnonymousInteractionRateLimiter(redisService);
|
||||
|
||||
limiter.check(new InteractionIdentity(9L, ""), "comment");
|
||||
|
||||
verify(redisService, never()).increment(anyString(), any());
|
||||
}
|
||||
}
|
||||
+65
-4
@@ -16,18 +16,22 @@ import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserOtpMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||
import com.fruitshorts.user.enums.AppUserStatus;
|
||||
import com.fruitshorts.user.event.AppInteractionMergeRequested;
|
||||
import com.fruitshorts.user.service.AppAuthService;
|
||||
import com.fruitshorts.user.service.AppOtpService;
|
||||
import com.fruitshorts.user.service.CredentialHasher;
|
||||
import com.fruitshorts.user.service.GoogleIdTokenVerifier;
|
||||
import com.fruitshorts.user.service.GoogleUser;
|
||||
import com.fruitshorts.user.service.IpRegionService;
|
||||
import com.fruitshorts.user.service.OtpSender;
|
||||
import com.fruitshorts.user.vo.LoginReqVO;
|
||||
import com.fruitshorts.user.vo.RegisterReqVO;
|
||||
import com.fruitshorts.user.vo.TokenRespVO;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
@@ -63,6 +67,8 @@ class AppAuthServiceTest {
|
||||
private PasswordEncoder passwordEncoder;
|
||||
private ConfigService configService;
|
||||
private GoogleIdTokenVerifier googleVerifier;
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
private IpRegionService ipRegionService;
|
||||
private AppAuthService authService;
|
||||
|
||||
@BeforeEach
|
||||
@@ -78,11 +84,15 @@ class AppAuthServiceTest {
|
||||
passwordEncoder = mock(PasswordEncoder.class);
|
||||
configService = mock(ConfigService.class);
|
||||
googleVerifier = mock(GoogleIdTokenVerifier.class);
|
||||
eventPublisher = mock(ApplicationEventPublisher.class);
|
||||
ipRegionService = mock(IpRegionService.class);
|
||||
given(configService.get(anyString(), anyString()))
|
||||
.willAnswer(invocation -> invocation.getArgument(1));
|
||||
// 单测里默认解析不出国家,走客户端区域 / 印尼兜底
|
||||
given(ipRegionService.resolveCountry(any())).willReturn("");
|
||||
authService = new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
||||
deviceMapper, otpService, hasher, tokenProvider, passwordEncoder, configService,
|
||||
googleVerifier);
|
||||
googleVerifier, eventPublisher, ipRegionService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,6 +108,9 @@ class AppAuthServiceTest {
|
||||
// 免码注册不等于"已验证":邮箱可达性没验证过,所以先记 0,等日后点验证链接再置 1
|
||||
assertThat(saved.get().getVerified()).isZero();
|
||||
verify(otpService, never()).consume(anyString(), anyString(), anyString(), any());
|
||||
AppInteractionMergeRequested event = capturedMergeEvent();
|
||||
assertThat(event.userId()).isEqualTo(1001L);
|
||||
assertThat(event.deviceId()).isEqualTo("device-9");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -251,6 +264,44 @@ class AppAuthServiceTest {
|
||||
assertThat(resp.getAccessToken()).isEqualTo("access-1");
|
||||
assertThat(resp.getUser().getUid()).isEqualTo("UAB12CD");
|
||||
verify(sessionMapper).insert(any(AppUserSession.class));
|
||||
AppInteractionMergeRequested event = capturedMergeEvent();
|
||||
assertThat(event.userId()).isEqualTo(1001L);
|
||||
assertThat(event.deviceId()).isEqualTo("device-9");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_sync_country_from_ip_on_login() {
|
||||
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
|
||||
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
|
||||
given(ipRegionService.resolveCountry(any())).willReturn("TH");
|
||||
|
||||
authService.login(emailLogin("abcd1234"), "49.237.8.1");
|
||||
|
||||
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
|
||||
verify(userMapper).updateById(captor.capture());
|
||||
AppUser saved = captor.getValue();
|
||||
assertThat(saved.getCountryCode()).isEqualTo("TH");
|
||||
assertThat(saved.getRegionCode()).isEqualTo("TH");
|
||||
assertThat(saved.getLanguage()).isEqualTo("en-US");
|
||||
assertThat(saved.getTimezone()).isEqualTo("Asia/Bangkok");
|
||||
assertThat(saved.getCurrency()).isEqualTo("THB");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_keep_user_customized_language_when_syncing_country() {
|
||||
AppUser user = user(AppUserStatus.NORMAL);
|
||||
user.setLanguage("zh-CN");
|
||||
stubLogin(credential("bcrypt-hash"), user);
|
||||
given(passwordEncoder.matches("abcd1234", "bcrypt-hash")).willReturn(true);
|
||||
given(ipRegionService.resolveCountry(any())).willReturn("TH");
|
||||
|
||||
authService.login(emailLogin("abcd1234"), "49.237.8.1");
|
||||
|
||||
ArgumentCaptor<AppUser> captor = ArgumentCaptor.forClass(AppUser.class);
|
||||
verify(userMapper).updateById(captor.capture());
|
||||
assertThat(captor.getValue().getCountryCode()).isEqualTo("TH");
|
||||
// 用户自己改过的语言不被 IP 覆盖
|
||||
assertThat(captor.getValue().getLanguage()).isEqualTo("zh-CN");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -307,11 +358,14 @@ class AppAuthServiceTest {
|
||||
});
|
||||
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
|
||||
|
||||
TokenRespVO resp = authService.googleLogin("google-id-token");
|
||||
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9", "203.0.113.9");
|
||||
|
||||
assertThat(resp.getAccessToken()).isEqualTo("access-1");
|
||||
assertThat(resp.isNewUser()).isTrue();
|
||||
verify(sessionMapper).insert(any(AppUserSession.class));
|
||||
AppInteractionMergeRequested event = capturedMergeEvent();
|
||||
assertThat(event.userId()).isEqualTo(1001L);
|
||||
assertThat(event.deviceId()).isEqualTo("device-9");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -319,7 +373,7 @@ class AppAuthServiceTest {
|
||||
given(googleVerifier.verify(anyString()))
|
||||
.willReturn(new GoogleUser("sub-1", "", "Alice", ""));
|
||||
|
||||
assertThatThrownBy(() -> authService.googleLogin("google-id-token"))
|
||||
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9", "203.0.113.9"))
|
||||
.isInstanceOf(ServiceException.class)
|
||||
.hasMessage("Google 账号未返回邮箱,无法登录");
|
||||
}
|
||||
@@ -353,6 +407,13 @@ class AppAuthServiceTest {
|
||||
return saved;
|
||||
}
|
||||
|
||||
private AppInteractionMergeRequested capturedMergeEvent() {
|
||||
ArgumentCaptor<AppInteractionMergeRequested> event =
|
||||
ArgumentCaptor.forClass(AppInteractionMergeRequested.class);
|
||||
verify(eventPublisher).publishEvent(event.capture());
|
||||
return event.getValue();
|
||||
}
|
||||
|
||||
private void stubLogin(AppUserCredential credential, AppUser user) {
|
||||
given(credentialMapper.selectOne(any())).willReturn(credential);
|
||||
given(userMapper.selectById(any())).willReturn(user);
|
||||
@@ -371,7 +432,7 @@ class AppAuthServiceTest {
|
||||
AppOtpService realOtpService = new AppOtpService(otpMapper, mock(OtpSender.class), otpHasher);
|
||||
return new AppAuthService(userMapper, credentialMapper, sessionMapper, consentMapper,
|
||||
deviceMapper, realOtpService, hasher, tokenProvider, passwordEncoder, configService,
|
||||
googleVerifier);
|
||||
googleVerifier, eventPublisher, ipRegionService);
|
||||
}
|
||||
|
||||
private void setRegisterLimits(int perIp, int perDevice) {
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.app.vo.AppEpisodeStatsVO;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class AppEpisodeStatsServiceTest {
|
||||
|
||||
@Test
|
||||
void should_batch_single_episode_stats_without_ticket_side_effects() {
|
||||
EpisodeService episodeService = mock(EpisodeService.class);
|
||||
DramaService dramaService = mock(DramaService.class);
|
||||
CommentService commentService = mock(CommentService.class);
|
||||
LikeService likeService = mock(LikeService.class);
|
||||
FavoriteService favoriteService = mock(FavoriteService.class);
|
||||
|
||||
DramaEpisode episode = new DramaEpisode();
|
||||
episode.setId(11L);
|
||||
episode.setDramaId(7L);
|
||||
episode.setLikeCount(88L);
|
||||
Drama drama = new Drama();
|
||||
drama.setId(7L);
|
||||
drama.setFavoriteCount(1800L);
|
||||
given(episodeService.listPublishedByIds(List.of(11L))).willReturn(List.of(episode));
|
||||
given(dramaService.listPublishedByIds(List.of(7L))).willReturn(List.of(drama));
|
||||
given(commentService.countByEpisodes(List.of(11L))).willReturn(Map.of(11L, 8L));
|
||||
given(likeService.likedTargetIds(
|
||||
100L, "device-1", LikeService.TYPE_EPISODE, List.of(11L)))
|
||||
.willReturn(Set.of(11L));
|
||||
given(favoriteService.favoriteDramaIds(100L, "device-1", List.of(7L)))
|
||||
.willReturn(Set.of());
|
||||
|
||||
AppEpisodeStatsService service = new AppEpisodeStatsService(
|
||||
episodeService, dramaService, commentService, likeService, favoriteService);
|
||||
AppEpisodeStatsVO result = service.get(11L, 100L, "device-1");
|
||||
|
||||
assertThat(result.getEpisodeId()).isEqualTo(11L);
|
||||
assertThat(result.getDramaId()).isEqualTo(7L);
|
||||
assertThat(result.getLikeCount()).isEqualTo(88L);
|
||||
assertThat(result.getCommentCount()).isEqualTo(8L);
|
||||
assertThat(result.getFavoriteCount()).isEqualTo(1800L);
|
||||
assertThat(result.getLiked()).isTrue();
|
||||
assertThat(result.getFavorited()).isFalse();
|
||||
verify(episodeService).listPublishedByIds(List.of(11L));
|
||||
verify(commentService).countByEpisodes(List.of(11L));
|
||||
verify(likeService).likedTargetIds(
|
||||
100L, "device-1", LikeService.TYPE_EPISODE, List.of(11L));
|
||||
verify(favoriteService).favoriteDramaIds(100L, "device-1", List.of(7L));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Author: fruit.com.cn
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.user.enums.CountryProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** 国家解析与映射:IP 库文本 → ISO-2,再据此选语言/时区/币种。 */
|
||||
class CountryProfileTest {
|
||||
|
||||
@Test
|
||||
void should_map_ip_region_text_to_iso_code() {
|
||||
assertThat(CountryProfile.fromIpRegion("中国|0|广东省|深圳市|电信")).isEqualTo("CN");
|
||||
assertThat(CountryProfile.fromIpRegion("中国|0|台湾省|0|中华电信")).isEqualTo("TW");
|
||||
assertThat(CountryProfile.fromIpRegion("中国|0|香港|0|0")).isEqualTo("HK");
|
||||
assertThat(CountryProfile.fromIpRegion("中国|0|澳门|0|澳门电讯")).isEqualTo("MO");
|
||||
assertThat(CountryProfile.fromIpRegion("美国|0|0|0|Level3")).isEqualTo("US");
|
||||
assertThat(CountryProfile.fromIpRegion("印度尼西亚|0|大雅加达|雅加达|0")).isEqualTo("ID");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_for_private_ip_and_unknown_country() {
|
||||
assertThat(CountryProfile.fromIpRegion("0|0|0|内网IP|内网IP")).isEmpty();
|
||||
assertThat(CountryProfile.fromIpRegion("")).isEmpty();
|
||||
// 未收录的国家交给上层回退到客户端区域
|
||||
assertThat(CountryProfile.fromIpRegion("津巴布韦|0|0|0|0")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_normalize_client_region_and_fallback_to_default() {
|
||||
assertThat(CountryProfile.normalizeClientCode(" id ")).isEqualTo("ID");
|
||||
assertThat(CountryProfile.normalizeClientCode("us")).isEqualTo("US");
|
||||
assertThat(CountryProfile.normalizeClientCode("XX")).isEmpty();
|
||||
assertThat(CountryProfile.normalizeClientCode("")).isEmpty();
|
||||
|
||||
assertThat(CountryProfile.of("US").currency()).isEqualTo("USD");
|
||||
assertThat(CountryProfile.of("US").language()).isEqualTo("en-US");
|
||||
assertThat(CountryProfile.of("").code()).isEqualTo("ID");
|
||||
assertThat(CountryProfile.of("").currency()).isEqualTo("IDR");
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.interaction.service.CommentService;
|
||||
import com.fruitshorts.interaction.service.LikeService;
|
||||
import com.fruitshorts.playback.service.FavoriteService;
|
||||
import com.fruitshorts.playback.service.WatchProgressService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class InteractionAccountMergeServiceTest {
|
||||
|
||||
@Test
|
||||
void should_merge_all_device_interactions_and_watch_data() {
|
||||
LikeService likeService = mock(LikeService.class);
|
||||
FavoriteService favoriteService = mock(FavoriteService.class);
|
||||
CommentService commentService = mock(CommentService.class);
|
||||
WatchProgressService watchService = mock(WatchProgressService.class);
|
||||
given(likeService.mergeDeviceIntoUser(9L, "device-a"))
|
||||
.willReturn(new LikeService.MergeResult(1, 0));
|
||||
given(favoriteService.mergeDeviceIntoUser(9L, "device-a"))
|
||||
.willReturn(new FavoriteService.MergeResult(1, 0));
|
||||
given(commentService.mergeDeviceIntoUser(9L, "device-a"))
|
||||
.willReturn(new CommentService.MergeResult(1, 0));
|
||||
given(watchService.mergeDeviceIntoUser(9L, "device-a"))
|
||||
.willReturn(new WatchProgressService.MergeResult(2, 1, 3, 2));
|
||||
InteractionAccountMergeService service = new InteractionAccountMergeService(
|
||||
likeService, favoriteService, commentService, watchService);
|
||||
|
||||
service.merge(9L, "device-a");
|
||||
|
||||
verify(likeService).mergeDeviceIntoUser(9L, "device-a");
|
||||
verify(favoriteService).mergeDeviceIntoUser(9L, "device-a");
|
||||
verify(commentService).mergeDeviceIntoUser(9L, "device-a");
|
||||
verify(watchService).mergeDeviceIntoUser(9L, "device-a");
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// Author: fruit.com.cn
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.user.service.IpRegionService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* IpRegionService 集成测试:真实 xdb 文件 + 真实 resolve。
|
||||
*
|
||||
* <p>xdb 在 fruitshorts-module-user 的 resources/ip2region/ip2region.xdb 下(11MB),
|
||||
* 打包后会进 app-api 的 classpath。这个测试验证 Service 层调 ip2region 库的行为——
|
||||
* 合法公网 IP → ISO-2 国家码,内网/保留地址/空 → 空串。
|
||||
*/
|
||||
class IpRegionServiceTest {
|
||||
|
||||
private IpRegionService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new IpRegionService();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_resolve_known_public_ips() {
|
||||
assertThat(service.resolveCountry("8.8.8.8")).isEqualTo("US");
|
||||
assertThat(service.resolveCountry("114.114.114.114")).isEqualTo("CN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_for_private_loopback_and_reserved() {
|
||||
assertThat(service.resolveCountry("127.0.0.1")).isEmpty();
|
||||
assertThat(service.resolveCountry("0.0.0.0")).isEmpty();
|
||||
assertThat(service.resolveCountry("10.0.0.1")).isEmpty();
|
||||
assertThat(service.resolveCountry("192.168.1.1")).isEmpty();
|
||||
assertThat(service.resolveCountry("172.16.0.1")).isEmpty();
|
||||
assertThat(service.resolveCountry("169.254.1.1")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_empty_for_invalid_inputs() {
|
||||
assertThat(service.resolveCountry("")).isEmpty();
|
||||
assertThat(service.resolveCountry(null)).isEmpty();
|
||||
assertThat(service.resolveCountry("not-an-ip")).isEmpty();
|
||||
assertThat(service.resolveCountry("999.999.999.999")).isEmpty();
|
||||
}
|
||||
}
|
||||
+27
@@ -1,6 +1,8 @@
|
||||
// Author: fruit.com.cn
|
||||
package com.fruitshorts.app.service;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
@@ -20,6 +22,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -112,6 +115,30 @@ class PlaybackServiceTest {
|
||||
verify(ticketMapper, never()).insert(any(PlaybackTicket.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_locked_episode_ticket_for_anonymous_device() {
|
||||
given(episodeService.getPublished(12L)).willReturn(episode(12L, 0, 60, "/files/episode/2.mp4"));
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
playbackService.play(null, 12L, "device-9", "203.0.113.8"))
|
||||
.isInstanceOf(ServiceException.class)
|
||||
.extracting(error -> ((ServiceException) error).getCode())
|
||||
.isEqualTo(ErrorCode.UNAUTHORIZED.getCode());
|
||||
verify(signer, never()).sign(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_locked_episode_ticket_before_no_media_for_anonymous_device() {
|
||||
given(episodeService.getPublished(17L)).willReturn(episode(17L, 0, 60, ""));
|
||||
|
||||
assertThatThrownBy(() ->
|
||||
playbackService.play(null, 17L, "device-9", "203.0.113.8"))
|
||||
.isInstanceOf(ServiceException.class)
|
||||
.extracting(error -> ((ServiceException) error).getCode())
|
||||
.isEqualTo(ErrorCode.UNAUTHORIZED.getCode());
|
||||
verify(signer, never()).sign(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_return_entitled_access_when_entitlement_port_confirms_unlock() {
|
||||
given(episodeService.getPublished(13L)).willReturn(episode(13L, 0, 60, "/files/episode/3.mp4"));
|
||||
|
||||
+4
-1
@@ -2,6 +2,7 @@
|
||||
package com.fruitshorts.app.support;
|
||||
|
||||
import com.fruitshorts.framework.log.AccessDeniedRecorder;
|
||||
import com.fruitshorts.framework.web.WebUtils;
|
||||
import com.fruitshorts.framework.web.JacksonLongToStringConfig;
|
||||
import com.fruitshorts.framework.web.GlobalExceptionHandler;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
@@ -30,7 +31,9 @@ public final class ControllerContractSupport {
|
||||
/** 组装一个只含指定控制器与全局异常处理的 MockMvc。 */
|
||||
@SuppressWarnings("unchecked")
|
||||
public static MockMvc mockMvcOf(Object controller) {
|
||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(Mockito.mock(ObjectProvider.class));
|
||||
AccessDeniedRecorder recorder = new AccessDeniedRecorder(
|
||||
Mockito.mock(ObjectProvider.class),
|
||||
Mockito.mock(ObjectProvider.class));
|
||||
return MockMvcBuilders.standaloneSetup(controller)
|
||||
.setControllerAdvice(new GlobalExceptionHandler(recorder))
|
||||
// 与 Spring Boot 的 Jackson 配置对齐:时间按 ISO 字符串输出而不是数组,
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.interaction.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
import com.fruitshorts.interaction.config.InteractionProperties;
|
||||
import com.fruitshorts.interaction.dal.entity.ContentComment;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentAuditRecordMapper;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentCommentMapper;
|
||||
import com.fruitshorts.interaction.dal.mapper.ContentLikeMapper;
|
||||
import com.fruitshorts.interaction.vo.CommentPublishReqVO;
|
||||
import com.fruitshorts.interaction.vo.CommentRespVO;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class AnonymousCommentServiceTest {
|
||||
|
||||
private ContentCommentMapper commentMapper;
|
||||
private SensitiveWordService sensitiveWordService;
|
||||
private CommentService commentService;
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
ContentComment.class);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
commentMapper = mock(ContentCommentMapper.class);
|
||||
sensitiveWordService = mock(SensitiveWordService.class);
|
||||
AuditRecorder auditRecorder = mock(AuditRecorder.class);
|
||||
commentService = new CommentService(
|
||||
commentMapper,
|
||||
mock(ContentLikeMapper.class),
|
||||
mock(ContentAuditRecordMapper.class),
|
||||
mock(AppUserMapper.class),
|
||||
mock(DramaService.class),
|
||||
mock(EpisodeService.class),
|
||||
sensitiveWordService,
|
||||
auditRecorder,
|
||||
new InteractionProperties());
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_publish_anonymous_comment_with_guest_name_and_device_owner() {
|
||||
given(commentMapper.selectCount(any())).willReturn(0L);
|
||||
given(commentMapper.insert(any(ContentComment.class))).willReturn(1);
|
||||
given(sensitiveWordService.check("hello")).willReturn(
|
||||
SensitiveWordCheck.pass("hello"));
|
||||
|
||||
CommentRespVO result = commentService.publish(
|
||||
new InteractionIdentity(null, "device-a"),
|
||||
request("hello"),
|
||||
"127.0.0.1");
|
||||
|
||||
ArgumentCaptor<ContentComment> captor =
|
||||
ArgumentCaptor.forClass(ContentComment.class);
|
||||
verify(commentMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getUserId()).isNull();
|
||||
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
|
||||
assertThat(result.getNickname()).isEqualTo("游客");
|
||||
assertThat(result.getMine()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_reject_duplicate_anonymous_content_within_one_minute() {
|
||||
given(commentMapper.selectCount(any())).willReturn(0L, 1L);
|
||||
given(sensitiveWordService.check("hello")).willReturn(
|
||||
SensitiveWordCheck.pass("hello"));
|
||||
|
||||
assertThatThrownBy(() -> commentService.publish(
|
||||
new InteractionIdentity(null, "device-a"),
|
||||
request("hello"),
|
||||
"127.0.0.1"))
|
||||
.hasMessageContaining("重复");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_merge_device_comments_and_remove_duplicate() {
|
||||
ContentComment duplicate = comment(1L, "same");
|
||||
ContentComment unique = comment(2L, "new");
|
||||
given(commentMapper.selectList(any())).willReturn(List.of(duplicate, unique));
|
||||
given(commentMapper.selectOne(any())).willReturn(comment(3L, "same"), null);
|
||||
given(commentMapper.physicalDeleteById(1L)).willReturn(1);
|
||||
|
||||
CommentService.MergeResult result =
|
||||
commentService.mergeDeviceIntoUser(9L, "device-a");
|
||||
|
||||
assertThat(result.migrated()).isEqualTo(1);
|
||||
assertThat(result.duplicates()).isEqualTo(1);
|
||||
verify(commentMapper).physicalDeleteById(1L);
|
||||
verify(commentMapper).updateById(unique);
|
||||
assertThat(unique.getUserId()).isEqualTo(9L);
|
||||
}
|
||||
|
||||
private CommentPublishReqVO request(String content) {
|
||||
CommentPublishReqVO req = new CommentPublishReqVO();
|
||||
req.setDramaId(7L);
|
||||
req.setContent(content);
|
||||
return req;
|
||||
}
|
||||
|
||||
private ContentComment comment(Long id, String content) {
|
||||
ContentComment comment = new ContentComment();
|
||||
comment.setId(id);
|
||||
comment.setDramaId(7L);
|
||||
comment.setEpisodeId(0L);
|
||||
comment.setParentId(0L);
|
||||
comment.setContent(content);
|
||||
comment.setStatus(CommentService.STATUS_PUBLISHED);
|
||||
comment.setDeviceId("device-a");
|
||||
return comment;
|
||||
}
|
||||
}
|
||||
+50
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
@@ -19,6 +20,9 @@ import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
@@ -95,6 +99,44 @@ class LikeServiceEpisodeTest {
|
||||
verify(likeMapper, never()).insert(any(ContentLike.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_store_anonymous_episode_like_by_device() {
|
||||
DramaEpisode published = episode(1L);
|
||||
given(episodeService.getPublished(11L)).willReturn(published);
|
||||
given(dramaService.getPublished(5L)).willReturn(new Drama());
|
||||
given(likeMapper.selectOne(any())).willReturn(null);
|
||||
given(episodeService.getExisting(11L)).willReturn(published);
|
||||
|
||||
likeService.toggle(new InteractionIdentity(null, "device-a"), request(11L));
|
||||
|
||||
ArgumentCaptor<ContentLike> captor = ArgumentCaptor.forClass(ContentLike.class);
|
||||
verify(likeMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getUserId()).isNull();
|
||||
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_merge_device_likes_and_decrement_duplicate_count_once() {
|
||||
DramaEpisode published = episode(2L);
|
||||
ContentLike duplicate = like(1L, LikeService.TYPE_EPISODE, 11L);
|
||||
ContentLike unique = like(2L, LikeService.TYPE_EPISODE, 12L);
|
||||
given(likeMapper.selectList(any())).willReturn(List.of(duplicate, unique));
|
||||
given(likeMapper.selectOne(any())).willReturn(
|
||||
like(3L, LikeService.TYPE_EPISODE, 11L),
|
||||
null);
|
||||
given(likeMapper.physicalDeleteById(1L)).willReturn(1);
|
||||
given(episodeService.getExisting(11L)).willReturn(published);
|
||||
given(episodeService.getExisting(12L)).willReturn(published);
|
||||
|
||||
LikeService.MergeResult result = likeService.mergeDeviceIntoUser(9L, "device-a");
|
||||
|
||||
assertThat(result.migrated()).isEqualTo(1);
|
||||
assertThat(result.duplicates()).isEqualTo(1);
|
||||
verify(episodeService).adjustLikeCount(11L, -1);
|
||||
verify(likeMapper).updateById(unique);
|
||||
assertThat(unique.getUserId()).isEqualTo(9L);
|
||||
}
|
||||
|
||||
private DramaEpisode episode(Long likeCount) {
|
||||
DramaEpisode episode = new DramaEpisode();
|
||||
episode.setId(11L);
|
||||
@@ -109,4 +151,12 @@ class LikeServiceEpisodeTest {
|
||||
req.setTargetId(episodeId);
|
||||
return req;
|
||||
}
|
||||
|
||||
private ContentLike like(Long id, String type, Long targetId) {
|
||||
ContentLike like = new ContentLike();
|
||||
like.setId(id);
|
||||
like.setTargetType(type);
|
||||
like.setTargetId(targetId);
|
||||
return like;
|
||||
}
|
||||
}
|
||||
+67
-1
@@ -7,6 +7,7 @@ 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.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
import com.fruitshorts.playback.dal.entity.UserFavorite;
|
||||
@@ -58,6 +59,38 @@ class FavoriteServiceTest {
|
||||
verify(dramaService).adjustFavoriteCount(7L, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_store_anonymous_favorite_by_device() {
|
||||
given(favoriteMapper.selectOne(any())).willReturn(null);
|
||||
given(favoriteMapper.insert(any(UserFavorite.class))).willReturn(1);
|
||||
|
||||
favoriteService.toggle(new InteractionIdentity(null, "device-a"), 7L);
|
||||
|
||||
ArgumentCaptor<UserFavorite> captor = ArgumentCaptor.forClass(UserFavorite.class);
|
||||
verify(favoriteMapper).insert(captor.capture());
|
||||
assertThat(captor.getValue().getUserId()).isNull();
|
||||
assertThat(captor.getValue().getDeviceId()).isEqualTo("device-a");
|
||||
verify(dramaService).adjustFavoriteCount(7L, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_merge_device_favorites_and_decrement_duplicate_count_once() {
|
||||
UserFavorite duplicate = favorite(7L);
|
||||
UserFavorite unique = favorite(8L);
|
||||
given(favoriteMapper.selectList(any())).willReturn(List.of(duplicate, unique));
|
||||
given(favoriteMapper.selectOne(any())).willReturn(favorite(9L), null);
|
||||
given(favoriteMapper.physicalDeleteById(duplicate.getId())).willReturn(1);
|
||||
|
||||
FavoriteService.MergeResult result =
|
||||
favoriteService.mergeDeviceIntoUser(1L, "device-a");
|
||||
|
||||
assertThat(result.migrated()).isEqualTo(1);
|
||||
assertThat(result.duplicates()).isEqualTo(1);
|
||||
verify(dramaService).adjustFavoriteCount(7L, -1);
|
||||
verify(favoriteMapper).updateById(unique);
|
||||
assertThat(unique.getUserId()).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_decrement_favorite_count_when_toggle_removes_relation() {
|
||||
given(favoriteMapper.selectOne(any())).willReturn(new UserFavorite());
|
||||
@@ -87,13 +120,28 @@ class FavoriteServiceTest {
|
||||
given(favoriteMapper.physicalDelete(1L, 8L)).willReturn(0);
|
||||
given(favoriteMapper.physicalDelete(1L, 9L)).willReturn(1);
|
||||
|
||||
favoriteService.removeBatch(1L, Arrays.asList(7L, 8L, 9L, null));
|
||||
int deleted =
|
||||
favoriteService.removeBatch(1L, Arrays.asList(7L, 8L, 9L, 7L, null));
|
||||
|
||||
assertThat(deleted).isEqualTo(2);
|
||||
verify(dramaService).adjustFavoriteCount(7L, -1);
|
||||
verify(dramaService, never()).adjustFavoriteCount(8L, -1);
|
||||
verify(dramaService).adjustFavoriteCount(9L, -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_remove_anonymous_batch_by_device_and_return_deleted_count() {
|
||||
given(favoriteMapper.physicalDeleteDevice("device-a", 7L)).willReturn(1);
|
||||
given(favoriteMapper.physicalDeleteDevice("device-a", 8L)).willReturn(1);
|
||||
|
||||
int deleted = favoriteService.removeBatch(
|
||||
new InteractionIdentity(null, "device-a"), List.of(7L, 8L));
|
||||
|
||||
assertThat(deleted).isEqualTo(2);
|
||||
verify(dramaService).adjustFavoriteCount(7L, -1);
|
||||
verify(dramaService).adjustFavoriteCount(8L, -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_use_database_page_and_keep_favorite_order_when_listing() {
|
||||
UserFavorite first = favorite(51L);
|
||||
@@ -124,6 +172,24 @@ class FavoriteServiceTest {
|
||||
verify(dramaService).listPublishedByIds(List.of(51L, 52L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_page_anonymous_favorites_by_device() {
|
||||
Page<UserFavorite> databasePage = new Page<>(1, 20, 0);
|
||||
databasePage.setRecords(List.of());
|
||||
given(favoriteMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
|
||||
|
||||
favoriteService.page(
|
||||
new InteractionIdentity(null, "device-a"), 1, 20);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Wrapper<UserFavorite>> wrapperCaptor =
|
||||
ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(favoriteMapper).selectPage(any(Page.class), wrapperCaptor.capture());
|
||||
assertThat(wrapperCaptor.getValue().getSqlSegment())
|
||||
.contains("user_id IS NULL")
|
||||
.contains("device_id");
|
||||
}
|
||||
|
||||
private UserFavorite favorite(Long dramaId) {
|
||||
UserFavorite favorite = new UserFavorite();
|
||||
favorite.setDramaId(dramaId);
|
||||
|
||||
+198
-2
@@ -7,22 +7,26 @@ 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.common.interaction.InteractionIdentity;
|
||||
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.entity.WatchHistory;
|
||||
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.apache.ibatis.annotations.Select;
|
||||
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.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -43,6 +47,7 @@ class WatchProgressServiceTest {
|
||||
}
|
||||
|
||||
private WatchProgressMapper progressMapper;
|
||||
private WatchHistoryMapper historyMapper;
|
||||
private DramaService dramaService;
|
||||
private EpisodeService episodeService;
|
||||
private WatchProgressService progressService;
|
||||
@@ -50,11 +55,12 @@ class WatchProgressServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
progressMapper = mock(WatchProgressMapper.class);
|
||||
historyMapper = mock(WatchHistoryMapper.class);
|
||||
dramaService = mock(DramaService.class);
|
||||
episodeService = mock(EpisodeService.class);
|
||||
progressService = new WatchProgressService(
|
||||
progressMapper,
|
||||
mock(WatchHistoryMapper.class),
|
||||
historyMapper,
|
||||
dramaService,
|
||||
episodeService);
|
||||
}
|
||||
@@ -120,7 +126,7 @@ class WatchProgressServiceTest {
|
||||
hidden.setId(9L);
|
||||
hidden.setUserId(7L);
|
||||
hidden.setDeleted(1);
|
||||
given(progressMapper.selectAny(7L, 5L)).willReturn(hidden);
|
||||
given(progressMapper.selectAnyForIdentity(7L, "", 5L)).willReturn(hidden);
|
||||
given(progressMapper.selectById(9L)).willReturn(hidden);
|
||||
ProgressSaveReqVO req = new ProgressSaveReqVO();
|
||||
req.setEpisodeId(88L);
|
||||
@@ -134,6 +140,185 @@ class WatchProgressServiceTest {
|
||||
assertThat(hidden.getDeleted()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_save_and_read_anonymous_progress_by_device() {
|
||||
DramaEpisode episode = episode(88L, 1);
|
||||
episode.setDramaId(5L);
|
||||
given(episodeService.getPublished(88L)).willReturn(episode);
|
||||
given(dramaService.getPublished(5L)).willReturn(drama(5L, "剧名", 10));
|
||||
given(progressMapper.selectAnyForIdentity(null, "device-a", 5L))
|
||||
.willReturn(null);
|
||||
given(progressMapper.insert(any(WatchProgress.class))).willAnswer(invocation -> {
|
||||
WatchProgress saved = invocation.getArgument(0);
|
||||
saved.setId(99L);
|
||||
return 1;
|
||||
});
|
||||
given(progressMapper.selectById(99L)).willAnswer(invocation -> {
|
||||
WatchProgress saved = new WatchProgress();
|
||||
saved.setId(99L);
|
||||
saved.setDramaId(5L);
|
||||
saved.setEpisodeId(88L);
|
||||
saved.setPositionMs(12_000L);
|
||||
saved.setDurationMs(60_000L);
|
||||
saved.setPlayCount(1);
|
||||
saved.setDeviceId("device-a");
|
||||
return saved;
|
||||
});
|
||||
ProgressSaveReqVO req = new ProgressSaveReqVO();
|
||||
req.setEpisodeId(88L);
|
||||
req.setPositionMs(12_000L);
|
||||
req.setDurationMs(60_000L);
|
||||
|
||||
progressService.save(new InteractionIdentity(null, "device-a"), req);
|
||||
|
||||
ArgumentCaptor<WatchProgress> progressCaptor =
|
||||
ArgumentCaptor.forClass(WatchProgress.class);
|
||||
verify(progressMapper).insert(progressCaptor.capture());
|
||||
assertThat(progressCaptor.getValue().getUserId()).isNull();
|
||||
assertThat(progressCaptor.getValue().getDeviceId()).isEqualTo("device-a");
|
||||
ArgumentCaptor<WatchHistory> historyCaptor =
|
||||
ArgumentCaptor.forClass(WatchHistory.class);
|
||||
verify(historyMapper).insert(historyCaptor.capture());
|
||||
assertThat(historyCaptor.getValue().getUserId()).isNull();
|
||||
assertThat(historyCaptor.getValue().getDeviceId()).isEqualTo("device-a");
|
||||
|
||||
WatchProgress saved = progressCaptor.getValue();
|
||||
saved.setUpdatedAt(LocalDateTime.of(2026, 10, 27, 9, 0));
|
||||
Page<WatchProgress> databasePage = new Page<>(1, 20, 1);
|
||||
databasePage.setRecords(List.of(saved));
|
||||
given(progressMapper.selectPage(any(Page.class), any())).willReturn(databasePage);
|
||||
given(dramaService.listByIds(List.of(5L)))
|
||||
.willReturn(List.of(drama(5L, "匿名观看", 10)));
|
||||
given(episodeService.listByIds(List.of(88L)))
|
||||
.willReturn(List.of(episode));
|
||||
|
||||
PageResult<ProgressRespVO> recent = progressService.recentPage(
|
||||
new InteractionIdentity(null, "device-a"), 1, 20);
|
||||
|
||||
assertThat(recent.getList()).hasSize(1);
|
||||
assertThat(recent.getList().get(0).getEpisodeId()).isEqualTo(88L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_read_anonymous_progress_by_device() {
|
||||
WatchProgress progress = progress(5L, 88L);
|
||||
progress.setUserId(null);
|
||||
progress.setDeviceId("device-a");
|
||||
given(progressMapper.selectOne(any())).willReturn(progress);
|
||||
|
||||
ProgressRespVO result = progressService.ofDrama(
|
||||
new InteractionIdentity(null, "device-a"), 5L);
|
||||
|
||||
assertThat(result.getEpisodeId()).isEqualTo(88L);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Wrapper<WatchProgress>> wrapperCaptor =
|
||||
ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(progressMapper).selectOne(wrapperCaptor.capture());
|
||||
assertThat(wrapperCaptor.getValue().getSqlSegment())
|
||||
.contains("user_id IS NULL")
|
||||
.contains("device_id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_read_logged_user_progress() {
|
||||
WatchProgress progress = progress(5L, 88L);
|
||||
progress.setUserId(9L);
|
||||
given(progressMapper.selectOne(any())).willReturn(progress);
|
||||
|
||||
ProgressRespVO result = progressService.ofDrama(
|
||||
new InteractionIdentity(9L, ""), 5L);
|
||||
|
||||
assertThat(result.getEpisodeId()).isEqualTo(88L);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Wrapper<WatchProgress>> wrapperCaptor =
|
||||
ArgumentCaptor.forClass(Wrapper.class);
|
||||
verify(progressMapper).selectOne(wrapperCaptor.capture());
|
||||
assertThat(wrapperCaptor.getValue().getSqlSegment())
|
||||
.contains("user_id")
|
||||
.doesNotContain("user_id IS NULL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_declare_jdbc_type_for_nullable_identity_sql() throws Exception {
|
||||
Method method = WatchProgressMapper.class.getMethod(
|
||||
"selectAnyForIdentity", Long.class, String.class, Long.class);
|
||||
Select select = method.getAnnotation(Select.class);
|
||||
String sql = String.join("\n", select.value());
|
||||
|
||||
assertThat(sql)
|
||||
.contains("#{userId,jdbcType=BIGINT} IS NOT NULL")
|
||||
.contains("#{userId,jdbcType=BIGINT} IS NULL")
|
||||
.doesNotContain("#{userId} ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_merge_watch_data_and_keep_more_advanced_progress() {
|
||||
DramaEpisode episode = episode(88L, 2);
|
||||
episode.setDramaId(5L);
|
||||
given(episodeService.listByIds(List.of(88L))).willReturn(List.of(episode));
|
||||
|
||||
WatchProgress deviceProgress = progress(5L, 88L);
|
||||
deviceProgress.setId(1L);
|
||||
deviceProgress.setPositionMs(90_000L);
|
||||
deviceProgress.setPlayCount(3);
|
||||
given(progressMapper.selectList(any())).willReturn(List.of(deviceProgress));
|
||||
WatchProgress accountProgress = progress(5L, 88L);
|
||||
accountProgress.setId(2L);
|
||||
accountProgress.setUserId(9L);
|
||||
accountProgress.setPositionMs(60_000L);
|
||||
accountProgress.setPlayCount(2);
|
||||
given(progressMapper.selectAnyForIdentity(9L, "", 5L))
|
||||
.willReturn(accountProgress);
|
||||
|
||||
WatchHistory deviceHistory = history(5L, 88L, 90_000L);
|
||||
deviceHistory.setId(3L);
|
||||
given(historyMapper.selectList(any())).willReturn(List.of(deviceHistory));
|
||||
WatchHistory accountHistory = history(5L, 88L, 60_000L);
|
||||
accountHistory.setId(4L);
|
||||
accountHistory.setUserId(9L);
|
||||
given(historyMapper.selectOne(any())).willReturn(accountHistory);
|
||||
|
||||
WatchProgressService.MergeResult result =
|
||||
progressService.mergeDeviceIntoUser(9L, "device-a");
|
||||
|
||||
assertThat(result.progressMigrated()).isEqualTo(1);
|
||||
assertThat(result.progressIgnored()).isZero();
|
||||
assertThat(result.historyMigrated()).isEqualTo(1);
|
||||
assertThat(result.historyIgnored()).isZero();
|
||||
assertThat(accountProgress.getPositionMs()).isEqualTo(90_000L);
|
||||
assertThat(accountProgress.getPlayCount()).isEqualTo(3);
|
||||
verify(progressMapper).updateAny(accountProgress);
|
||||
verify(progressMapper).deleteById(1L);
|
||||
verify(historyMapper).updateById(accountHistory);
|
||||
verify(historyMapper).deleteById(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void should_ignore_device_progress_when_account_progress_is_ahead() {
|
||||
DramaEpisode episode = episode(88L, 2);
|
||||
episode.setDramaId(5L);
|
||||
given(episodeService.listByIds(List.of(88L))).willReturn(List.of(episode));
|
||||
|
||||
WatchProgress deviceProgress = progress(5L, 88L);
|
||||
deviceProgress.setId(1L);
|
||||
deviceProgress.setPositionMs(50_000L);
|
||||
given(progressMapper.selectList(any())).willReturn(List.of(deviceProgress));
|
||||
WatchProgress accountProgress = progress(5L, 88L);
|
||||
accountProgress.setId(2L);
|
||||
accountProgress.setUserId(9L);
|
||||
accountProgress.setPositionMs(70_000L);
|
||||
given(progressMapper.selectAnyForIdentity(9L, "", 5L))
|
||||
.willReturn(accountProgress);
|
||||
|
||||
WatchProgressService.MergeResult result =
|
||||
progressService.mergeDeviceIntoUser(9L, "device-a");
|
||||
|
||||
assertThat(result.progressMigrated()).isZero();
|
||||
assertThat(result.progressIgnored()).isEqualTo(1);
|
||||
verify(progressMapper, never()).updateAny(any(WatchProgress.class));
|
||||
verify(progressMapper).deleteById(1L);
|
||||
}
|
||||
|
||||
private Drama drama(Long id, String title, int totalEpisodes) {
|
||||
Drama drama = new Drama();
|
||||
drama.setId(id);
|
||||
@@ -149,4 +334,15 @@ class WatchProgressServiceTest {
|
||||
episode.setEpNo(epNo);
|
||||
return episode;
|
||||
}
|
||||
|
||||
private WatchHistory history(Long dramaId, Long episodeId, long positionMs) {
|
||||
WatchHistory history = new WatchHistory();
|
||||
history.setDramaId(dramaId);
|
||||
history.setEpisodeId(episodeId);
|
||||
history.setPositionMs(positionMs);
|
||||
history.setDurationMs(120_000L);
|
||||
history.setDeviceId("device-a");
|
||||
history.setWatchedAt(LocalDateTime.of(2026, 10, 27, 9, 0));
|
||||
return history;
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,9 @@ public enum ErrorCode {
|
||||
*/
|
||||
CREATOR_NOT_BOUND(200004, "当前账号未绑定创作者主体"),
|
||||
CREATOR_TARGET_REQUIRED(200005, "请先选择要代看的创作者"),
|
||||
CREATOR_IMPERSONATE_READONLY(200006, "代看模式下只读,不能修改创作者数据");
|
||||
CREATOR_IMPERSONATE_READONLY(200006, "代看模式下只读,不能修改创作者数据"),
|
||||
|
||||
INTERACTION_IDENTITY_REQUIRED(200007, "缺少登录身份或设备标识,请重新登录");
|
||||
|
||||
private final int code;
|
||||
private final String message;
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.common.interaction;
|
||||
|
||||
/** 非付费互动的归属身份:登录用户优先,否则使用稳定设备号。 */
|
||||
public record InteractionIdentity(Long userId, String deviceId) {
|
||||
|
||||
public boolean authenticated() {
|
||||
return userId != null;
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.framework.interaction;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 点赞、收藏、评论共用的身份解析入口。 */
|
||||
@Component
|
||||
public class InteractionIdentityResolver {
|
||||
|
||||
public InteractionIdentity resolve(Long userId, String headerDeviceId, String bodyDeviceId) {
|
||||
if (userId != null) {
|
||||
return new InteractionIdentity(userId, "");
|
||||
}
|
||||
String deviceId = normalize(headerDeviceId);
|
||||
if (deviceId.isEmpty()) {
|
||||
deviceId = normalize(bodyDeviceId);
|
||||
}
|
||||
if (deviceId.isEmpty()) {
|
||||
throw new ServiceException(
|
||||
ErrorCode.INTERACTION_IDENTITY_REQUIRED,
|
||||
ErrorCode.INTERACTION_IDENTITY_REQUIRED.getMessage());
|
||||
}
|
||||
return new InteractionIdentity(null, deviceId);
|
||||
}
|
||||
|
||||
private String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -22,6 +22,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
public class AccessDeniedRecorder {
|
||||
|
||||
private final ObjectProvider<OperationLogSink> sinkProvider;
|
||||
private final ObjectProvider<WebUtils> webUtilsProvider;
|
||||
|
||||
public void record(HttpServletRequest request) {
|
||||
OperationLogSink sink = sinkProvider.getIfAvailable();
|
||||
@@ -47,10 +48,16 @@ public class AccessDeniedRecorder {
|
||||
.status("FAIL")
|
||||
.errorMsg("无权限")
|
||||
.durationMs(0)
|
||||
.ip(request == null ? "" : WebUtils.getClientIp(request))
|
||||
.ip(request == null ? "" : clientIp(request))
|
||||
.build());
|
||||
}
|
||||
|
||||
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
|
||||
private String clientIp(HttpServletRequest request) {
|
||||
WebUtils webUtils = webUtilsProvider.getIfAvailable();
|
||||
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
|
||||
}
|
||||
|
||||
/** 从当前线程取出请求,供全局异常处理使用。 */
|
||||
public void recordCurrentRequest() {
|
||||
if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
|
||||
|
||||
+8
-1
@@ -43,6 +43,7 @@ public class OperationLogAspect {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ObjectProvider<OperationLogSink> sinkProvider;
|
||||
private final ObjectProvider<WebUtils> webUtilsProvider;
|
||||
|
||||
@Around("@annotation(operationLog)")
|
||||
public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
|
||||
@@ -86,10 +87,16 @@ public class OperationLogAspect {
|
||||
.status(error == null ? "SUCCESS" : "FAIL")
|
||||
.errorMsg(error == null ? "" : truncate(error.getMessage()))
|
||||
.durationMs(durationMs)
|
||||
.ip(request == null ? "" : WebUtils.getClientIp(request))
|
||||
.ip(request == null ? "" : clientIp(request))
|
||||
.build());
|
||||
}
|
||||
|
||||
/** 优先用 Spring 注入的 WebUtils(尊重可信代理配置),拿不到回退静态方法。 */
|
||||
private String clientIp(HttpServletRequest request) {
|
||||
WebUtils webUtils = webUtilsProvider.getIfAvailable();
|
||||
return webUtils != null ? webUtils.clientIp(request) : WebUtils.getClientIp(request);
|
||||
}
|
||||
|
||||
/** 把方法入参整理成 JSON,文件只记名称和大小。 */
|
||||
private String body(ProceedingJoinPoint point) {
|
||||
Object[] args = point.getArgs();
|
||||
|
||||
+2
@@ -62,6 +62,8 @@ public final class ImpersonationGuard {
|
||||
|
||||
public static String clientIp() {
|
||||
HttpServletRequest request = currentRequest();
|
||||
// 这里走静态 getClientIp——等价于 trusted-proxies 为空时的逻辑(只用 remoteAddr,不解析 XFF)。
|
||||
// 这个类是纯静态工具(无 Spring 注入),且只在 Creator 代看场景用,安全影响低。
|
||||
return request == null ? "" : com.fruitshorts.framework.web.WebUtils.getClientIp(request);
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -45,6 +45,7 @@ public class SecurityConfig {
|
||||
"/app/dramas/**",
|
||||
"/app/search",
|
||||
"/app/episodes/*/play",
|
||||
"/app/episodes/*/stats",
|
||||
"/app/config/**",
|
||||
/* 启动配置与公告:客户端登录前就要拿(POST /app/creator/apply 等仍要登录) */
|
||||
"/app/config",
|
||||
@@ -80,9 +81,21 @@ public class SecurityConfig {
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(registry -> registry
|
||||
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
|
||||
/* 评论列表允许匿名浏览;发布/删除仍需登录(未列入白名单即需鉴权) */
|
||||
/* 非付费互动允许设备身份;解锁、钱包与权益接口仍只允许登录用户。 */
|
||||
.requestMatchers(HttpMethod.POST, "/app/likes/toggle").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/app/favorites/toggle").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/app/favorites/remove").permitAll()
|
||||
.requestMatchers(HttpMethod.DELETE, "/app/favorites/*").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/app/comments").permitAll()
|
||||
.requestMatchers(HttpMethod.DELETE, "/app/comments/*").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/app/comments").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/app/comments/count").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/app/favorites").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/app/watch/recent").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/app/watch/progress").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/app/watch/progress").permitAll()
|
||||
.requestMatchers(HttpMethod.DELETE, "/app/watch/progress/*").permitAll()
|
||||
.requestMatchers(HttpMethod.DELETE, "/app/watch/progress").permitAll()
|
||||
.requestMatchers(PUBLIC_PATHS).permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(handling -> handling
|
||||
|
||||
@@ -3,25 +3,146 @@
|
||||
package com.fruitshorts.framework.web;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
public final class WebUtils {
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 取真实客户端 IP。
|
||||
*
|
||||
* <p>安全策略:默认信任 {@link HttpServletRequest#getRemoteAddr()} 本身,只有当
|
||||
* 它属于配置的可信代理 CIDR 时才解析 X-Forwarded-For / X-Real-IP 等头。
|
||||
* 这样客户端伪造的 XFF 不会生效,只有经 Nginx / K8s ingress 等前置代理转发的请求
|
||||
* 才能带上可信的 XFF 链。
|
||||
*
|
||||
* <p>生产建议:同时开启 Tomcat RemoteIpValve(prod profile 已配置),让
|
||||
* {@code getRemoteAddr()} 在经过代理后直接就是客户端真实 IP。此时可信代理列表
|
||||
* 配成空即可,Valve 已经帮我们做了 XFF 解析。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class WebUtils {
|
||||
|
||||
private static final String UNKNOWN = "unknown";
|
||||
private static final String[] PROXY_HEADERS = {"X-Forwarded-For", "X-Real-IP",
|
||||
"Proxy-Client-IP", "WL-Proxy-Client-IP"};
|
||||
|
||||
private WebUtils() {
|
||||
/** 可信代理 CIDR 列表,逗号分隔;空表示永不解析 XFF,直接用 remoteAddr。 */
|
||||
@Value("${fruitshorts.web.trusted-proxies:}")
|
||||
private String trustedProxies = "";
|
||||
|
||||
/** 纯静态调用路径(不依赖 Spring),供测试或无 IoC 场景使用。 */
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
return resolve(request, List.of());
|
||||
}
|
||||
|
||||
/** 取真实客户端 IP,兼容 Nginx 反向代理。 */
|
||||
public static String getClientIp(HttpServletRequest request) {
|
||||
String[] headers = {"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"};
|
||||
for (String header : headers) {
|
||||
String value = request.getHeader(header);
|
||||
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
|
||||
int comma = value.indexOf(',');
|
||||
return comma > 0 ? value.substring(0, comma).trim() : value.trim();
|
||||
/** Spring 注入版:自动按配置解析 XFF。 */
|
||||
public String clientIp(HttpServletRequest request) {
|
||||
List<String> cidrs = StringUtils.hasText(trustedProxies)
|
||||
? Arrays.asList(trustedProxies.split(","))
|
||||
: List.of();
|
||||
return resolve(request, cidrs);
|
||||
}
|
||||
|
||||
private static String resolve(HttpServletRequest request, List<String> trustedCidrs) {
|
||||
String remoteAddr = request.getRemoteAddr();
|
||||
if (isTrustedProxy(remoteAddr, trustedCidrs)) {
|
||||
String fromHeader = readProxyHeader(request);
|
||||
if (StringUtils.hasText(fromHeader)) {
|
||||
return fromHeader;
|
||||
}
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
return remoteAddr;
|
||||
}
|
||||
|
||||
private static String readProxyHeader(HttpServletRequest request) {
|
||||
for (String header : PROXY_HEADERS) {
|
||||
String value = request.getHeader(header);
|
||||
if (StringUtils.hasText(value) && !UNKNOWN.equalsIgnoreCase(value)) {
|
||||
// XFF 链格式:client, proxy1, proxy2 —— 最左侧是原始客户端 IP
|
||||
String[] parts = value.split(",");
|
||||
return parts[0].trim();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 remoteAddr 是否属于可信代理。
|
||||
*
|
||||
* <p>CIDR 简化实现:只支持单个 IP 或 "/24" 这类前缀掩码,不支持复杂区间。
|
||||
* 生产反代一般就是 127.0.0.1、10.0.0.0/8 这类,够用。
|
||||
*/
|
||||
static boolean isTrustedProxy(String remoteAddr, List<String> trustedCidrs) {
|
||||
if (!StringUtils.hasText(remoteAddr) || trustedCidrs.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
InetAddress remote = InetAddress.getByName(remoteAddr.trim());
|
||||
for (String cidr : trustedCidrs) {
|
||||
if (cidrMatches(remote, cidr.trim())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (UnknownHostException ex) {
|
||||
log.debug("无法解析 remoteAddr {} 为 IP,跳过 XFF 信任判定", remoteAddr);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean cidrMatches(InetAddress target, String cidr) {
|
||||
if (!cidr.contains("/")) {
|
||||
// 单 IP 精确匹配
|
||||
InetAddress trusted;
|
||||
try {
|
||||
trusted = InetAddress.getByName(cidr);
|
||||
} catch (UnknownHostException ex) {
|
||||
return false;
|
||||
}
|
||||
return trusted.equals(target);
|
||||
}
|
||||
String[] parts = cidr.split("/", 2);
|
||||
String netPart = parts[0];
|
||||
int prefixLen;
|
||||
try {
|
||||
prefixLen = Integer.parseInt(parts[1]);
|
||||
} catch (NumberFormatException ex) {
|
||||
return false;
|
||||
}
|
||||
InetAddress net;
|
||||
try {
|
||||
net = InetAddress.getByName(netPart);
|
||||
} catch (UnknownHostException ex) {
|
||||
return false;
|
||||
}
|
||||
byte[] targetBytes = target.getAddress();
|
||||
byte[] netBytes = net.getAddress();
|
||||
if (targetBytes.length != netBytes.length) {
|
||||
return false;
|
||||
}
|
||||
int fullBytes = prefixLen / 8;
|
||||
int remainingBits = prefixLen % 8;
|
||||
for (int i = 0; i < fullBytes; i++) {
|
||||
if (targetBytes[i] != netBytes[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (remainingBits > 0 && fullBytes < targetBytes.length) {
|
||||
int mask = (0xFF << (8 - remainingBits)) & 0xFF;
|
||||
if ((targetBytes[fullBytes] & mask) != (netBytes[fullBytes] & mask)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Spring 直接实例化;保留 package-private 方便单测 new。 */
|
||||
WebUtils() {
|
||||
}
|
||||
}
|
||||
+14
@@ -158,6 +158,20 @@ public class EpisodeService implements EpisodeTranscodeCompletionPort, EpisodeVi
|
||||
Wrappers.<DramaEpisode>lambdaQuery().in(DramaEpisode::getId, ids));
|
||||
}
|
||||
|
||||
/** C 端:按 ID 批量取已上线剧集,用于只读统计。 */
|
||||
public List<DramaEpisode> listPublishedByIds(Collection<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> normalized = ids.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (normalized.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return dramaEpisodeMapper.selectList(Wrappers.<DramaEpisode>lambdaQuery()
|
||||
.in(DramaEpisode::getId, normalized)
|
||||
.eq(DramaEpisode::getStatus, ContentStatus.PUBLISHED.getCode()));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long create(EpisodeSaveReqVO req) {
|
||||
dramaService.getExisting(req.getDramaId());
|
||||
|
||||
+1
@@ -18,6 +18,7 @@ public class ContentLike {
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String deviceId;
|
||||
/** DRAMA/EPISODE/COMMENT */
|
||||
private String targetType;
|
||||
private Long targetId;
|
||||
|
||||
+4
@@ -4,6 +4,7 @@ package com.fruitshorts.interaction.dal.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.fruitshorts.interaction.dal.entity.ContentComment;
|
||||
import org.apache.ibatis.annotations.Delete;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
@@ -12,6 +13,9 @@ import java.util.List;
|
||||
|
||||
public interface ContentCommentMapper extends BaseMapper<ContentComment> {
|
||||
|
||||
@Delete("DELETE FROM content_comment WHERE id = #{id}")
|
||||
int physicalDeleteById(@Param("id") Long id);
|
||||
|
||||
/**
|
||||
* 后台举报工单按评论 id 批量读取,包含逻辑删除记录。
|
||||
*
|
||||
|
||||
+9
@@ -20,4 +20,13 @@ public interface ContentLikeMapper extends BaseMapper<ContentLike> {
|
||||
+ "AND target_id = #{targetId}")
|
||||
int physicalDelete(@Param("userId") Long userId, @Param("targetType") String targetType,
|
||||
@Param("targetId") Long targetId);
|
||||
|
||||
@Delete("DELETE FROM content_like WHERE user_id IS NULL AND device_id = #{deviceId} "
|
||||
+ "AND target_type = #{targetType} AND target_id = #{targetId}")
|
||||
int physicalDeleteDevice(@Param("deviceId") String deviceId,
|
||||
@Param("targetType") String targetType,
|
||||
@Param("targetId") Long targetId);
|
||||
|
||||
@Delete("DELETE FROM content_like WHERE id = #{id}")
|
||||
int physicalDeleteById(@Param("id") Long id);
|
||||
}
|
||||
+158
-23
@@ -9,6 +9,7 @@ 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.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.common.pojo.CursorResult;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
@@ -78,6 +79,11 @@ public class CommentService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CommentRespVO publish(Long userId, CommentPublishReqVO req, String ip, String deviceId) {
|
||||
return publish(new InteractionIdentity(userId, deviceId), req, ip);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CommentRespVO publish(InteractionIdentity identity, CommentPublishReqVO req, String ip) {
|
||||
dramaService.getPublished(req.getDramaId());
|
||||
if (req.getEpisodeId() != null) {
|
||||
episodeService.getPublished(req.getEpisodeId());
|
||||
@@ -90,7 +96,8 @@ public class CommentService {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST,
|
||||
"评论最多 " + properties.getCommentMaxLength() + " 字");
|
||||
}
|
||||
checkRate(userId);
|
||||
checkRate(identity);
|
||||
checkDuplicate(identity, req, text);
|
||||
|
||||
SensitiveWordCheck check = sensitiveWordService.check(text);
|
||||
if (check.blocked()) {
|
||||
@@ -110,7 +117,7 @@ public class CommentService {
|
||||
ContentComment comment = new ContentComment();
|
||||
comment.setDramaId(req.getDramaId());
|
||||
comment.setEpisodeId(req.getEpisodeId() == null ? 0L : req.getEpisodeId());
|
||||
comment.setUserId(userId);
|
||||
comment.setUserId(identity.userId());
|
||||
comment.setParentId(parent == null ? 0L : parent.getId());
|
||||
comment.setRootId(resolveRootId(parent));
|
||||
comment.setContent(check.sanitized());
|
||||
@@ -121,7 +128,7 @@ public class CommentService {
|
||||
comment.setReplyCount(0);
|
||||
comment.setReportCount(0);
|
||||
comment.setIp(ip == null ? "" : ip);
|
||||
comment.setDeviceId(deviceId == null ? "" : deviceId);
|
||||
comment.setDeviceId(identity.authenticated() ? "" : identity.deviceId());
|
||||
comment.setCountryCode("");
|
||||
commentMapper.insert(comment);
|
||||
|
||||
@@ -134,13 +141,22 @@ public class CommentService {
|
||||
.eq(ContentComment::getId, parent.getId())
|
||||
.setSql("reply_count = reply_count + 1"));
|
||||
}
|
||||
return toResp(comment, appUserMapper.selectById(userId), false, userId);
|
||||
return toResp(
|
||||
comment,
|
||||
identity.authenticated() ? appUserMapper.selectById(identity.userId()) : null,
|
||||
false,
|
||||
identity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 游标翻页。unsetRootId 表示只看顶层评论;传 rootId 则看该楼层的回复。
|
||||
*/
|
||||
public CursorResult<CommentRespVO> page(Long meUserId, CommentQueryReqVO req) {
|
||||
return page(meUserId, "", req);
|
||||
}
|
||||
|
||||
public CursorResult<CommentRespVO> page(
|
||||
Long meUserId, String meDeviceId, CommentQueryReqVO req) {
|
||||
if (req.getDramaId() == null) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST, "缺少 dramaId");
|
||||
}
|
||||
@@ -151,8 +167,13 @@ public class CommentService {
|
||||
.eq(req.getEpisodeId() != null, ContentComment::getEpisodeId, req.getEpisodeId())
|
||||
.eq(ContentComment::getRootId, rootFilter)
|
||||
.lt(req.getCursor() != null, ContentComment::getId, req.getCursor());
|
||||
if (meUserId == null) {
|
||||
if (meUserId == null && (meDeviceId == null || meDeviceId.isBlank())) {
|
||||
wrapper.eq(ContentComment::getStatus, STATUS_PUBLISHED);
|
||||
} else if (meUserId == null) {
|
||||
wrapper.and(w -> w.eq(ContentComment::getStatus, STATUS_PUBLISHED)
|
||||
.or(x -> x.eq(ContentComment::getStatus, STATUS_PENDING)
|
||||
.isNull(ContentComment::getUserId)
|
||||
.eq(ContentComment::getDeviceId, meDeviceId)));
|
||||
} else {
|
||||
// 已发布 + 自己待审核的
|
||||
wrapper.and(w -> w.eq(ContentComment::getStatus, STATUS_PUBLISHED)
|
||||
@@ -166,13 +187,25 @@ public class CommentService {
|
||||
rows = rows.subList(0, size);
|
||||
}
|
||||
Long nextCursor = rows.isEmpty() ? null : rows.get(rows.size() - 1).getId();
|
||||
return new CursorResult<>(toRespList(rows, meUserId), hasMore ? nextCursor : null, hasMore);
|
||||
return new CursorResult<>(
|
||||
toRespList(rows, new InteractionIdentity(meUserId, meDeviceId)),
|
||||
hasMore ? nextCursor : null,
|
||||
hasMore);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delete(Long userId, Long commentId) {
|
||||
delete(new InteractionIdentity(userId, ""), commentId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delete(InteractionIdentity identity, Long commentId) {
|
||||
ContentComment comment = getExisting(commentId);
|
||||
if (!comment.getUserId().equals(userId)) {
|
||||
boolean mine = identity.authenticated()
|
||||
? identity.userId().equals(comment.getUserId())
|
||||
: comment.getUserId() == null
|
||||
&& identity.deviceId().equals(comment.getDeviceId());
|
||||
if (!mine) {
|
||||
throw new ServiceException(ErrorCode.FORBIDDEN, "只能删除自己的评论");
|
||||
}
|
||||
softDelete(comment);
|
||||
@@ -278,7 +311,7 @@ public class CommentService {
|
||||
req.getKeyword())
|
||||
.orderByDesc(ContentComment::getId));
|
||||
List<ContentComment> rows = result.getRecords();
|
||||
List<CommentRespVO> list = toRespList(rows, null);
|
||||
List<CommentRespVO> list = toRespList(rows, new InteractionIdentity(null, ""));
|
||||
fillAdminContentInfo(rows, list);
|
||||
return new PageResult<>(result.getTotal(), list);
|
||||
}
|
||||
@@ -349,15 +382,87 @@ public class CommentService {
|
||||
commentMapper.updateById(comment);
|
||||
}
|
||||
|
||||
private void checkRate(Long userId) {
|
||||
Long recent = commentMapper.selectCount(Wrappers.<ContentComment>lambdaQuery()
|
||||
.eq(ContentComment::getUserId, userId)
|
||||
.ge(ContentComment::getCreatedAt, LocalDateTime.now().minusMinutes(1)));
|
||||
private void checkRate(InteractionIdentity identity) {
|
||||
var query = Wrappers.<ContentComment>lambdaQuery()
|
||||
.ge(ContentComment::getCreatedAt, LocalDateTime.now().minusMinutes(1));
|
||||
if (identity.authenticated()) {
|
||||
query.eq(ContentComment::getUserId, identity.userId());
|
||||
} else {
|
||||
query.isNull(ContentComment::getUserId)
|
||||
.eq(ContentComment::getDeviceId, identity.deviceId());
|
||||
}
|
||||
Long recent = commentMapper.selectCount(query);
|
||||
if (recent != null && recent >= properties.getCommentPerMinute()) {
|
||||
throw new ServiceException(ErrorCode.TOO_MANY_REQUESTS, "发言过于频繁,请稍后再试");
|
||||
}
|
||||
}
|
||||
|
||||
private void checkDuplicate(
|
||||
InteractionIdentity identity, CommentPublishReqVO req, String text) {
|
||||
var query = Wrappers.<ContentComment>lambdaQuery()
|
||||
.eq(ContentComment::getDramaId, req.getDramaId())
|
||||
.eq(ContentComment::getEpisodeId,
|
||||
req.getEpisodeId() == null ? 0L : req.getEpisodeId())
|
||||
.eq(ContentComment::getParentId,
|
||||
req.getParentId() == null ? 0L : req.getParentId())
|
||||
.eq(ContentComment::getContent, text)
|
||||
.ne(ContentComment::getStatus, STATUS_DELETED)
|
||||
.ge(ContentComment::getCreatedAt, LocalDateTime.now().minusMinutes(1));
|
||||
if (identity.authenticated()) {
|
||||
query.eq(ContentComment::getUserId, identity.userId());
|
||||
} else {
|
||||
query.isNull(ContentComment::getUserId)
|
||||
.eq(ContentComment::getDeviceId, identity.deviceId());
|
||||
}
|
||||
Long count = commentMapper.selectCount(query);
|
||||
if (count != null && count > 0) {
|
||||
throw new ServiceException(ErrorCode.DATA_EXISTS, "请勿重复发送相同评论");
|
||||
}
|
||||
}
|
||||
|
||||
/** 登录时把设备评论归并到账号;重复内容删除设备侧记录。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public MergeResult mergeDeviceIntoUser(Long userId, String deviceId) {
|
||||
if (userId == null || !StringUtils.hasText(deviceId)) {
|
||||
return new MergeResult(0, 0);
|
||||
}
|
||||
List<ContentComment> deviceComments = commentMapper.selectList(
|
||||
Wrappers.<ContentComment>lambdaQuery()
|
||||
.isNull(ContentComment::getUserId)
|
||||
.eq(ContentComment::getDeviceId, deviceId));
|
||||
int migrated = 0;
|
||||
int duplicates = 0;
|
||||
for (ContentComment deviceComment : deviceComments) {
|
||||
ContentComment existing = commentMapper.selectOne(
|
||||
Wrappers.<ContentComment>lambdaQuery()
|
||||
.eq(ContentComment::getUserId, userId)
|
||||
.eq(ContentComment::getDramaId, deviceComment.getDramaId())
|
||||
.eq(ContentComment::getEpisodeId, deviceComment.getEpisodeId())
|
||||
.eq(ContentComment::getParentId, deviceComment.getParentId())
|
||||
.eq(ContentComment::getContent, deviceComment.getContent())
|
||||
.ne(ContentComment::getStatus, STATUS_DELETED)
|
||||
.last("limit 1"));
|
||||
if (existing != null) {
|
||||
if (commentMapper.physicalDeleteById(deviceComment.getId()) > 0
|
||||
&& deviceComment.getParentId() != null
|
||||
&& deviceComment.getParentId() > 0) {
|
||||
commentMapper.update(null, Wrappers.<ContentComment>lambdaUpdate()
|
||||
.eq(ContentComment::getId, deviceComment.getParentId())
|
||||
.setSql("reply_count = GREATEST(reply_count - 1, 0)"));
|
||||
}
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
deviceComment.setUserId(userId);
|
||||
commentMapper.updateById(deviceComment);
|
||||
migrated++;
|
||||
}
|
||||
return new MergeResult(migrated, duplicates);
|
||||
}
|
||||
|
||||
public record MergeResult(int migrated, int duplicates) {
|
||||
}
|
||||
|
||||
private Long resolveRootId(ContentComment parent) {
|
||||
if (parent == null) {
|
||||
return 0L;
|
||||
@@ -371,27 +476,45 @@ public class CommentService {
|
||||
return Math.min(value, properties.getPageMaxSize());
|
||||
}
|
||||
|
||||
private List<CommentRespVO> toRespList(List<ContentComment> rows, Long meUserId) {
|
||||
private List<CommentRespVO> toRespList(
|
||||
List<ContentComment> rows, InteractionIdentity identity) {
|
||||
if (rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
Map<Long, AppUser> users = new HashMap<>();
|
||||
List<Long> userIds = rows.stream().map(ContentComment::getUserId).distinct().toList();
|
||||
for (AppUser user : appUserMapper.selectBatchIds(userIds)) {
|
||||
users.put(user.getId(), user);
|
||||
List<Long> userIds = rows.stream()
|
||||
.map(ContentComment::getUserId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (!userIds.isEmpty()) {
|
||||
for (AppUser user : appUserMapper.selectBatchIds(userIds)) {
|
||||
users.put(user.getId(), user);
|
||||
}
|
||||
}
|
||||
Set<Long> likedIds = new HashSet<>();
|
||||
if (meUserId != null) {
|
||||
for (ContentLike like : likeMapper.selectList(Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(ContentLike::getUserId, meUserId)
|
||||
if (identity.userId() != null || StringUtils.hasText(identity.deviceId())) {
|
||||
var query = Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(ContentLike::getTargetType, "COMMENT")
|
||||
.in(ContentLike::getTargetId, rows.stream().map(ContentComment::getId).toList()))) {
|
||||
.in(ContentLike::getTargetId,
|
||||
rows.stream().map(ContentComment::getId).toList());
|
||||
if (identity.authenticated()) {
|
||||
query.eq(ContentLike::getUserId, identity.userId());
|
||||
} else {
|
||||
query.isNull(ContentLike::getUserId)
|
||||
.eq(ContentLike::getDeviceId, identity.deviceId());
|
||||
}
|
||||
for (ContentLike like : likeMapper.selectList(query)) {
|
||||
likedIds.add(like.getTargetId());
|
||||
}
|
||||
}
|
||||
List<CommentRespVO> list = new ArrayList<>(rows.size());
|
||||
for (ContentComment row : rows) {
|
||||
list.add(toResp(row, users.get(row.getUserId()), likedIds.contains(row.getId()), meUserId));
|
||||
list.add(toResp(
|
||||
row,
|
||||
users.get(row.getUserId()),
|
||||
likedIds.contains(row.getId()),
|
||||
identity));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
@@ -429,7 +552,11 @@ public class CommentService {
|
||||
}
|
||||
}
|
||||
|
||||
private CommentRespVO toResp(ContentComment comment, AppUser author, boolean liked, Long meUserId) {
|
||||
private CommentRespVO toResp(
|
||||
ContentComment comment,
|
||||
AppUser author,
|
||||
boolean liked,
|
||||
InteractionIdentity identity) {
|
||||
CommentRespVO vo = new CommentRespVO();
|
||||
vo.setId(comment.getId());
|
||||
vo.setDramaId(comment.getDramaId());
|
||||
@@ -444,12 +571,20 @@ public class CommentService {
|
||||
vo.setReplyCount(comment.getReplyCount());
|
||||
vo.setReportCount(comment.getReportCount());
|
||||
vo.setCreatedAt(comment.getCreatedAt());
|
||||
vo.setMine(meUserId != null && meUserId.equals(comment.getUserId()));
|
||||
boolean mine = identity.authenticated()
|
||||
? identity.userId().equals(comment.getUserId())
|
||||
: comment.getUserId() == null
|
||||
&& identity.deviceId().equals(comment.getDeviceId());
|
||||
vo.setMine(mine);
|
||||
vo.setLiked(liked);
|
||||
if (author != null) {
|
||||
vo.setUid(author.getUid());
|
||||
vo.setNickname(author.getNickname());
|
||||
vo.setAvatarUrl(author.getAvatarUrl());
|
||||
} else {
|
||||
vo.setUid("");
|
||||
vo.setNickname("游客");
|
||||
vo.setAvatarUrl("");
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
+95
-4
@@ -5,6 +5,7 @@ package com.fruitshorts.interaction.service;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
import com.fruitshorts.content.service.EpisodeService;
|
||||
@@ -18,7 +19,11 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 点赞。关系表是事实来源,计数同步更新在目标行上。
|
||||
@@ -41,6 +46,11 @@ public class LikeService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LikeToggleRespVO toggle(Long userId, LikeToggleReqVO req) {
|
||||
return toggle(new InteractionIdentity(userId, ""), req);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public LikeToggleRespVO toggle(InteractionIdentity identity, LikeToggleReqVO req) {
|
||||
String type = req.getTargetType().trim().toUpperCase(Locale.ROOT);
|
||||
if (!TYPE_DRAMA.equals(type) && !TYPE_EPISODE.equals(type) && !TYPE_COMMENT.equals(type)) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST, "只支持对短剧、剧集或评论点赞");
|
||||
@@ -48,22 +58,26 @@ public class LikeService {
|
||||
Long targetId = req.getTargetId();
|
||||
validateTarget(type, targetId);
|
||||
|
||||
ContentLike existing = likeMapper.selectOne(Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(ContentLike::getUserId, userId)
|
||||
ContentLike existing = likeMapper.selectOne(identityQuery(identity)
|
||||
.eq(ContentLike::getTargetType, type)
|
||||
.eq(ContentLike::getTargetId, targetId)
|
||||
.last("limit 1"));
|
||||
boolean liked;
|
||||
if (existing == null) {
|
||||
ContentLike like = new ContentLike();
|
||||
like.setUserId(userId);
|
||||
like.setUserId(identity.userId());
|
||||
like.setDeviceId(identity.authenticated() ? "" : identity.deviceId());
|
||||
like.setTargetType(type);
|
||||
like.setTargetId(targetId);
|
||||
likeMapper.insert(like);
|
||||
liked = true;
|
||||
adjustCount(type, targetId, 1);
|
||||
} else {
|
||||
likeMapper.physicalDelete(userId, type, targetId);
|
||||
if (identity.authenticated()) {
|
||||
likeMapper.physicalDelete(identity.userId(), type, targetId);
|
||||
} else {
|
||||
likeMapper.physicalDeleteDevice(identity.deviceId(), type, targetId);
|
||||
}
|
||||
liked = false;
|
||||
adjustCount(type, targetId, -1);
|
||||
}
|
||||
@@ -86,6 +100,83 @@ public class LikeService {
|
||||
return comment == null || comment.getLikeCount() == null ? 0L : comment.getLikeCount();
|
||||
}
|
||||
|
||||
/** 批量判断用户是否已点赞,一次查询覆盖多个目标。 */
|
||||
public Set<Long> likedTargetIds(Long userId, String type, Collection<Long> targetIds) {
|
||||
return likedTargetIds(userId, "", type, targetIds);
|
||||
}
|
||||
|
||||
/** 登录用户优先;匿名状态按设备号查询。 */
|
||||
public Set<Long> likedTargetIds(Long userId, String deviceId, String type,
|
||||
Collection<Long> targetIds) {
|
||||
if (targetIds == null || targetIds.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
Set<Long> normalized = new HashSet<>();
|
||||
for (Long targetId : targetIds) {
|
||||
if (targetId != null) {
|
||||
normalized.add(targetId);
|
||||
}
|
||||
}
|
||||
if (normalized.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
if (userId == null && (deviceId == null || deviceId.isBlank())) {
|
||||
return Set.of();
|
||||
}
|
||||
return likeMapper.selectList(identityQuery(new InteractionIdentity(userId, deviceId))
|
||||
.eq(ContentLike::getTargetType, type)
|
||||
.in(ContentLike::getTargetId, normalized))
|
||||
.stream()
|
||||
.map(ContentLike::getTargetId)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
}
|
||||
|
||||
/** 登录时把设备点赞归并到账号;重复关系删除并回退目标计数。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public MergeResult mergeDeviceIntoUser(Long userId, String deviceId) {
|
||||
if (userId == null || deviceId == null || deviceId.isBlank()) {
|
||||
return new MergeResult(0, 0);
|
||||
}
|
||||
List<ContentLike> deviceLikes = likeMapper.selectList(
|
||||
Wrappers.<ContentLike>lambdaQuery()
|
||||
.isNull(ContentLike::getUserId)
|
||||
.eq(ContentLike::getDeviceId, deviceId));
|
||||
int migrated = 0;
|
||||
int duplicates = 0;
|
||||
for (ContentLike deviceLike : deviceLikes) {
|
||||
ContentLike existing = likeMapper.selectOne(Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(ContentLike::getUserId, userId)
|
||||
.eq(ContentLike::getTargetType, deviceLike.getTargetType())
|
||||
.eq(ContentLike::getTargetId, deviceLike.getTargetId())
|
||||
.last("limit 1"));
|
||||
if (existing != null) {
|
||||
if (likeMapper.physicalDeleteById(deviceLike.getId()) > 0) {
|
||||
adjustCount(deviceLike.getTargetType(), deviceLike.getTargetId(), -1);
|
||||
}
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
deviceLike.setUserId(userId);
|
||||
likeMapper.updateById(deviceLike);
|
||||
migrated++;
|
||||
}
|
||||
return new MergeResult(migrated, duplicates);
|
||||
}
|
||||
|
||||
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ContentLike>
|
||||
identityQuery(InteractionIdentity identity) {
|
||||
if (identity.authenticated()) {
|
||||
return Wrappers.<ContentLike>lambdaQuery()
|
||||
.eq(ContentLike::getUserId, identity.userId());
|
||||
}
|
||||
return Wrappers.<ContentLike>lambdaQuery()
|
||||
.isNull(ContentLike::getUserId)
|
||||
.eq(ContentLike::getDeviceId, identity.deviceId());
|
||||
}
|
||||
|
||||
public record MergeResult(int migrated, int duplicates) {
|
||||
}
|
||||
|
||||
private void adjustCount(String type, Long targetId, int delta) {
|
||||
if (TYPE_DRAMA.equals(type)) {
|
||||
dramaService.adjustLikeCount(targetId, delta);
|
||||
|
||||
+3
@@ -20,4 +20,7 @@ public class CommentPublishReqVO {
|
||||
|
||||
/** 回复某条评论时传它的 id;顶层评论不传 */
|
||||
private Long parentId;
|
||||
|
||||
/** 兼容旧调用;正常客户端通过 X-Device-Id 下发。 */
|
||||
private String deviceId;
|
||||
}
|
||||
+3
@@ -16,4 +16,7 @@ public class LikeToggleReqVO {
|
||||
|
||||
@NotNull(message = "缺少 targetId")
|
||||
private Long targetId;
|
||||
|
||||
/** 兼容旧调用;正常客户端通过 X-Device-Id 下发。 */
|
||||
private String deviceId;
|
||||
}
|
||||
+1
@@ -20,6 +20,7 @@ public class UserFavorite {
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
private String deviceId;
|
||||
private Long dramaId;
|
||||
private Integer sort;
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
+7
@@ -17,4 +17,11 @@ public interface UserFavoriteMapper extends BaseMapper<UserFavorite> {
|
||||
*/
|
||||
@Delete("DELETE FROM user_favorite WHERE user_id = #{userId} AND drama_id = #{dramaId}")
|
||||
int physicalDelete(@Param("userId") Long userId, @Param("dramaId") Long dramaId);
|
||||
|
||||
@Delete("DELETE FROM user_favorite WHERE user_id IS NULL AND device_id = #{deviceId} "
|
||||
+ "AND drama_id = #{dramaId}")
|
||||
int physicalDeleteDevice(@Param("deviceId") String deviceId, @Param("dramaId") Long dramaId);
|
||||
|
||||
@Delete("DELETE FROM user_favorite WHERE id = #{id}")
|
||||
int physicalDeleteById(@Param("id") Long id);
|
||||
}
|
||||
+11
-3
@@ -10,13 +10,21 @@ import org.apache.ibatis.annotations.Update;
|
||||
|
||||
public interface WatchProgressMapper extends BaseMapper<WatchProgress> {
|
||||
|
||||
/** 含逻辑删除行。唯一索引不区分 deleted,再看同一部剧必须能找回旧行。 */
|
||||
/** 按登录用户或匿名设备读取同一部剧的记录,包含逻辑删除行。 */
|
||||
@Select("""
|
||||
SELECT * FROM watch_progress
|
||||
WHERE user_id = #{userId} AND drama_id = #{dramaId}
|
||||
WHERE (
|
||||
(#{userId,jdbcType=BIGINT} IS NOT NULL AND user_id = #{userId,jdbcType=BIGINT})
|
||||
OR
|
||||
(#{userId,jdbcType=BIGINT} IS NULL AND user_id IS NULL AND device_id = #{deviceId})
|
||||
)
|
||||
AND drama_id = #{dramaId}
|
||||
LIMIT 1
|
||||
""")
|
||||
WatchProgress selectAny(@Param("userId") Long userId, @Param("dramaId") Long dramaId);
|
||||
WatchProgress selectAnyForIdentity(
|
||||
@Param("userId") Long userId,
|
||||
@Param("deviceId") String deviceId,
|
||||
@Param("dramaId") Long dramaId);
|
||||
|
||||
/** 恢复并更新。手写 SQL 不带 deleted=0 条件,逻辑删除行也能写回。 */
|
||||
@Update("""
|
||||
|
||||
+130
-10
@@ -6,6 +6,7 @@ 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.pojo.PageResult;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.enums.ContentStatus;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
@@ -17,9 +18,12 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/** 收藏:切换、列表、批量删除;收藏数在同一事务内同步维护。 */
|
||||
@Service
|
||||
@@ -34,21 +38,28 @@ public class FavoriteService {
|
||||
/** 返回切换后的状态:true 表示已收藏。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean toggle(Long userId, Long dramaId) {
|
||||
return toggle(new InteractionIdentity(userId, ""), dramaId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean toggle(InteractionIdentity identity, Long dramaId) {
|
||||
dramaService.getPublished(dramaId);
|
||||
UserFavorite existing = favoriteMapper.selectOne(Wrappers.<UserFavorite>lambdaQuery()
|
||||
.eq(UserFavorite::getUserId, userId)
|
||||
UserFavorite existing = favoriteMapper.selectOne(identityQuery(identity)
|
||||
.eq(UserFavorite::getDramaId, dramaId)
|
||||
.last("limit 1"));
|
||||
if (existing != null) {
|
||||
// 必须物理删除:唯一索引 (user_id, drama_id) 会挡住"取消后再收藏"
|
||||
int removed = favoriteMapper.physicalDelete(userId, dramaId);
|
||||
int removed = identity.authenticated()
|
||||
? favoriteMapper.physicalDelete(identity.userId(), dramaId)
|
||||
: favoriteMapper.physicalDeleteDevice(identity.deviceId(), dramaId);
|
||||
if (removed > 0) {
|
||||
dramaService.adjustFavoriteCount(dramaId, -1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
UserFavorite favorite = new UserFavorite();
|
||||
favorite.setUserId(userId);
|
||||
favorite.setUserId(identity.userId());
|
||||
favorite.setDeviceId(identity.authenticated() ? "" : identity.deviceId());
|
||||
favorite.setDramaId(dramaId);
|
||||
favorite.setSort(0);
|
||||
favoriteMapper.insert(favorite);
|
||||
@@ -63,16 +74,97 @@ public class FavoriteService {
|
||||
return count != null && count > 0;
|
||||
}
|
||||
|
||||
/** 批量判断用户是否已收藏,一次查询覆盖多部剧。 */
|
||||
public Set<Long> favoriteDramaIds(Long userId, Collection<Long> dramaIds) {
|
||||
return favoriteDramaIds(userId, "", dramaIds);
|
||||
}
|
||||
|
||||
/** 登录用户优先;匿名状态按设备号查询。 */
|
||||
public Set<Long> favoriteDramaIds(Long userId, String deviceId,
|
||||
Collection<Long> dramaIds) {
|
||||
if (dramaIds == null || dramaIds.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
Set<Long> normalized = new HashSet<>();
|
||||
for (Long dramaId : dramaIds) {
|
||||
if (dramaId != null) {
|
||||
normalized.add(dramaId);
|
||||
}
|
||||
}
|
||||
if (normalized.isEmpty()) {
|
||||
return Set.of();
|
||||
}
|
||||
if (userId == null && (deviceId == null || deviceId.isBlank())) {
|
||||
return Set.of();
|
||||
}
|
||||
return favoriteMapper.selectList(identityQuery(new InteractionIdentity(userId, deviceId))
|
||||
.in(UserFavorite::getDramaId, normalized))
|
||||
.stream()
|
||||
.map(UserFavorite::getDramaId)
|
||||
.collect(java.util.stream.Collectors.toSet());
|
||||
}
|
||||
|
||||
/** 登录时把设备收藏归并到账号;重复收藏删除并回退剧级计数。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public MergeResult mergeDeviceIntoUser(Long userId, String deviceId) {
|
||||
if (userId == null || deviceId == null || deviceId.isBlank()) {
|
||||
return new MergeResult(0, 0);
|
||||
}
|
||||
List<UserFavorite> deviceFavorites = favoriteMapper.selectList(
|
||||
Wrappers.<UserFavorite>lambdaQuery()
|
||||
.isNull(UserFavorite::getUserId)
|
||||
.eq(UserFavorite::getDeviceId, deviceId));
|
||||
int migrated = 0;
|
||||
int duplicates = 0;
|
||||
for (UserFavorite deviceFavorite : deviceFavorites) {
|
||||
UserFavorite existing = favoriteMapper.selectOne(
|
||||
Wrappers.<UserFavorite>lambdaQuery()
|
||||
.eq(UserFavorite::getUserId, userId)
|
||||
.eq(UserFavorite::getDramaId, deviceFavorite.getDramaId())
|
||||
.last("limit 1"));
|
||||
if (existing != null) {
|
||||
if (favoriteMapper.physicalDeleteById(deviceFavorite.getId()) > 0) {
|
||||
dramaService.adjustFavoriteCount(deviceFavorite.getDramaId(), -1);
|
||||
}
|
||||
duplicates++;
|
||||
continue;
|
||||
}
|
||||
deviceFavorite.setUserId(userId);
|
||||
favoriteMapper.updateById(deviceFavorite);
|
||||
migrated++;
|
||||
}
|
||||
return new MergeResult(migrated, duplicates);
|
||||
}
|
||||
|
||||
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserFavorite>
|
||||
identityQuery(InteractionIdentity identity) {
|
||||
if (identity.authenticated()) {
|
||||
return Wrappers.<UserFavorite>lambdaQuery()
|
||||
.eq(UserFavorite::getUserId, identity.userId());
|
||||
}
|
||||
return Wrappers.<UserFavorite>lambdaQuery()
|
||||
.isNull(UserFavorite::getUserId)
|
||||
.eq(UserFavorite::getDeviceId, identity.deviceId());
|
||||
}
|
||||
|
||||
public record MergeResult(int migrated, int duplicates) {
|
||||
}
|
||||
|
||||
/** 分页查询收藏短剧,保持收藏时间与 dramaId 稳定排序。 */
|
||||
public PageResult<Drama> page(Long userId, int pageIndex, int pageSize) {
|
||||
return page(new InteractionIdentity(userId, ""), pageIndex, pageSize);
|
||||
}
|
||||
|
||||
/** 分页查询当前登录账号或匿名设备的收藏短剧。 */
|
||||
public PageResult<Drama> page(
|
||||
InteractionIdentity identity, int pageIndex, int pageSize) {
|
||||
int safeIndex = Math.max(pageIndex, 1);
|
||||
int safeSize = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Page<UserFavorite> request = new Page<>(safeIndex, safeSize);
|
||||
String publishedDramaSql = "SELECT id FROM drama WHERE deleted = 0 AND status = '"
|
||||
+ ContentStatus.PUBLISHED.getCode() + "'";
|
||||
IPage<UserFavorite> result = favoriteMapper.selectPage(request,
|
||||
Wrappers.<UserFavorite>lambdaQuery()
|
||||
.eq(UserFavorite::getUserId, userId)
|
||||
identityQuery(identity)
|
||||
.inSql(UserFavorite::getDramaId, publishedDramaSql)
|
||||
.orderByDesc(UserFavorite::getCreatedAt)
|
||||
.orderByDesc(UserFavorite::getDramaId));
|
||||
@@ -106,19 +198,47 @@ public class FavoriteService {
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void removeBatch(Long userId, List<Long> dramaIds) {
|
||||
if (dramaIds == null || dramaIds.isEmpty()) {
|
||||
return;
|
||||
public void removeDevice(String deviceId, Long dramaId) {
|
||||
int removed = favoriteMapper.physicalDeleteDevice(deviceId, dramaId);
|
||||
if (removed > 0) {
|
||||
dramaService.adjustFavoriteCount(dramaId, -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int removeBatch(Long userId, List<Long> dramaIds) {
|
||||
return removeBatchInternal(new InteractionIdentity(userId, ""), dramaIds);
|
||||
}
|
||||
|
||||
/** 登录账号或匿名设备在同一事务内批量取消收藏。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int removeBatch(InteractionIdentity identity, List<Long> dramaIds) {
|
||||
return removeBatchInternal(identity, dramaIds);
|
||||
}
|
||||
|
||||
private int removeBatchInternal(
|
||||
InteractionIdentity identity, List<Long> dramaIds) {
|
||||
if (dramaIds == null || dramaIds.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
Set<Long> normalized = new HashSet<>();
|
||||
for (Long dramaId : dramaIds) {
|
||||
if (dramaId == null) {
|
||||
continue;
|
||||
}
|
||||
int removed = favoriteMapper.physicalDelete(userId, dramaId);
|
||||
normalized.add(dramaId);
|
||||
}
|
||||
int deleted = 0;
|
||||
for (Long dramaId : normalized) {
|
||||
int removed = identity.authenticated()
|
||||
? favoriteMapper.physicalDelete(identity.userId(), dramaId)
|
||||
: favoriteMapper.physicalDeleteDevice(identity.deviceId(), dramaId);
|
||||
if (removed > 0) {
|
||||
dramaService.adjustFavoriteCount(dramaId, -1);
|
||||
deleted += removed;
|
||||
}
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/** 查询用户对某部剧最近一次收藏时间。 */
|
||||
|
||||
+6
@@ -2,6 +2,8 @@
|
||||
|
||||
package com.fruitshorts.playback.service;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.DramaService;
|
||||
@@ -57,6 +59,10 @@ public class PlaybackService {
|
||||
|
||||
boolean free = episode.getIsFree() != null && episode.getIsFree() == 1;
|
||||
boolean entitled = userId != null && entitlementPort.isUnlocked(userId, drama.getId(), episode.getId());
|
||||
if (!free && !entitled && userId == null) {
|
||||
// 锁定集正片必须登录;即使暂时没有片源,也不能把游客引到匿名取票分支。
|
||||
throw new ServiceException(ErrorCode.UNAUTHORIZED, "登录后才能解锁并观看该集");
|
||||
}
|
||||
String source = playableSource(episode);
|
||||
|
||||
PlayRespVO vo = new PlayRespVO();
|
||||
|
||||
+206
-24
@@ -3,9 +3,11 @@
|
||||
package com.fruitshorts.playback.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.fruitshorts.common.pojo.PageResult;
|
||||
import com.fruitshorts.common.interaction.InteractionIdentity;
|
||||
import com.fruitshorts.content.dal.entity.Drama;
|
||||
import com.fruitshorts.content.dal.entity.DramaEpisode;
|
||||
import com.fruitshorts.content.service.ContentLocaleTexts;
|
||||
@@ -21,6 +23,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
@@ -33,7 +36,7 @@ import java.util.Objects;
|
||||
* 观看进度。
|
||||
*
|
||||
* <p>每次上报都写库在高并发下会成为瓶颈(1 万并发 × 每 10 秒一次 ≈ 1000 写/秒),
|
||||
* 所以生产形态是「先写 Redis,后台任务按 user+drama 合并后批量 UPSERT」。
|
||||
* 所以生产形态是「先写 Redis,后台任务按登录账号或设备 + drama 合并后批量 UPSERT」。
|
||||
* 这里先落地权威表与合并规则,缓存层在接入 Redis 时补齐,接口契约不变。
|
||||
*
|
||||
* <p>合并规则:以客户端上报的 positionMs 为准,但只在「更靠后」时覆盖,
|
||||
@@ -53,6 +56,11 @@ public class WatchProgressService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProgressRespVO save(Long userId, ProgressSaveReqVO req) {
|
||||
return save(new InteractionIdentity(userId, ""), req);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProgressRespVO save(InteractionIdentity identity, ProgressSaveReqVO req) {
|
||||
DramaEpisode episode = episodeService.getPublished(req.getEpisodeId());
|
||||
Drama drama = dramaService.getPublished(episode.getDramaId());
|
||||
long position = req.getPositionMs() == null ? 0L : Math.max(0L, req.getPositionMs());
|
||||
@@ -60,11 +68,11 @@ public class WatchProgressService {
|
||||
boolean finished = Boolean.TRUE.equals(req.getFinished())
|
||||
|| (duration > 0 && position + FINISH_THRESHOLD_MS >= duration);
|
||||
|
||||
LoadedProgress loaded = loadForSave(userId, drama.getId(), episode, position, duration,
|
||||
LoadedProgress loaded = loadForSave(identity, drama.getId(), episode, position, duration,
|
||||
finished, req);
|
||||
WatchProgress existing = loaded.progress();
|
||||
if (loaded.created()) {
|
||||
appendHistory(userId, drama.getId(), episode.getId(), position, duration,
|
||||
appendHistory(identity, drama.getId(), episode.getId(), position, duration,
|
||||
existing.getSource(), existing.getDeviceId());
|
||||
return toResp(progressMapper.selectById(existing.getId()));
|
||||
}
|
||||
@@ -74,7 +82,7 @@ public class WatchProgressService {
|
||||
&& existing.getEpisodeId().equals(episode.getId());
|
||||
if (hidden && sameEpisode) {
|
||||
existing.setPlayCount((existing.getPlayCount() == null ? 0 : existing.getPlayCount()) + 1);
|
||||
appendHistory(userId, drama.getId(), episode.getId(), position, duration,
|
||||
appendHistory(identity, drama.getId(), episode.getId(), position, duration,
|
||||
req.getSource(), existing.getDeviceId());
|
||||
}
|
||||
if (!sameEpisode) {
|
||||
@@ -84,7 +92,7 @@ public class WatchProgressService {
|
||||
existing.setDurationMs(duration);
|
||||
existing.setFinished(finished ? 1 : 0);
|
||||
existing.setPlayCount((existing.getPlayCount() == null ? 0 : existing.getPlayCount()) + 1);
|
||||
appendHistory(userId, drama.getId(), episode.getId(), position, duration,
|
||||
appendHistory(identity, drama.getId(), episode.getId(), position, duration,
|
||||
req.getSource(), existing.getDeviceId());
|
||||
} else {
|
||||
existing.setDurationMs(Math.max(existing.getDurationMs() == null ? 0L : existing.getDurationMs(),
|
||||
@@ -96,7 +104,9 @@ public class WatchProgressService {
|
||||
existing.setFinished(1);
|
||||
}
|
||||
}
|
||||
existing.setDeviceId(req.getDeviceId() == null ? "" : req.getDeviceId());
|
||||
existing.setDeviceId(identity.authenticated()
|
||||
? (req.getDeviceId() == null ? "" : req.getDeviceId())
|
||||
: identity.deviceId());
|
||||
existing.setSource(req.getSource() == null ? "" : req.getSource());
|
||||
if (hidden) {
|
||||
existing.setDeleted(0);
|
||||
@@ -107,18 +117,22 @@ public class WatchProgressService {
|
||||
return toResp(progressMapper.selectById(existing.getId()));
|
||||
}
|
||||
|
||||
private LoadedProgress loadForSave(Long userId, Long dramaId, DramaEpisode episode, long position,
|
||||
private LoadedProgress loadForSave(InteractionIdentity identity, Long dramaId,
|
||||
DramaEpisode episode, long position,
|
||||
long duration, boolean finished, ProgressSaveReqVO req) {
|
||||
WatchProgress existing = progressMapper.selectAny(userId, dramaId);
|
||||
WatchProgress existing = progressMapper.selectAnyForIdentity(
|
||||
identity.userId(), identity.deviceId(), dramaId);
|
||||
if (existing != null) {
|
||||
return new LoadedProgress(existing, false);
|
||||
}
|
||||
WatchProgress created = newProgress(userId, dramaId, episode, position, duration, finished, req);
|
||||
WatchProgress created = newProgress(
|
||||
identity, dramaId, episode, position, duration, finished, req);
|
||||
try {
|
||||
progressMapper.insert(created);
|
||||
return new LoadedProgress(created, true);
|
||||
} catch (DuplicateKeyException ex) {
|
||||
WatchProgress raced = progressMapper.selectAny(userId, dramaId);
|
||||
WatchProgress raced = progressMapper.selectAnyForIdentity(
|
||||
identity.userId(), identity.deviceId(), dramaId);
|
||||
if (raced == null) {
|
||||
throw ex;
|
||||
}
|
||||
@@ -126,17 +140,20 @@ public class WatchProgressService {
|
||||
}
|
||||
}
|
||||
|
||||
private WatchProgress newProgress(Long userId, Long dramaId, DramaEpisode episode, long position,
|
||||
private WatchProgress newProgress(InteractionIdentity identity, Long dramaId,
|
||||
DramaEpisode episode, long position,
|
||||
long duration, boolean finished, ProgressSaveReqVO req) {
|
||||
WatchProgress progress = new WatchProgress();
|
||||
progress.setUserId(userId);
|
||||
progress.setUserId(identity.userId());
|
||||
progress.setDramaId(dramaId);
|
||||
progress.setEpisodeId(episode.getId());
|
||||
progress.setPositionMs(position);
|
||||
progress.setDurationMs(duration);
|
||||
progress.setFinished(finished ? 1 : 0);
|
||||
progress.setPlayCount(1);
|
||||
progress.setDeviceId(req.getDeviceId() == null ? "" : req.getDeviceId());
|
||||
progress.setDeviceId(identity.authenticated()
|
||||
? (req.getDeviceId() == null ? "" : req.getDeviceId())
|
||||
: identity.deviceId());
|
||||
progress.setSource(req.getSource() == null ? "" : req.getSource());
|
||||
return progress;
|
||||
}
|
||||
@@ -145,8 +162,11 @@ public class WatchProgressService {
|
||||
}
|
||||
|
||||
public ProgressRespVO ofDrama(Long userId, Long dramaId) {
|
||||
WatchProgress progress = progressMapper.selectOne(Wrappers.<WatchProgress>lambdaQuery()
|
||||
.eq(WatchProgress::getUserId, userId)
|
||||
return ofDrama(new InteractionIdentity(userId, ""), dramaId);
|
||||
}
|
||||
|
||||
public ProgressRespVO ofDrama(InteractionIdentity identity, Long dramaId) {
|
||||
WatchProgress progress = progressMapper.selectOne(identityQuery(identity)
|
||||
.eq(WatchProgress::getDramaId, dramaId)
|
||||
.last("limit 1"));
|
||||
return progress == null ? null : toResp(progress);
|
||||
@@ -154,12 +174,16 @@ public class WatchProgressService {
|
||||
|
||||
/** 分页查询最近观看,按更新时间倒序并以 id 兜底保证稳定。 */
|
||||
public PageResult<ProgressRespVO> recentPage(Long userId, int pageIndex, int pageSize) {
|
||||
return recentPage(new InteractionIdentity(userId, ""), pageIndex, pageSize);
|
||||
}
|
||||
|
||||
public PageResult<ProgressRespVO> recentPage(
|
||||
InteractionIdentity identity, int pageIndex, int pageSize) {
|
||||
int safeIndex = Math.max(pageIndex, 1);
|
||||
int safeSize = Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Page<WatchProgress> request = new Page<>(safeIndex, safeSize);
|
||||
IPage<WatchProgress> result = progressMapper.selectPage(request,
|
||||
Wrappers.<WatchProgress>lambdaQuery()
|
||||
.eq(WatchProgress::getUserId, userId)
|
||||
identityQuery(identity)
|
||||
.orderByDesc(WatchProgress::getUpdatedAt)
|
||||
.orderByDesc(WatchProgress::getId));
|
||||
return new PageResult<>(result.getTotal(), enrichDisplay(result.getRecords()));
|
||||
@@ -167,15 +191,23 @@ public class WatchProgressService {
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void remove(Long userId, Long dramaId) {
|
||||
progressMapper.delete(Wrappers.<WatchProgress>lambdaQuery()
|
||||
.eq(WatchProgress::getUserId, userId)
|
||||
remove(new InteractionIdentity(userId, ""), dramaId);
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void remove(InteractionIdentity identity, Long dramaId) {
|
||||
progressMapper.delete(identityQuery(identity)
|
||||
.eq(WatchProgress::getDramaId, dramaId));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void clear(Long userId) {
|
||||
progressMapper.delete(Wrappers.<WatchProgress>lambdaQuery()
|
||||
.eq(WatchProgress::getUserId, userId));
|
||||
clear(new InteractionIdentity(userId, ""));
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void clear(InteractionIdentity identity) {
|
||||
progressMapper.delete(identityQuery(identity));
|
||||
}
|
||||
|
||||
private ProgressRespVO toResp(WatchProgress progress) {
|
||||
@@ -248,19 +280,169 @@ public class WatchProgressService {
|
||||
* 追加一条观看流水。只在「首次观看一部剧」和「切换剧集」时调用,
|
||||
* 每 10 秒的进度上报不写这里 —— 否则单集会产出几十条噪音。
|
||||
*/
|
||||
private void appendHistory(Long userId, Long dramaId, Long episodeId, long positionMs,
|
||||
private void appendHistory(InteractionIdentity identity, Long dramaId, Long episodeId,
|
||||
long positionMs,
|
||||
long durationMs, String source, String deviceId) {
|
||||
WatchHistory history = new WatchHistory();
|
||||
history.setUserId(userId);
|
||||
history.setUserId(identity.userId());
|
||||
history.setDramaId(dramaId);
|
||||
history.setEpisodeId(episodeId);
|
||||
history.setPositionMs(positionMs);
|
||||
history.setDurationMs(durationMs);
|
||||
history.setSource(source == null ? "" : source);
|
||||
history.setDeviceId(deviceId == null ? "" : deviceId);
|
||||
history.setDeviceId(identity.authenticated()
|
||||
? (deviceId == null ? "" : deviceId)
|
||||
: identity.deviceId());
|
||||
historyMapper.insert(history);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录时合并设备进度和观看流水。
|
||||
*
|
||||
* <p>同一部剧只保留进度更靠前的账号记录:先比较集号,同集再比较播放位置,
|
||||
* 最后用更新时间兜底。playCount 只取保留记录,不把两条记录的计数相加。
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public MergeResult mergeDeviceIntoUser(Long userId, String deviceId) {
|
||||
if (userId == null || !StringUtils.hasText(deviceId)) {
|
||||
return new MergeResult(0, 0, 0, 0);
|
||||
}
|
||||
List<WatchProgress> deviceProgress = progressMapper.selectList(
|
||||
Wrappers.<WatchProgress>lambdaQuery()
|
||||
.isNull(WatchProgress::getUserId)
|
||||
.eq(WatchProgress::getDeviceId, deviceId));
|
||||
Map<Long, Integer> episodeNumbers = episodeNumbers(deviceProgress);
|
||||
int progressMigrated = 0;
|
||||
int progressIgnored = 0;
|
||||
for (WatchProgress device : deviceProgress) {
|
||||
WatchProgress account = progressMapper.selectAnyForIdentity(
|
||||
userId, "", device.getDramaId());
|
||||
if (account == null) {
|
||||
device.setUserId(userId);
|
||||
progressMapper.updateById(device);
|
||||
progressMigrated++;
|
||||
continue;
|
||||
}
|
||||
if (progressAhead(device, account, episodeNumbers)) {
|
||||
copyProgress(device, account);
|
||||
account.setDeleted(0);
|
||||
progressMapper.updateAny(account);
|
||||
progressMigrated++;
|
||||
} else {
|
||||
progressIgnored++;
|
||||
}
|
||||
progressMapper.deleteById(device.getId());
|
||||
}
|
||||
|
||||
List<WatchHistory> deviceHistory = historyMapper.selectList(
|
||||
Wrappers.<WatchHistory>lambdaQuery()
|
||||
.isNull(WatchHistory::getUserId)
|
||||
.eq(WatchHistory::getDeviceId, deviceId));
|
||||
int historyMigrated = 0;
|
||||
int historyIgnored = 0;
|
||||
for (WatchHistory device : deviceHistory) {
|
||||
WatchHistory account = historyMapper.selectOne(
|
||||
Wrappers.<WatchHistory>lambdaQuery()
|
||||
.eq(WatchHistory::getUserId, userId)
|
||||
.eq(WatchHistory::getDramaId, device.getDramaId())
|
||||
.eq(WatchHistory::getEpisodeId, device.getEpisodeId())
|
||||
.orderByDesc(WatchHistory::getWatchedAt)
|
||||
.last("limit 1"));
|
||||
if (account == null) {
|
||||
device.setUserId(userId);
|
||||
historyMapper.updateById(device);
|
||||
historyMigrated++;
|
||||
continue;
|
||||
}
|
||||
if (historyAhead(device, account)) {
|
||||
account.setPositionMs(device.getPositionMs());
|
||||
account.setDurationMs(device.getDurationMs());
|
||||
account.setSource(device.getSource());
|
||||
account.setWatchedAt(device.getWatchedAt());
|
||||
historyMapper.updateById(account);
|
||||
historyMigrated++;
|
||||
} else {
|
||||
historyIgnored++;
|
||||
}
|
||||
historyMapper.deleteById(device.getId());
|
||||
}
|
||||
return new MergeResult(
|
||||
progressMigrated, progressIgnored, historyMigrated, historyIgnored);
|
||||
}
|
||||
|
||||
public record MergeResult(
|
||||
int progressMigrated,
|
||||
int progressIgnored,
|
||||
int historyMigrated,
|
||||
int historyIgnored) {
|
||||
}
|
||||
|
||||
private Map<Long, Integer> episodeNumbers(List<WatchProgress> progress) {
|
||||
List<Long> episodeIds = progress.stream()
|
||||
.map(WatchProgress::getEpisodeId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
Map<Long, Integer> result = new HashMap<>();
|
||||
if (episodeIds.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
for (DramaEpisode episode : episodeService.listByIds(episodeIds)) {
|
||||
result.put(episode.getId(), episode.getEpNo());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean progressAhead(
|
||||
WatchProgress candidate,
|
||||
WatchProgress current,
|
||||
Map<Long, Integer> episodeNumbers) {
|
||||
Integer candidateNo = episodeNumbers.get(candidate.getEpisodeId());
|
||||
Integer currentNo = episodeNumbers.get(current.getEpisodeId());
|
||||
if (candidateNo != null && currentNo != null && !candidateNo.equals(currentNo)) {
|
||||
return candidateNo > currentNo;
|
||||
}
|
||||
long candidatePosition = candidate.getPositionMs() == null ? 0L : candidate.getPositionMs();
|
||||
long currentPosition = current.getPositionMs() == null ? 0L : current.getPositionMs();
|
||||
if (candidatePosition != currentPosition) {
|
||||
return candidatePosition > currentPosition;
|
||||
}
|
||||
return candidate.getUpdatedAt() != null
|
||||
&& (current.getUpdatedAt() == null
|
||||
|| candidate.getUpdatedAt().isAfter(current.getUpdatedAt()));
|
||||
}
|
||||
|
||||
private void copyProgress(WatchProgress source, WatchProgress target) {
|
||||
target.setEpisodeId(source.getEpisodeId());
|
||||
target.setPositionMs(source.getPositionMs());
|
||||
target.setDurationMs(source.getDurationMs());
|
||||
target.setFinished(source.getFinished());
|
||||
target.setPlayCount(source.getPlayCount());
|
||||
target.setDeviceId(source.getDeviceId());
|
||||
target.setSource(source.getSource());
|
||||
}
|
||||
|
||||
private boolean historyAhead(WatchHistory candidate, WatchHistory current) {
|
||||
long candidatePosition = candidate.getPositionMs() == null ? 0L : candidate.getPositionMs();
|
||||
long currentPosition = current.getPositionMs() == null ? 0L : current.getPositionMs();
|
||||
if (candidatePosition != currentPosition) {
|
||||
return candidatePosition > currentPosition;
|
||||
}
|
||||
return candidate.getWatchedAt() != null
|
||||
&& (current.getWatchedAt() == null
|
||||
|| candidate.getWatchedAt().isAfter(current.getWatchedAt()));
|
||||
}
|
||||
|
||||
private LambdaQueryWrapper<WatchProgress> identityQuery(InteractionIdentity identity) {
|
||||
if (identity.authenticated()) {
|
||||
return Wrappers.<WatchProgress>lambdaQuery()
|
||||
.eq(WatchProgress::getUserId, identity.userId());
|
||||
}
|
||||
return Wrappers.<WatchProgress>lambdaQuery()
|
||||
.isNull(WatchProgress::getUserId)
|
||||
.eq(WatchProgress::getDeviceId, identity.deviceId());
|
||||
}
|
||||
|
||||
/** 供后续批量合并任务使用:只更新进度字段,避免整行覆盖。 */
|
||||
public void mergeInto(Long userId, Long dramaId, Long episodeId, long positionMs) {
|
||||
progressMapper.update(null, Wrappers.<WatchProgress>lambdaUpdate()
|
||||
|
||||
+6
-1
@@ -4,6 +4,7 @@ package com.fruitshorts.playback.vo;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.util.List;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -11,6 +12,10 @@ import lombok.Data;
|
||||
@Data
|
||||
public class FavoriteRemoveReqVO {
|
||||
|
||||
@NotEmpty(message = "缺少 dramaIds")
|
||||
@NotEmpty(message = "dramaIds 不能为空")
|
||||
@Size(max = 200, message = "dramaIds 最多 200 条")
|
||||
private List<@NotNull Long> dramaIds;
|
||||
|
||||
/** 未登录且未携带 X-Device-Id 时的兜底设备号。 */
|
||||
private String deviceId;
|
||||
}
|
||||
+3
@@ -11,4 +11,7 @@ public class FavoriteToggleReqVO {
|
||||
|
||||
@NotNull(message = "缺少 dramaId")
|
||||
private Long dramaId;
|
||||
|
||||
/** 兼容旧调用;正常客户端通过 X-Device-Id 下发。 */
|
||||
private String deviceId;
|
||||
}
|
||||
@@ -25,5 +25,10 @@
|
||||
<groupId>com.fruitshorts</groupId>
|
||||
<artifactId>fruitshorts-module-system</artifactId>
|
||||
</dependency>
|
||||
<!-- 离线 IP → 国家解析,xdb 数据在 src/main/resources/ip2region 下 -->
|
||||
<dependency>
|
||||
<groupId>org.lionsoul</groupId>
|
||||
<artifactId>ip2region</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.dal.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 设备平台:按 device_id 记录客户端是 iOS 还是 Android。
|
||||
* 与会话不同,它不依赖用户身份,游客请求也会建档。
|
||||
*/
|
||||
@Data
|
||||
@TableName("app_device_profile")
|
||||
public class AppDeviceProfile {
|
||||
|
||||
@TableId(type = IdType.ASSIGN_ID)
|
||||
private Long id;
|
||||
private String deviceId;
|
||||
private String platform;
|
||||
private LocalDateTime firstSeenAt;
|
||||
private LocalDateTime lastSeenAt;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.dal.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
public interface AppDeviceProfileMapper extends BaseMapper<AppDeviceProfile> {
|
||||
|
||||
/**
|
||||
* 按 device_id 建档或刷新平台。
|
||||
* 空平台不覆盖已有值:老版本客户端不带平台头,不能把已记录的值抹掉。
|
||||
*/
|
||||
@Insert("""
|
||||
INSERT INTO app_device_profile (id, device_id, platform,
|
||||
first_seen_at, last_seen_at, created_at, updated_at, deleted)
|
||||
VALUES (#{p.id}, #{p.deviceId}, #{p.platform},
|
||||
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 0)
|
||||
ON CONFLICT (device_id) DO UPDATE SET
|
||||
platform = CASE WHEN EXCLUDED.platform <> '' THEN EXCLUDED.platform
|
||||
ELSE app_device_profile.platform END,
|
||||
last_seen_at = CURRENT_TIMESTAMP,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""")
|
||||
int upsert(@Param("p") AppDeviceProfile profile);
|
||||
}
|
||||
+21
@@ -4,6 +4,27 @@ package com.fruitshorts.user.dal.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.fruitshorts.user.dal.entity.AppUserSession;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface AppUserSessionMapper extends BaseMapper<AppUserSession> {
|
||||
|
||||
/**
|
||||
* 最近一次登录会话平台等于指定值的用户。
|
||||
* 必须取「最近一次」而不是「存在过」:否则同一用户在 Android 登录过、
|
||||
* 后来又换 iOS,会被两端都命中,筛选结果与实际展示的系统不一致。
|
||||
*/
|
||||
@Select("""
|
||||
SELECT t.user_id
|
||||
FROM (
|
||||
SELECT DISTINCT ON (user_id) user_id, platform
|
||||
FROM app_user_session
|
||||
WHERE deleted = 0
|
||||
ORDER BY user_id, last_active_at DESC NULLS LAST, id DESC
|
||||
) t
|
||||
WHERE t.platform = #{platform}
|
||||
""")
|
||||
List<Long> selectUserIdsByLatestPlatform(@Param("platform") String platform);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.enums;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 国家/地区 → 语言、时区、币种。
|
||||
*
|
||||
* <p>App 目前只内置 en / id / zh 三种语言,除印尼、中国及台港澳外的市场统一落到 en-US;
|
||||
* 时区与币种按国家真实值写入,避免所有用户都变成 IDR。
|
||||
*
|
||||
* <p>未收录的国家按 {@link #DEFAULT}(印尼)处理,与历史行为保持一致。
|
||||
*/
|
||||
@Slf4j
|
||||
public enum CountryProfile {
|
||||
|
||||
ID("id-ID", "Asia/Jakarta", "IDR"),
|
||||
MY("en-US", "Asia/Kuala_Lumpur", "MYR"),
|
||||
SG("en-US", "Asia/Singapore", "SGD"),
|
||||
TH("en-US", "Asia/Bangkok", "THB"),
|
||||
VN("en-US", "Asia/Ho_Chi_Minh", "VND"),
|
||||
PH("en-US", "Asia/Manila", "PHP"),
|
||||
KH("en-US", "Asia/Phnom_Penh", "KHR"),
|
||||
MM("en-US", "Asia/Yangon", "MMK"),
|
||||
LA("en-US", "Asia/Vientiane", "LAK"),
|
||||
BN("en-US", "Asia/Brunei", "BND"),
|
||||
CN("zh-CN", "Asia/Shanghai", "CNY"),
|
||||
TW("zh-TW", "Asia/Taipei", "TWD"),
|
||||
HK("zh-HK", "Asia/Hong_Kong", "HKD"),
|
||||
MO("zh-HK", "Asia/Macau", "MOP"),
|
||||
JP("en-US", "Asia/Tokyo", "JPY"),
|
||||
KR("en-US", "Asia/Seoul", "KRW"),
|
||||
IN("en-US", "Asia/Kolkata", "INR"),
|
||||
PK("en-US", "Asia/Karachi", "PKR"),
|
||||
BD("en-US", "Asia/Dhaka", "BDT"),
|
||||
LK("en-US", "Asia/Colombo", "LKR"),
|
||||
NP("en-US", "Asia/Kathmandu", "NPR"),
|
||||
US("en-US", "America/New_York", "USD"),
|
||||
CA("en-US", "America/Toronto", "CAD"),
|
||||
MX("en-US", "America/Mexico_City", "MXN"),
|
||||
BR("en-US", "America/Sao_Paulo", "BRL"),
|
||||
AR("en-US", "America/Argentina/Buenos_Aires", "ARS"),
|
||||
CL("en-US", "America/Santiago", "CLP"),
|
||||
CO("en-US", "America/Bogota", "COP"),
|
||||
PE("en-US", "America/Lima", "PEN"),
|
||||
VE("en-US", "America/Caracas", "VES"),
|
||||
EC("en-US", "America/Guayaquil", "USD"),
|
||||
GT("en-US", "America/Guatemala", "GTQ"),
|
||||
DO("en-US", "America/Santo_Domingo", "DOP"),
|
||||
GB("en-US", "Europe/London", "GBP"),
|
||||
DE("en-US", "Europe/Berlin", "EUR"),
|
||||
FR("en-US", "Europe/Paris", "EUR"),
|
||||
ES("en-US", "Europe/Madrid", "EUR"),
|
||||
IT("en-US", "Europe/Rome", "EUR"),
|
||||
NL("en-US", "Europe/Amsterdam", "EUR"),
|
||||
PL("en-US", "Europe/Warsaw", "PLN"),
|
||||
RU("en-US", "Europe/Moscow", "RUB"),
|
||||
UA("en-US", "Europe/Kyiv", "UAH"),
|
||||
TR("en-US", "Europe/Istanbul", "TRY"),
|
||||
SA("en-US", "Asia/Riyadh", "SAR"),
|
||||
AE("en-US", "Asia/Dubai", "AED"),
|
||||
IL("en-US", "Asia/Jerusalem", "ILS"),
|
||||
EG("en-US", "Africa/Cairo", "EGP"),
|
||||
NG("en-US", "Africa/Lagos", "NGN"),
|
||||
ZA("en-US", "Africa/Johannesburg", "ZAR"),
|
||||
KE("en-US", "Africa/Nairobi", "KES"),
|
||||
MA("en-US", "Africa/Casablanca", "MAD"),
|
||||
AU("en-US", "Australia/Sydney", "AUD"),
|
||||
NZ("en-US", "Pacific/Auckland", "NZD");
|
||||
|
||||
public static final CountryProfile DEFAULT = ID;
|
||||
|
||||
/** ip2region 返回的中文国家名 → ISO-2,只收录上面配置过的国家。 */
|
||||
private static final Map<String, String> IP_COUNTRY_NAMES = Map.ofEntries(
|
||||
Map.entry("印度尼西亚", "ID"),
|
||||
Map.entry("马来西亚", "MY"),
|
||||
Map.entry("新加坡", "SG"),
|
||||
Map.entry("泰国", "TH"),
|
||||
Map.entry("越南", "VN"),
|
||||
Map.entry("菲律宾", "PH"),
|
||||
Map.entry("柬埔寨", "KH"),
|
||||
Map.entry("缅甸", "MM"),
|
||||
Map.entry("老挝", "LA"),
|
||||
Map.entry("文莱", "BN"),
|
||||
Map.entry("中国", "CN"),
|
||||
Map.entry("日本", "JP"),
|
||||
Map.entry("韩国", "KR"),
|
||||
Map.entry("印度", "IN"),
|
||||
Map.entry("巴基斯坦", "PK"),
|
||||
Map.entry("孟加拉国", "BD"),
|
||||
Map.entry("斯里兰卡", "LK"),
|
||||
Map.entry("尼泊尔", "NP"),
|
||||
Map.entry("美国", "US"),
|
||||
Map.entry("加拿大", "CA"),
|
||||
Map.entry("墨西哥", "MX"),
|
||||
Map.entry("巴西", "BR"),
|
||||
Map.entry("阿根廷", "AR"),
|
||||
Map.entry("智利", "CL"),
|
||||
Map.entry("哥伦比亚", "CO"),
|
||||
Map.entry("秘鲁", "PE"),
|
||||
Map.entry("委内瑞拉", "VE"),
|
||||
Map.entry("厄瓜多尔", "EC"),
|
||||
Map.entry("危地马拉", "GT"),
|
||||
Map.entry("多米尼加", "DO"),
|
||||
Map.entry("英国", "GB"),
|
||||
Map.entry("德国", "DE"),
|
||||
Map.entry("法国", "FR"),
|
||||
Map.entry("西班牙", "ES"),
|
||||
Map.entry("意大利", "IT"),
|
||||
Map.entry("荷兰", "NL"),
|
||||
Map.entry("波兰", "PL"),
|
||||
Map.entry("俄罗斯", "RU"),
|
||||
Map.entry("乌克兰", "UA"),
|
||||
Map.entry("土耳其", "TR"),
|
||||
Map.entry("沙特阿拉伯", "SA"),
|
||||
Map.entry("阿联酋", "AE"),
|
||||
Map.entry("以色列", "IL"),
|
||||
Map.entry("埃及", "EG"),
|
||||
Map.entry("尼日利亚", "NG"),
|
||||
Map.entry("南非", "ZA"),
|
||||
Map.entry("肯尼亚", "KE"),
|
||||
Map.entry("摩洛哥", "MA"),
|
||||
Map.entry("澳大利亚", "AU"),
|
||||
Map.entry("新西兰", "NZ"));
|
||||
|
||||
private static final Map<String, CountryProfile> BY_CODE = new HashMap<>();
|
||||
|
||||
static {
|
||||
for (CountryProfile profile : values()) {
|
||||
BY_CODE.put(profile.name(), profile);
|
||||
}
|
||||
}
|
||||
|
||||
private final String language;
|
||||
private final String timezone;
|
||||
private final String currency;
|
||||
|
||||
CountryProfile(String language, String timezone, String currency) {
|
||||
this.language = language;
|
||||
this.timezone = timezone;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public String code() {
|
||||
return name();
|
||||
}
|
||||
|
||||
public String language() {
|
||||
return language;
|
||||
}
|
||||
|
||||
public String timezone() {
|
||||
return timezone;
|
||||
}
|
||||
|
||||
public String currency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
/** 未收录的国家统一回退到印尼。 */
|
||||
public static CountryProfile of(String countryCode) {
|
||||
CountryProfile profile = BY_CODE.get(normalize(countryCode));
|
||||
return profile == null ? DEFAULT : profile;
|
||||
}
|
||||
|
||||
/** 客户端上报的区域:只接受两位字母且已收录的国家,其余返回空串。 */
|
||||
public static String normalizeClientCode(String raw) {
|
||||
String code = normalize(raw);
|
||||
return BY_CODE.containsKey(code) ? code : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 ip2region 的 `国家|区域|省份|城市|运营商` 转成 ISO-2。
|
||||
* 台港澳在库里的国家字段都是「中国」,需要看省份区分。
|
||||
*/
|
||||
public static String fromIpRegion(String region) {
|
||||
if (!StringUtils.hasText(region)) {
|
||||
return "";
|
||||
}
|
||||
String[] parts = region.split("\\|", -1);
|
||||
String country = parts[0].trim();
|
||||
if (!StringUtils.hasText(country) || "0".equals(country)) {
|
||||
return "";
|
||||
}
|
||||
if ("中国".equals(country)) {
|
||||
String province = parts.length > 2 ? parts[2].trim() : "";
|
||||
if (province.contains("台湾")) {
|
||||
return "TW";
|
||||
}
|
||||
if (province.contains("香港")) {
|
||||
return "HK";
|
||||
}
|
||||
if (province.contains("澳门")) {
|
||||
return "MO";
|
||||
}
|
||||
return "CN";
|
||||
}
|
||||
String result = IP_COUNTRY_NAMES.getOrDefault(country, "");
|
||||
if (!StringUtils.hasText(result) && StringUtils.hasText(country)) {
|
||||
// ip2region 库里有但我们没收录的国家,debug 日志方便排查
|
||||
log.debug("ip2region 返回未收录的国家 '{}',回退到默认值(印尼)", country);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String normalize(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return "";
|
||||
}
|
||||
String code = raw.trim().toUpperCase(Locale.ROOT);
|
||||
return code.length() == 2 ? code : "";
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.event;
|
||||
|
||||
/** 登录/注册成功后,在同一事务内触发设备互动合并。 */
|
||||
public record AppInteractionMergeRequested(Long userId, String deviceId) {
|
||||
}
|
||||
+81
-16
@@ -18,6 +18,7 @@ import com.fruitshorts.user.dal.mapper.AppUserDeviceMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserMapper;
|
||||
import com.fruitshorts.user.dal.mapper.AppUserSessionMapper;
|
||||
import com.fruitshorts.user.enums.AppUserStatus;
|
||||
import com.fruitshorts.user.enums.CountryProfile;
|
||||
import com.fruitshorts.user.enums.CredentialType;
|
||||
import com.fruitshorts.user.enums.OtpScene;
|
||||
import com.fruitshorts.user.vo.AppUserRespVO;
|
||||
@@ -25,8 +26,10 @@ import com.fruitshorts.user.vo.LoginReqVO;
|
||||
import com.fruitshorts.user.vo.LogoutReqVO;
|
||||
import com.fruitshorts.user.vo.RegisterReqVO;
|
||||
import com.fruitshorts.user.vo.TokenRespVO;
|
||||
import com.fruitshorts.user.event.AppInteractionMergeRequested;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.ApplicationEventPublisher;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -63,6 +66,8 @@ public class AppAuthService {
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final ConfigService configService;
|
||||
private final GoogleIdTokenVerifier googleVerifier;
|
||||
private final ApplicationEventPublisher eventPublisher;
|
||||
private final IpRegionService ipRegionService;
|
||||
|
||||
/** 后台 sys_config 缺失或非法时使用;小于等于 0 表示不限制。 */
|
||||
@Value("${fruitshorts.auth.register-max-per-ip-per-day:5}")
|
||||
@@ -130,6 +135,7 @@ public class AppAuthService {
|
||||
TokenRespVO resp = issueTokens(user, credential, req.getDeviceId(), req.getDeviceModel(),
|
||||
req.getOsVersion(), req.getAppVersion(), req.getPlatform(), clientIp);
|
||||
resp.setNewUser(true);
|
||||
requestInteractionMerge(user.getId(), req.getDeviceId());
|
||||
return resp;
|
||||
}
|
||||
|
||||
@@ -174,11 +180,14 @@ public class AppAuthService {
|
||||
|
||||
user.setLastLoginAt(LocalDateTime.now());
|
||||
user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
|
||||
syncCountryByIp(user, clientIp);
|
||||
appUserMapper.updateById(user);
|
||||
touchDevice(user.getId(), req.getDeviceId(), req.getPlatform(), req.getDeviceModel());
|
||||
|
||||
return issueTokens(user, credential, req.getDeviceId(), req.getDeviceModel(), req.getOsVersion(),
|
||||
req.getAppVersion(), req.getPlatform(), clientIp);
|
||||
TokenRespVO resp = issueTokens(user, credential, req.getDeviceId(), req.getDeviceModel(),
|
||||
req.getOsVersion(), req.getAppVersion(), req.getPlatform(), clientIp);
|
||||
requestInteractionMerge(user.getId(), req.getDeviceId());
|
||||
return resp;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,7 +197,7 @@ public class AppAuthService {
|
||||
* 再落一条 GOOGLE 凭证用于下次直接登录;已有邮箱账号时只补 GOOGLE 凭证,不重复建号。
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public TokenRespVO googleLogin(String idToken) {
|
||||
public TokenRespVO googleLogin(String idToken, String deviceId, String clientIp) {
|
||||
GoogleUser googleUser = googleVerifier.verify(idToken);
|
||||
String email = requireEmail(googleUser);
|
||||
AppUserCredential googleCredential = findCredential(CredentialType.GOOGLE.name(), email);
|
||||
@@ -197,7 +206,7 @@ public class AppAuthService {
|
||||
if (googleCredential == null) {
|
||||
AppUserCredential emailCredential = findCredential(CredentialType.EMAIL.name(), email);
|
||||
if (emailCredential == null) {
|
||||
AppUser user = createGoogleUser(googleUser);
|
||||
AppUser user = createGoogleUser(googleUser, clientIp);
|
||||
insertCredential(user.getId(), CredentialType.EMAIL.name(), email, "");
|
||||
userId = user.getId();
|
||||
newUser = true;
|
||||
@@ -213,10 +222,13 @@ public class AppAuthService {
|
||||
googleCredential.setLastUsedAt(LocalDateTime.now());
|
||||
credentialMapper.updateById(googleCredential);
|
||||
user.setLastLoginAt(LocalDateTime.now());
|
||||
user.setLastLoginIp("");
|
||||
user.setLastLoginIp(AppIdentifier.nullSafe(clientIp));
|
||||
syncCountryByIp(user, clientIp);
|
||||
appUserMapper.updateById(user);
|
||||
TokenRespVO resp = issueTokens(user, googleCredential, null, null, null, null, null, null);
|
||||
touchDevice(user.getId(), deviceId, null, null);
|
||||
TokenRespVO resp = issueTokens(user, googleCredential, deviceId, null, null, null, null, clientIp);
|
||||
resp.setNewUser(newUser);
|
||||
requestInteractionMerge(user.getId(), deviceId);
|
||||
return resp;
|
||||
}
|
||||
|
||||
@@ -230,7 +242,7 @@ public class AppAuthService {
|
||||
}
|
||||
|
||||
/** 创建 Google 用户:邮箱已验证,昵称与头像直接取 Google 返回。 */
|
||||
private AppUser createGoogleUser(GoogleUser googleUser) {
|
||||
private AppUser createGoogleUser(GoogleUser googleUser, String clientIp) {
|
||||
AppUser user = new AppUser();
|
||||
user.setUid(hasher.newUid());
|
||||
String nickname = StringUtils.hasText(googleUser.name())
|
||||
@@ -238,11 +250,13 @@ public class AppAuthService {
|
||||
user.setNickname(nickname);
|
||||
user.setAvatarUrl(AppIdentifier.nullSafe(googleUser.picture()));
|
||||
user.setGender("");
|
||||
user.setCountryCode("ID");
|
||||
user.setRegionCode("ID");
|
||||
user.setLanguage("id-ID");
|
||||
user.setTimezone("Asia/Jakarta");
|
||||
user.setCurrency("IDR");
|
||||
String country = resolveCountry(clientIp, "");
|
||||
CountryProfile profile = CountryProfile.of(country);
|
||||
user.setCountryCode(country);
|
||||
user.setRegionCode(country);
|
||||
user.setLanguage(profile.language());
|
||||
user.setTimezone(profile.timezone());
|
||||
user.setCurrency(profile.currency());
|
||||
user.setStatus(AppUserStatus.NORMAL);
|
||||
user.setRegisterSource("APP");
|
||||
user.setRegisterChannel("");
|
||||
@@ -436,6 +450,13 @@ public class AppAuthService {
|
||||
return resp;
|
||||
}
|
||||
|
||||
private void requestInteractionMerge(Long userId, String deviceId) {
|
||||
if (StringUtils.hasText(deviceId)) {
|
||||
eventPublisher.publishEvent(
|
||||
new AppInteractionMergeRequested(userId, deviceId.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
private static final String REGISTER_IP_LIMIT_KEY = "app.register.max-per-ip-per-day";
|
||||
private static final String REGISTER_DEVICE_LIMIT_KEY = "app.register.max-per-device-per-day";
|
||||
|
||||
@@ -512,12 +533,13 @@ public class AppAuthService {
|
||||
: "User" + user.getUid().substring(1, 7));
|
||||
user.setAvatarUrl("");
|
||||
user.setGender("");
|
||||
String country = StringUtils.hasText(req.getCountryCode()) ? req.getCountryCode() : "ID";
|
||||
String country = resolveCountry(clientIp, req.getCountryCode());
|
||||
CountryProfile profile = CountryProfile.of(country);
|
||||
user.setCountryCode(country);
|
||||
user.setRegionCode(country);
|
||||
user.setLanguage("id-ID");
|
||||
user.setTimezone("Asia/Jakarta");
|
||||
user.setCurrency("IDR");
|
||||
user.setLanguage(profile.language());
|
||||
user.setTimezone(profile.timezone());
|
||||
user.setCurrency(profile.currency());
|
||||
user.setStatus(AppUserStatus.NORMAL);
|
||||
user.setRegisterSource("APP");
|
||||
user.setRegisterChannel("");
|
||||
@@ -534,6 +556,49 @@ public class AppAuthService {
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 国家判定优先级:服务端 IP 解析 → 客户端上报的设备区域 → 印尼(历史默认)。
|
||||
* IP 在本地开发/内网环境解析不出来,这时才用客户端区域。
|
||||
*/
|
||||
private String resolveCountry(String clientIp, String clientCountryCode) {
|
||||
String byIp = ipRegionService.resolveCountry(clientIp);
|
||||
if (StringUtils.hasText(byIp)) {
|
||||
return byIp;
|
||||
}
|
||||
String byClient = CountryProfile.normalizeClientCode(clientCountryCode);
|
||||
return StringUtils.hasText(byClient) ? byClient : CountryProfile.DEFAULT.code();
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录时按 IP 修正国家,解决历史账号被统一写成 ID 的问题(老用户下次登录即自愈)。
|
||||
*
|
||||
* <p>regionCode / 语言 / 时区 / 币种 只在它们仍是「旧国家映射值」时才跟着改,
|
||||
* 用户自己在资料页改过就保留,不被 IP 覆盖。countryCode 始终用 IP 结果覆盖
|
||||
* (它是国家判断的权威来源,不涉及用户偏好)。
|
||||
*/
|
||||
private void syncCountryByIp(AppUser user, String clientIp) {
|
||||
String byIp = ipRegionService.resolveCountry(clientIp);
|
||||
if (!StringUtils.hasText(byIp) || byIp.equalsIgnoreCase(user.getCountryCode())) {
|
||||
return;
|
||||
}
|
||||
CountryProfile before = CountryProfile.of(user.getCountryCode());
|
||||
CountryProfile after = CountryProfile.of(byIp);
|
||||
user.setCountryCode(byIp);
|
||||
// regionCode 与 countryCode 永远同时写入(注册时就是这样),所以保护条件和语言一致
|
||||
if (!StringUtils.hasText(user.getRegionCode()) || user.getRegionCode().equalsIgnoreCase(before.code())) {
|
||||
user.setRegionCode(byIp);
|
||||
}
|
||||
if (!StringUtils.hasText(user.getLanguage()) || user.getLanguage().equals(before.language())) {
|
||||
user.setLanguage(after.language());
|
||||
}
|
||||
if (!StringUtils.hasText(user.getTimezone()) || user.getTimezone().equals(before.timezone())) {
|
||||
user.setTimezone(after.timezone());
|
||||
}
|
||||
if (!StringUtils.hasText(user.getCurrency()) || user.getCurrency().equals(before.currency())) {
|
||||
user.setCurrency(after.currency());
|
||||
}
|
||||
}
|
||||
|
||||
private void recordConsent(Long userId, String scene, String version, String clientIp, String deviceId) {
|
||||
AppUserConsent consent = new AppUserConsent();
|
||||
consent.setUserId(userId);
|
||||
|
||||
+29
-25
@@ -2,6 +2,7 @@
|
||||
|
||||
package com.fruitshorts.user.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
@@ -30,6 +31,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -52,33 +54,36 @@ public class AppUserAdminService {
|
||||
req.getPageIndex() == null || req.getPageIndex() < 1 ? 1 : req.getPageIndex(),
|
||||
req.getPageSize() == null || req.getPageSize() < 1 ? 10 : req.getPageSize());
|
||||
|
||||
IPage<AppUser> result;
|
||||
List<Long> platformUserIds = null;
|
||||
if (StringUtils.hasText(req.getPlatform())) {
|
||||
// 与列表展示保持一致:取每个用户最近一次会话的平台
|
||||
platformUserIds = sessionMapper.selectUserIdsByLatestPlatform(
|
||||
req.getPlatform().trim().toUpperCase(Locale.ROOT));
|
||||
if (platformUserIds.isEmpty()) {
|
||||
return new PageResult<>(0L, List.of());
|
||||
}
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<AppUser> wrapper = Wrappers.lambdaQuery();
|
||||
if (StringUtils.hasText(req.getKeyword())) {
|
||||
// uid / 昵称 直接查;手机号与邮箱要先在凭证表命中 userId
|
||||
List<Long> matchedUserIds = userIdsByCredential(req.getKeyword());
|
||||
result = appUserMapper.selectPage(page, Wrappers.<AppUser>lambdaQuery()
|
||||
.and(wrapper -> {
|
||||
wrapper.like(AppUser::getUid, req.getKeyword())
|
||||
.or().like(AppUser::getNickname, req.getKeyword());
|
||||
if (!matchedUserIds.isEmpty()) {
|
||||
wrapper.or().in(AppUser::getId, matchedUserIds);
|
||||
}
|
||||
})
|
||||
.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
|
||||
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
|
||||
req.getCountryCode())
|
||||
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
|
||||
req.getRegisterSource())
|
||||
.orderByDesc(AppUser::getId));
|
||||
} else {
|
||||
result = appUserMapper.selectPage(page, Wrappers.<AppUser>lambdaQuery()
|
||||
.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
|
||||
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
|
||||
req.getCountryCode())
|
||||
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
|
||||
req.getRegisterSource())
|
||||
.orderByDesc(AppUser::getId));
|
||||
wrapper.and(nested -> {
|
||||
nested.like(AppUser::getUid, req.getKeyword())
|
||||
.or().like(AppUser::getNickname, req.getKeyword());
|
||||
if (!matchedUserIds.isEmpty()) {
|
||||
nested.or().in(AppUser::getId, matchedUserIds);
|
||||
}
|
||||
});
|
||||
}
|
||||
wrapper.eq(StringUtils.hasText(req.getStatus()), AppUser::getStatus, req.getStatus())
|
||||
.eq(StringUtils.hasText(req.getCountryCode()), AppUser::getCountryCode,
|
||||
req.getCountryCode())
|
||||
.eq(StringUtils.hasText(req.getRegisterSource()), AppUser::getRegisterSource,
|
||||
req.getRegisterSource())
|
||||
.in(platformUserIds != null, AppUser::getId, platformUserIds)
|
||||
.orderByDesc(AppUser::getId);
|
||||
IPage<AppUser> result = appUserMapper.selectPage(page, wrapper);
|
||||
List<AppUserAdminRespVO> list = toRespList(result.getRecords());
|
||||
fillLatestSystem(list);
|
||||
return new PageResult<>(result.getTotal(), list);
|
||||
@@ -164,7 +169,7 @@ public class AppUserAdminService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 用最近一次未吊销会话上的系统信息,供后台用户列表展示。 */
|
||||
/** 用最近一次会话上的系统信息,供后台用户列表展示;排序需与平台筛选一致。 */
|
||||
private void fillLatestSystem(List<AppUserAdminRespVO> list) {
|
||||
if (list.isEmpty()) {
|
||||
return;
|
||||
@@ -180,7 +185,6 @@ public class AppUserAdminService {
|
||||
}
|
||||
List<AppUserSession> sessions = sessionMapper.selectList(Wrappers.<AppUserSession>lambdaQuery()
|
||||
.in(AppUserSession::getUserId, ids)
|
||||
.isNull(AppUserSession::getRevokedAt)
|
||||
.orderByDesc(AppUserSession::getLastActiveAt)
|
||||
.orderByDesc(AppUserSession::getId));
|
||||
Map<Long, AppUserSession> latest = new HashMap<>();
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
|
||||
import com.fruitshorts.user.dal.entity.AppDeviceProfile;
|
||||
import com.fruitshorts.user.dal.mapper.AppDeviceProfileMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/** 设备平台写入:按 device_id 建档,匿名请求也记录。 */
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceProfileService {
|
||||
|
||||
private static final int DEVICE_ID_MAX = 128;
|
||||
private static final int PLATFORM_MAX = 16;
|
||||
|
||||
private final AppDeviceProfileMapper mapper;
|
||||
|
||||
/** 记录或刷新设备平台;平台为空时直接跳过,避免产生无意义记录。 */
|
||||
public void touch(String deviceId, String platform) {
|
||||
String cleanPlatform = sanitize(platform, PLATFORM_MAX).toUpperCase(Locale.ROOT);
|
||||
if (!StringUtils.hasText(deviceId) || cleanPlatform.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
AppDeviceProfile profile = new AppDeviceProfile();
|
||||
profile.setId(IdWorker.getId());
|
||||
profile.setDeviceId(sanitize(deviceId, DEVICE_ID_MAX));
|
||||
profile.setPlatform(cleanPlatform);
|
||||
try {
|
||||
mapper.upsert(profile);
|
||||
} catch (RuntimeException ex) {
|
||||
// 平台只用于后台展示,写失败不能影响正常业务请求
|
||||
log.warn("device-platform upsert failed deviceId={} reason={}", profile.getDeviceId(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private String sanitize(String value, int maxLength) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = value.trim().replaceAll("[\\p{Cntrl}]", "");
|
||||
return trimmed.length() <= maxLength ? trimmed : trimmed.substring(0, maxLength);
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.user.service;
|
||||
|
||||
import com.fruitshorts.user.enums.CountryProfile;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.lionsoul.ip2region.xdb.Searcher;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* 把登录/注册请求的客户端 IP 解析成国家码。
|
||||
*
|
||||
* <p>用离线 ip2region(xdb 随包发布),不依赖外部接口;内网、保留地址与未收录国家返回空串,
|
||||
* 由调用方回退到客户端上报的设备区域。数据加载失败也不阻断启动,只是 IP 解析不生效。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class IpRegionService {
|
||||
|
||||
private static final String DB_PATH = "ip2region/ip2region.xdb";
|
||||
|
||||
private volatile Searcher searcher;
|
||||
private volatile boolean loaded;
|
||||
|
||||
/** 返回 ISO-2 国家码;解析不出来返回空串。 */
|
||||
public String resolveCountry(String ip) {
|
||||
Searcher current = searcher();
|
||||
if (current == null || !StringUtils.hasText(ip)) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
return CountryProfile.fromIpRegion(current.search(ip.trim()));
|
||||
} catch (Exception ex) {
|
||||
// 非法 IP(本地开发、测试桩)不当作错误,交给客户端区域兜底
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private Searcher searcher() {
|
||||
if (loaded) {
|
||||
return searcher;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (!loaded) {
|
||||
try (InputStream in = new ClassPathResource(DB_PATH).getInputStream()) {
|
||||
searcher = Searcher.newWithBuffer(in.readAllBytes());
|
||||
} catch (Exception ex) {
|
||||
log.warn("ip2region 数据加载失败,IP 国家解析不可用: {}", ex.getMessage());
|
||||
} finally {
|
||||
loaded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return searcher;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ public class AppUserQueryReqVO {
|
||||
private String status;
|
||||
private String countryCode;
|
||||
private String registerSource;
|
||||
/** 客户端平台筛选:ANDROID / IOS / WEB,留空不限制;按最近一次会话的平台判定 */
|
||||
private String platform;
|
||||
private Integer pageIndex = 1;
|
||||
private Integer pageSize = 10;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ public class RegisterReqVO {
|
||||
private String password;
|
||||
|
||||
private String nickname;
|
||||
/** 客户端上报的设备区域(ISO-2),仅在服务端 IP 解析失败时作为兜底 */
|
||||
private String countryCode;
|
||||
private String deviceId;
|
||||
private String deviceModel;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Author: fruit.com.cn
|
||||
# ip2region 离线库数据版本追踪
|
||||
# 每次替换 ip2region.xdb 时更新此文件
|
||||
|
||||
version: 2.7.0
|
||||
updated: 2026-10-21
|
||||
source: org.lionsoul:ip2region:2.7.0
|
||||
xdb-path: fruitshorts-module-user/src/main/resources/ip2region/ip2region.xdb
|
||||
|
||||
# 覆盖范围:国家 + 省份 + 城市 + 运营商(IPv4)
|
||||
# 生产请留意:xdb 随 jar 打包约 11MB,admin-api 不解析 IP 但也会带上这份数据。
|
||||
# 后续可考虑用 Spring Profile + 条件装配,让 admin-api 不带 ip2region。
|
||||
Binary file not shown.
@@ -44,6 +44,7 @@
|
||||
<mybatis-plus.version>3.5.7</mybatis-plus.version>
|
||||
<jjwt.version>0.12.5</jjwt.version>
|
||||
<springdoc.version>2.5.0</springdoc.version>
|
||||
<ip2region.version>2.7.0</ip2region.version>
|
||||
<!-- Spring Boot 3.2 默认的 1.18.32 在 JDK 23+ 上会编译失败,这里提升到支持新 JDK 的版本 -->
|
||||
<lombok.version>1.18.48</lombok.version>
|
||||
</properties>
|
||||
@@ -130,6 +131,12 @@
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${springdoc.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.lionsoul</groupId>
|
||||
<artifactId>ip2region</artifactId>
|
||||
<version>${ip2region.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
-- 非付费互动支持 deviceId 归属;登录时由应用事务合并到账号。
|
||||
|
||||
ALTER TABLE content_like
|
||||
ADD COLUMN IF NOT EXISTS device_id VARCHAR(128) NOT NULL DEFAULT '';
|
||||
ALTER TABLE content_like
|
||||
ALTER COLUMN user_id DROP NOT NULL;
|
||||
DROP INDEX IF EXISTS uk_content_like;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_content_like_user
|
||||
ON content_like (user_id, target_type, target_id)
|
||||
WHERE user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_content_like_device
|
||||
ON content_like (device_id, target_type, target_id)
|
||||
WHERE user_id IS NULL AND device_id <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_content_like_device
|
||||
ON content_like (device_id, created_at DESC)
|
||||
WHERE device_id <> '';
|
||||
|
||||
ALTER TABLE user_favorite
|
||||
ADD COLUMN IF NOT EXISTS device_id VARCHAR(128) NOT NULL DEFAULT '';
|
||||
ALTER TABLE user_favorite
|
||||
ALTER COLUMN user_id DROP NOT NULL;
|
||||
DROP INDEX IF EXISTS uk_user_favorite;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_user_favorite_user
|
||||
ON user_favorite (user_id, drama_id)
|
||||
WHERE user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_user_favorite_device
|
||||
ON user_favorite (device_id, drama_id)
|
||||
WHERE user_id IS NULL AND device_id <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_user_favorite_device
|
||||
ON user_favorite (device_id, created_at DESC)
|
||||
WHERE device_id <> '';
|
||||
|
||||
ALTER TABLE content_comment
|
||||
ADD COLUMN IF NOT EXISTS device_id VARCHAR(128) NOT NULL DEFAULT '';
|
||||
ALTER TABLE content_comment
|
||||
ALTER COLUMN user_id DROP NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_device
|
||||
ON content_comment (device_id, created_at DESC)
|
||||
WHERE user_id IS NULL AND device_id <> '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_content_comment_user_content
|
||||
ON content_comment (
|
||||
user_id,
|
||||
drama_id,
|
||||
episode_id,
|
||||
parent_id,
|
||||
md5(content)
|
||||
)
|
||||
WHERE user_id IS NOT NULL AND deleted = 0 AND status <> 'deleted';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_content_comment_device_content
|
||||
ON content_comment (
|
||||
device_id,
|
||||
drama_id,
|
||||
episode_id,
|
||||
parent_id,
|
||||
md5(content)
|
||||
)
|
||||
WHERE user_id IS NULL AND device_id <> '' AND deleted = 0 AND status <> 'deleted';
|
||||
@@ -0,0 +1,24 @@
|
||||
-- 观看进度与观看流水支持 deviceId 归属;登录时由账号事务合并。
|
||||
|
||||
ALTER TABLE watch_progress
|
||||
ADD COLUMN IF NOT EXISTS device_id VARCHAR(128) NOT NULL DEFAULT '';
|
||||
ALTER TABLE watch_progress
|
||||
ALTER COLUMN user_id DROP NOT NULL;
|
||||
DROP INDEX IF EXISTS uk_watch_progress;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_watch_progress_user
|
||||
ON watch_progress (user_id, drama_id)
|
||||
WHERE user_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uk_watch_progress_device
|
||||
ON watch_progress (device_id, drama_id)
|
||||
WHERE user_id IS NULL AND device_id <> '';
|
||||
CREATE INDEX IF NOT EXISTS idx_watch_progress_device
|
||||
ON watch_progress (device_id, updated_at DESC)
|
||||
WHERE device_id <> '';
|
||||
|
||||
ALTER TABLE watch_history
|
||||
ADD COLUMN IF NOT EXISTS device_id VARCHAR(128) NOT NULL DEFAULT '';
|
||||
ALTER TABLE watch_history
|
||||
ALTER COLUMN user_id DROP NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_watch_history_device
|
||||
ON watch_history (device_id, watched_at DESC)
|
||||
WHERE user_id IS NULL AND device_id <> '';
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K107 后台收藏和点赞只读权限及菜单。
|
||||
BEGIN;
|
||||
INSERT INTO sys_permission (id, code, name, group_name, type, sort) VALUES
|
||||
(1106, 'favorite:list', '查看收藏', '用户管理', 'BUTTON', 106),
|
||||
(1107, 'like:list', '查看点赞', '用户管理', 'BUTTON', 107)
|
||||
ON CONFLICT (code) DO NOTHING;
|
||||
|
||||
INSERT INTO sys_role_permission (id, role_id, permission_id)
|
||||
SELECT r.id * 1000000 + p.id, r.id, p.id
|
||||
FROM sys_role r CROSS JOIN sys_permission p
|
||||
WHERE r.code = 'super_admin' AND p.code IN ('favorite:list', 'like:list')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO sys_menu (id, parent_id, title, route_path, route_name, component, redirect, icon,
|
||||
permission_code, type, always_show, affix, sort) VALUES
|
||||
(40, 15, '收藏列表', 'favorites', 'user-favorites', 'views/userManagement/FavoritesView',
|
||||
'', '', 'favorite:list', 'MENU', 0, 0, 3),
|
||||
(41, 15, '点赞列表', 'likes', 'user-likes', 'views/userManagement/LikesView',
|
||||
'', '', 'like:list', 'MENU', 0, 0, 4)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
INSERT INTO sys_role_menu (id, role_id, menu_id)
|
||||
SELECT r.id * 1000000 + m.id, r.id, m.id
|
||||
FROM sys_role r CROSS JOIN sys_menu m
|
||||
WHERE r.code = 'super_admin' AND m.id IN (40, 41)
|
||||
ON CONFLICT DO NOTHING;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K108 后台收藏/点赞列表按时间倒序的分页索引。
|
||||
-- 列表默认 ORDER BY created_at DESC, id DESC,且实体走逻辑删除(deleted = 0),
|
||||
-- 原有索引只覆盖 (user_id, created_at) / (device_id, created_at) 前缀,
|
||||
-- 不加筛选条件时会退化成全表扫描 + 排序。
|
||||
BEGIN;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_content_like_created
|
||||
ON content_like (created_at DESC, id DESC) WHERE deleted = 0;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_favorite_created
|
||||
ON user_favorite (created_at DESC, id DESC) WHERE deleted = 0;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K109 清理历史遗留的「按整部剧点赞」数据。
|
||||
-- 产品口径:收藏按剧,点赞与评论按集。客户端点赞入口只作用于当前剧集
|
||||
-- (targetType = EPISODE),以下 DRAMA 记录均为 2026-10-21 15:49 之前的旧模型遗留。
|
||||
BEGIN;
|
||||
|
||||
UPDATE content_like
|
||||
SET deleted = 1
|
||||
WHERE target_type = 'DRAMA' AND deleted = 0;
|
||||
|
||||
-- 剧级点赞数由这些行累加而来,随软删一并按实际剩余行数校准,避免详情页展示虚高数字。
|
||||
UPDATE drama d
|
||||
SET like_count = sub.cnt
|
||||
FROM (
|
||||
SELECT d2.id, COUNT(l.id) AS cnt
|
||||
FROM drama d2
|
||||
LEFT JOIN content_like l
|
||||
ON l.target_type = 'DRAMA' AND l.target_id = d2.id AND l.deleted = 0
|
||||
GROUP BY d2.id
|
||||
) sub
|
||||
WHERE d.id = sub.id AND d.like_count IS DISTINCT FROM sub.cnt;
|
||||
|
||||
COMMIT;
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user