Compare commits
10
Commits
7baaeddf26
...
272aa62434
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
272aa62434 | ||
|
|
a41ab18636 | ||
|
|
8999ff395d | ||
|
|
229f1d0198 | ||
|
|
2dadca6288 | ||
|
|
2cf8f9a1c3 | ||
|
|
d9a1670a72 | ||
|
|
5ff4626b33 | ||
|
|
6bbde0b100 | ||
|
|
884324b8fd |
No files matched your search
@@ -19,3 +19,4 @@ data/uploads/*
|
||||
|
||||
# 部署用的真实环境变量(含密钥),只提交 .env.example
|
||||
.env
|
||||
dump.rdb
|
||||
+6
-4
@@ -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 计数,不新建计数表)。
|
||||
|
||||
@@ -863,13 +865,13 @@ 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/favorites/page` | `favorite:list` | 收藏只读分页,含游客 |
|
||||
| GET | `/admin/likes/page` | `like:list` | 点赞只读分页,含游客及多态目标 |
|
||||
| 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 |
|
||||
|
||||
状态处置会**立即吊销该用户全部会话**并写入封禁记录,避免"封了还能用"。
|
||||
|
||||
+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 的动态路由一致。 */
|
||||
|
||||
+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()) {
|
||||
|
||||
+45
@@ -9,13 +9,19 @@ 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;
|
||||
@@ -35,6 +41,9 @@ public class EngagementAdminLookup {
|
||||
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) {
|
||||
@@ -96,6 +105,42 @@ public class EngagementAdminLookup {
|
||||
.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();
|
||||
}
|
||||
|
||||
+38
-4
@@ -10,7 +10,9 @@ 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;
|
||||
@@ -34,6 +36,10 @@ public class FavoriteAdminService {
|
||||
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)
|
||||
@@ -41,8 +47,22 @@ public class FavoriteAdminService {
|
||||
.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())
|
||||
.orderByDesc(UserFavorite::getCreatedAt, UserFavorite::getId);
|
||||
.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()));
|
||||
}
|
||||
@@ -53,17 +73,31 @@ public class FavoriteAdminService {
|
||||
}
|
||||
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.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) {
|
||||
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) {
|
||||
|
||||
+43
-4
@@ -14,7 +14,9 @@ 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;
|
||||
@@ -67,6 +69,23 @@ public class LikeAdminService {
|
||||
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()));
|
||||
}
|
||||
@@ -80,6 +99,8 @@ public class LikeAdminService {
|
||||
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()));
|
||||
}
|
||||
@@ -92,8 +113,7 @@ public class LikeAdminService {
|
||||
.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())
|
||||
.orderByDesc(ContentLike::getCreatedAt, ContentLike::getId);
|
||||
.le(req.getEndTime() != null, ContentLike::getCreatedAt, req.getEndTime());
|
||||
}
|
||||
|
||||
private List<AdminLikeVO> assemble(List<ContentLike> rows) {
|
||||
@@ -110,7 +130,13 @@ public class LikeAdminService {
|
||||
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);
|
||||
return rows.stream().map(row -> toVo(row, users, comments, episodes, dramas)).toList();
|
||||
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) {
|
||||
@@ -130,12 +156,25 @@ public class LikeAdminService {
|
||||
}
|
||||
|
||||
private AdminLikeVO toVo(ContentLike row, Map<Long, AppUser> users, Map<Long, ContentComment> comments,
|
||||
Map<Long, DramaEpisode> episodes, Map<Long, Drama> dramas) {
|
||||
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());
|
||||
|
||||
+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());
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ public class AdminFavoriteVO {
|
||||
private String uid;
|
||||
private String nickname;
|
||||
private String deviceId;
|
||||
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||
private String platform;
|
||||
private Boolean anonymous;
|
||||
private Long dramaId;
|
||||
private String dramaTitle;
|
||||
|
||||
@@ -13,6 +13,8 @@ public class AdminLikeVO {
|
||||
private String uid;
|
||||
private String nickname;
|
||||
private String deviceId;
|
||||
/** 客户端平台:ANDROID / IOS / WEB,来自设备平台记录,游客同样有值。 */
|
||||
private String platform;
|
||||
private Boolean anonymous;
|
||||
private Long dramaId;
|
||||
private String dramaTitle;
|
||||
|
||||
@@ -16,6 +16,8 @@ public class EngagementQueryReqVO {
|
||||
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)
|
||||
|
||||
+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}
|
||||
|
||||
+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() {
|
||||
|
||||
+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 字符串输出而不是数组,
|
||||
|
||||
+6
-4
@@ -35,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();
|
||||
}
|
||||
|
||||
@@ -50,7 +51,7 @@ public class AppAuthController {
|
||||
public Result<TokenRespVO> register(@Valid @RequestBody RegisterReqVO req,
|
||||
HttpServletRequest request) {
|
||||
applyHeaderDeviceId(req, request);
|
||||
return Result.ok(authService.register(req, WebUtils.getClientIp(request)));
|
||||
return Result.ok(authService.register(req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "登录(验证码或密码)")
|
||||
@@ -59,7 +60,7 @@ public class AppAuthController {
|
||||
public Result<TokenRespVO> login(@Valid @RequestBody LoginReqVO req,
|
||||
HttpServletRequest request) {
|
||||
applyHeaderDeviceId(req, request);
|
||||
return Result.ok(authService.login(req, WebUtils.getClientIp(request)));
|
||||
return Result.ok(authService.login(req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "Google 登录(未配置 clientId 时返回明确错误)")
|
||||
@@ -69,7 +70,8 @@ public class AppAuthController {
|
||||
String headerDeviceId = request.getHeader("X-Device-Id");
|
||||
String deviceId = StringUtils.hasText(headerDeviceId)
|
||||
? headerDeviceId : req.getDeviceId();
|
||||
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId));
|
||||
return Result.ok(authService.googleLogin(req.getIdToken(), deviceId,
|
||||
webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "刷新令牌(旧 refresh token 立即失效)")
|
||||
|
||||
+2
-1
@@ -48,6 +48,7 @@ public class AppCommentController {
|
||||
private final EpisodeService episodeService;
|
||||
private final InteractionIdentityResolver identityResolver;
|
||||
private final AnonymousInteractionRateLimiter anonymousRateLimiter;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
@Operation(summary = "发布评论")
|
||||
@PostMapping
|
||||
@@ -59,7 +60,7 @@ public class AppCommentController {
|
||||
req.getDeviceId());
|
||||
anonymousRateLimiter.check(identity, "comment");
|
||||
return Result.ok(commentService.publish(
|
||||
identity, req, WebUtils.getClientIp(request)));
|
||||
identity, req, webUtils.clientIp(request)));
|
||||
}
|
||||
|
||||
@Operation(summary = "评论列表(游标翻页,可匿名浏览)")
|
||||
|
||||
+2
-1
@@ -37,6 +37,7 @@ public class AppDramaController {
|
||||
private final EpisodeService episodeService;
|
||||
private final CommentService commentService;
|
||||
private final AppEpisodeStatsService appEpisodeStatsService;
|
||||
private final WebUtils webUtils;
|
||||
|
||||
/** 详情:包含剧集列表,客户端进详情页一次请求即可渲染 */
|
||||
@Operation(summary = "短剧详情(含剧集列表,进详情页一次请求即可渲染)")
|
||||
@@ -56,7 +57,7 @@ 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));
|
||||
|
||||
+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();
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -51,7 +51,8 @@ class AppCatalogControllerContractTest {
|
||||
dramaMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppDramaController(catalogService, mock(PlaybackService.class),
|
||||
mock(EpisodeService.class), mock(CommentService.class),
|
||||
mock(AppEpisodeStatsService.class)));
|
||||
mock(AppEpisodeStatsService.class),
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ class AppCommentControllerContractTest {
|
||||
commentService,
|
||||
episodeService,
|
||||
mock(InteractionIdentityResolver.class),
|
||||
mock(AnonymousInteractionRateLimiter.class)));
|
||||
mock(AnonymousInteractionRateLimiter.class),
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-3
@@ -234,7 +234,8 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
commentService,
|
||||
episodeService,
|
||||
identityResolver,
|
||||
rateLimiter);
|
||||
rateLimiter,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -303,7 +304,8 @@ class AppCommentCountAnonymousSecurityTest {
|
||||
mock(PlaybackService.class),
|
||||
episodeService,
|
||||
commentService,
|
||||
appEpisodeStatsService);
|
||||
appEpisodeStatsService,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -340,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
|
||||
|
||||
+2
-1
@@ -54,7 +54,8 @@ class AppPlaybackContractTest {
|
||||
given(commentService.countByEpisodes(any())).willReturn(Map.of());
|
||||
mockMvc = ControllerContractSupport.mockMvcOf(
|
||||
new AppDramaController(mock(AppCatalogService.class), playbackService,
|
||||
episodeService, commentService, episodeStatsService));
|
||||
episodeService, commentService, episodeStatsService,
|
||||
mock(com.fruitshorts.framework.web.WebUtils.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+44
-4
@@ -22,6 +22,7 @@ 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;
|
||||
@@ -67,6 +68,7 @@ class AppAuthServiceTest {
|
||||
private ConfigService configService;
|
||||
private GoogleIdTokenVerifier googleVerifier;
|
||||
private ApplicationEventPublisher eventPublisher;
|
||||
private IpRegionService ipRegionService;
|
||||
private AppAuthService authService;
|
||||
|
||||
@BeforeEach
|
||||
@@ -83,11 +85,14 @@ class AppAuthServiceTest {
|
||||
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, eventPublisher);
|
||||
googleVerifier, eventPublisher, ipRegionService);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -264,6 +269,41 @@ class AppAuthServiceTest {
|
||||
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
|
||||
void should_reject_login_when_password_does_not_match() {
|
||||
stubLogin(credential("bcrypt-hash"), user(AppUserStatus.NORMAL));
|
||||
@@ -318,7 +358,7 @@ class AppAuthServiceTest {
|
||||
});
|
||||
given(userMapper.selectById(any())).willAnswer(invocation -> inserted.get());
|
||||
|
||||
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9");
|
||||
TokenRespVO resp = authService.googleLogin("google-id-token", "device-9", "203.0.113.9");
|
||||
|
||||
assertThat(resp.getAccessToken()).isEqualTo("access-1");
|
||||
assertThat(resp.isNewUser()).isTrue();
|
||||
@@ -333,7 +373,7 @@ class AppAuthServiceTest {
|
||||
given(googleVerifier.verify(anyString()))
|
||||
.willReturn(new GoogleUser("sub-1", "", "Alice", ""));
|
||||
|
||||
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9"))
|
||||
assertThatThrownBy(() -> authService.googleLogin("google-id-token", "device-9", "203.0.113.9"))
|
||||
.isInstanceOf(ServiceException.class)
|
||||
.hasMessage("Google 账号未返回邮箱,无法登录");
|
||||
}
|
||||
@@ -392,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, eventPublisher);
|
||||
googleVerifier, eventPublisher, ipRegionService);
|
||||
}
|
||||
|
||||
private void setRegisterLimits(int perIp, int perDevice) {
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
+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();
|
||||
}
|
||||
}
|
||||
+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 字符串输出而不是数组,
|
||||
|
||||
+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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
}
|
||||
}
|
||||
@@ -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 : "";
|
||||
}
|
||||
}
|
||||
+64
-14
@@ -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;
|
||||
@@ -66,6 +67,7 @@ public class AppAuthService {
|
||||
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}")
|
||||
@@ -178,6 +180,7 @@ 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());
|
||||
|
||||
@@ -194,7 +197,7 @@ public class AppAuthService {
|
||||
* 再落一条 GOOGLE 凭证用于下次直接登录;已有邮箱账号时只补 GOOGLE 凭证,不重复建号。
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public TokenRespVO googleLogin(String idToken, String deviceId) {
|
||||
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);
|
||||
@@ -203,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;
|
||||
@@ -219,10 +222,11 @@ 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);
|
||||
touchDevice(user.getId(), deviceId, null, null);
|
||||
TokenRespVO resp = issueTokens(user, googleCredential, deviceId, null, null, null, null, null);
|
||||
TokenRespVO resp = issueTokens(user, googleCredential, deviceId, null, null, null, null, clientIp);
|
||||
resp.setNewUser(newUser);
|
||||
requestInteractionMerge(user.getId(), deviceId);
|
||||
return resp;
|
||||
@@ -238,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())
|
||||
@@ -246,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("");
|
||||
@@ -527,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("");
|
||||
@@ -549,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,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;
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K110 校准互动计数字段。
|
||||
-- 历史压测数据把部分计数直接改成 100000 量级,与真实行数不符;
|
||||
-- 这里按实际有效互动行重算剧集点赞数与剧收藏数,可重复执行。
|
||||
BEGIN;
|
||||
|
||||
-- 剧集点赞数 = 该集未删除的 EPISODE 点赞行数
|
||||
UPDATE drama_episode e
|
||||
SET like_count = sub.cnt
|
||||
FROM (
|
||||
SELECT e2.id, COUNT(l.id) AS cnt
|
||||
FROM drama_episode e2
|
||||
LEFT JOIN content_like l
|
||||
ON l.target_type = 'EPISODE' AND l.target_id = e2.id AND l.deleted = 0
|
||||
GROUP BY e2.id
|
||||
) sub
|
||||
WHERE e.id = sub.id AND e.like_count IS DISTINCT FROM sub.cnt;
|
||||
|
||||
-- 剧收藏数 = 该剧未删除的收藏行数
|
||||
UPDATE drama d
|
||||
SET favorite_count = sub.cnt
|
||||
FROM (
|
||||
SELECT d2.id, COUNT(f.id) AS cnt
|
||||
FROM drama d2
|
||||
LEFT JOIN user_favorite f ON f.drama_id = d2.id AND f.deleted = 0
|
||||
GROUP BY d2.id
|
||||
) sub
|
||||
WHERE d.id = sub.id AND d.favorite_count IS DISTINCT FROM sub.cnt;
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K111 设备平台:记录每个 device_id 是 iOS 还是 Android。
|
||||
-- 会话/设备表都依赖已登录账号,游客行为拿不到平台;这里按 device_id 独立建档,
|
||||
-- 只存平台,系统版本与机型不上报。
|
||||
BEGIN;
|
||||
|
||||
DROP TABLE IF EXISTS app_device_profile;
|
||||
|
||||
CREATE TABLE app_device_profile (
|
||||
id BIGINT NOT NULL,
|
||||
device_id VARCHAR(128) NOT NULL,
|
||||
platform VARCHAR(16) NOT NULL DEFAULT '',
|
||||
first_seen_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_seen_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
deleted SMALLINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
-- 不带 deleted 谓词:写入用的 ON CONFLICT (device_id) 需要能推断到唯一索引;
|
||||
-- 设备平台不做软删,重复建档走更新。
|
||||
CREATE UNIQUE INDEX uk_app_device_profile_device
|
||||
ON app_device_profile (device_id);
|
||||
|
||||
COMMENT ON TABLE app_device_profile IS '设备平台:device_id 维度区分 iOS/Android,匿名请求同样记录';
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K112 观看记录默认列表的排序索引。
|
||||
-- 后台按 watched_at DESC, id DESC 倒序翻页,原有索引都以 user_id/drama_id/device_id 开头,
|
||||
-- 不带筛选条件时只能全表扫描再排序;补一条时间索引让翻页直接走索引。
|
||||
-- watch_history 是分区表,在父表建索引会自动下发到各分区。
|
||||
BEGIN;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_watch_history_watched_at
|
||||
ON watch_history (watched_at DESC, id DESC);
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Author: fruit.com.cn
|
||||
-- K113 app_user_session 按「最近一次」平台筛选用户的索引。
|
||||
--
|
||||
-- selectUserIdsByLatestPlatform 用的是 DISTINCT ON (user_id) ... ORDER BY user_id, last_active_at DESC NULLS LAST, id DESC。
|
||||
-- 原表只有 (user_id, revoked_at) 索引,DISTINCT ON + ORDER BY 退化成全表 Sort + Seq Scan,
|
||||
-- 500 行还行,10 万行就扛不住了。补一个匹配 ORDER BY 的部分索引:deleted = 0 覆盖逻辑删除。
|
||||
--
|
||||
-- 注意:CREATE INDEX CONCURRENTLY 不能在事务块里执行,这里直接跑,不加 BEGIN/COMMIT。
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_session_user_latest
|
||||
ON app_user_session (user_id, last_active_at DESC NULLS LAST, id DESC)
|
||||
WHERE deleted = 0;
|
||||
Reference in new issue
Block a user