Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
dragove committed Mar 30, 2024
2 parents 1e71dd4 + dbc2eb1 commit 134c7c5
Show file tree
Hide file tree
Showing 16 changed files with 111 additions and 85 deletions.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
distributionUrl=https\://mirrors.huaweicloud.com/gradle/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ package plus.maa.backend.common.utils.converter
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import plus.maa.backend.controller.request.copilotset.CopilotSetCreateReq
import plus.maa.backend.controller.response.copilotset.CopilotSetRes
import plus.maa.backend.controller.response.copilotset.CopilotSetListRes
import plus.maa.backend.controller.response.copilotset.CopilotSetRes
import plus.maa.backend.repository.entity.CopilotSet
import java.time.LocalDateTime

Expand All @@ -23,7 +23,6 @@ interface CopilotSetConverter {
@Mapping(target = "updateTime", expression = "java(LocalDateTime.now())")
fun convert(createReq: CopilotSetCreateReq, id: Long, creatorId: String): CopilotSet

@Mapping(target = "creator", ignore = true)
fun convert(copilotSet: CopilotSet, creator: String): CopilotSetListRes

fun convertDetail(copilotSet: CopilotSet, creator: String): CopilotSetRes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import org.springframework.web.server.ResponseStatusException
import plus.maa.backend.common.utils.IpUtil.getIpAddr
import plus.maa.backend.common.utils.IpUtil
import plus.maa.backend.service.jwt.JwtAuthToken
import plus.maa.backend.service.model.LoginUser
import java.util.*
Expand All @@ -35,39 +35,35 @@ class AuthenticationHelper {
*/
@Throws(ResponseStatusException::class)
fun requireUserId(): String {
val id = userId ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED)
return id
return obtainUserId() ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED)
}

val userId: String?
/**
* 获取用户 id
*
* @return 用户 id,如未验证则返回 null
*/
get() {
val auth = SecurityContextHolder.getContext().authentication ?: return null
if (auth is UsernamePasswordAuthenticationToken) {
val principal = auth.getPrincipal()
if (principal is LoginUser) return principal.userId
} else if (auth is JwtAuthToken) {
return auth.subject
}
return null
/**
* 获取用户 id
*
* @return 用户 id,如未验证则返回 null
*/
fun obtainUserId(): String? {
val auth = SecurityContextHolder.getContext().authentication ?: return null
if (auth is UsernamePasswordAuthenticationToken) {
val user = auth.getPrincipal() as? LoginUser
return user?.userId
} else if (auth is JwtAuthToken) {
return auth.subject
}
return null
}

val userIdOrIpAddress: String
/**
* 获取已验证用户 id 或者未验证用户 ip 地址。在 HTTP request 之外调用该方法获取 ip 会抛出 NPE
*
* @return 用户 id 或者 ip 地址
*/
get() {
val id = userId
if (id != null) return id
/**
* 获取已验证用户 id 或者未验证用户 ip 地址。在 HTTP request 之外调用该方法获取 ip 会抛出 [IllegalStateException]
*
* @return 用户 id 或者 ip 地址
*/
fun obtainUserIdOrIpAddress(): String {
val id = obtainUserId()
if (id != null) return id

val attributes = Objects.requireNonNull(RequestContextHolder.getRequestAttributes())
val request = (attributes as ServletRequestAttributes).request
return getIpAddr(request)
}
val request = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request
return checkNotNull(request).run(IpUtil::getIpAddr)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class CopilotController(
fun getCopilotById(
@Parameter(description = "作业id") @PathVariable("id") id: Long
): MaaResult<CopilotInfo?> {
val userIdOrIpAddress = helper.userIdOrIpAddress
val userIdOrIpAddress = helper.obtainUserIdOrIpAddress()
return copilotService.getCopilotById(userIdOrIpAddress, id)?.let { success(it) }
?: fail(404, "作业不存在")
}
Expand All @@ -76,7 +76,7 @@ class CopilotController(
): MaaResult<CopilotPageInfo> {
// 三秒防抖,缓解前端重复请求问题
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=3, must-revalidate")
return success(copilotService.queriesCopilot(helper.userId, parsed))
return success(copilotService.queriesCopilot(helper.obtainUserId(), parsed))
}

@Operation(summary = "更新作业")
Expand All @@ -95,7 +95,7 @@ class CopilotController(
@JsonSchema
@PostMapping("/rating")
fun ratesCopilotOperation(@RequestBody copilotRatingReq: CopilotRatingReq): MaaResult<String> {
copilotService.rates(helper.userIdOrIpAddress, copilotRatingReq)
copilotService.rates(helper.obtainUserIdOrIpAddress(), copilotRatingReq)
return success("评分成功")
}

Expand All @@ -104,7 +104,7 @@ class CopilotController(
@ApiResponse(description = "success")
@GetMapping("/status")
fun modifyStatus(@RequestParam id: @NotBlank Long, @RequestParam status: Boolean): MaaResult<String> {
copilotService.notificationStatus(helper.userId, id, status)
copilotService.notificationStatus(helper.obtainUserId(), id, status)
return success("success")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class CopilotSetController(
@ApiResponse(description = "作业集id")
@PostMapping("/query")
fun querySets(@RequestBody req: @Valid CopilotSetQuery): MaaResult<CopilotSetPageRes> {
return success(service.query(req))
return success(service.query(req, helper.obtainUserId()))
}

@Operation(summary = "查询作业集列表")
Expand All @@ -50,7 +50,7 @@ class CopilotSetController(
@RequireJwt
@PostMapping("/create")
fun createSet(@RequestBody req: @Valid CopilotSetCreateReq): MaaResult<Long> {
return success(service.create(req, helper.userId))
return success(service.create(req, helper.obtainUserId()))
}

@Operation(summary = "添加作业集作业列表")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class FileController(
@RequestPart(required = false) classification: String?,
@RequestPart(required = false) label: String
): MaaResult<String> {
fileService.uploadFile(file, type, version, classification, label, helper.userIdOrIpAddress)
fileService.uploadFile(file, type, version, classification, label, helper.obtainUserIdOrIpAddress())
return success("上传成功,数据已被接收")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,11 @@ data class CopilotSetQuery (
) Int = 10,

@Schema(title = "查询关键词")
val keyword: String? = null
val keyword: String? = null,

@Schema(title = "创建者id")
val creatorId: String? = null,

@Schema(title = "需要包含的作业id列表")
val copilotIds: List<Long>? = null
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package plus.maa.backend.controller.response.copilotset

import io.swagger.v3.oas.annotations.media.Schema
import plus.maa.backend.service.model.CopilotSetStatus
import java.time.LocalDateTime

/**
Expand All @@ -24,9 +25,15 @@ data class CopilotSetListRes (
@Schema(title = "上传者昵称")
val creator: String,

@Schema(title = "作业状态", enumAsRef = true)
val status: CopilotSetStatus,

@Schema(title = "创建时间")
val createTime: LocalDateTime,

@Schema(title = "更新时间")
val updateTime: LocalDateTime
val updateTime: LocalDateTime,

@Schema(title = "作业id列表")
val copilotIds: List<Long>
)
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ data class CopilotSetPageRes (
@Schema(title = "是否有下一页")
val hasNext: Boolean = false,

@Schema(title = "当前页码")
@Schema(title = "总页数")
val page: Int = 0,

@Schema(title = "总数据量")
Expand Down
8 changes: 0 additions & 8 deletions src/main/kotlin/plus/maa/backend/repository/entity/MaaUser.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import org.springframework.data.annotation.Id
import org.springframework.data.annotation.Transient
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.Document
import plus.maa.backend.controller.request.user.UserInfoUpdateDTO
import java.io.Serializable

/**
Expand All @@ -25,13 +24,6 @@ data class MaaUser(
var refreshJwtIds: MutableList<String> = ArrayList()
) : Serializable {

fun updateAttribute(updateDTO: UserInfoUpdateDTO) {
val userName = updateDTO.userName
if (userName.isNotBlank()) {
this.userName = userName
}
}

companion object {
@Transient
val UNKNOWN: MaaUser = MaaUser(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package plus.maa.backend.repository.entity.gamedata

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.PropertyNamingStrategies.LowerCamelCaseStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming

// 小驼峰
@JsonNaming(LowerCamelCaseStrategy::class)
// 忽略对服务器无用的数据
@JsonIgnoreProperties(ignoreUnknown = true)
data class MaaArkStage(
Expand Down
48 changes: 39 additions & 9 deletions src/main/kotlin/plus/maa/backend/service/CopilotSetService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import cn.hutool.core.lang.Assert
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.support.PageableExecutionUtils
import org.springframework.stereotype.Service
import plus.maa.backend.common.utils.IdComponent
import plus.maa.backend.common.utils.converter.CopilotSetConverter
Expand All @@ -18,7 +22,9 @@ import plus.maa.backend.repository.UserRepository
import plus.maa.backend.repository.entity.CopilotSet
import plus.maa.backend.repository.entity.MaaUser
import plus.maa.backend.repository.findByUsersId
import plus.maa.backend.service.model.CopilotSetStatus
import java.time.LocalDateTime
import java.util.regex.Pattern

private val log = KotlinLogging.logger { }

Expand All @@ -32,6 +38,7 @@ class CopilotSetService(
private val converter: CopilotSetConverter,
private val repository: CopilotSetRepository,
private val userRepository: UserRepository,
private val mongoTemplate: MongoTemplate
) {

private val defaultSort: Sort = Sort.by("id").descending()
Expand Down Expand Up @@ -103,24 +110,47 @@ class CopilotSetService(
repository.save(copilotSet)
}

fun query(req: CopilotSetQuery): CopilotSetPageRes {
fun query(req: CopilotSetQuery, userId: String?): CopilotSetPageRes {
val pageRequest = PageRequest.of(req.page - 1, req.limit, defaultSort)

val keyword = req.keyword
val copilotSets = if (keyword.isNullOrBlank()) {
repository.findAll(pageRequest)
} else {
repository.findByKeyword(keyword, pageRequest)
val criteria = Criteria.where("status").`is`(CopilotSetStatus.PUBLIC)
val query = Query.query(
if (userId.isNullOrBlank()) {
criteria
} else {
Criteria().orOperator(criteria, Criteria.where("creatorId").`is`(userId))
}.and("delete").`is`(false)
).with(pageRequest)
if (!req.copilotIds.isNullOrEmpty()) {
query.addCriteria(Criteria.where("copilotIds").all(req.copilotIds)).with(pageRequest)
}

if (!req.creatorId.isNullOrBlank()) {
query.addCriteria(Criteria.where("creatorId").`is`(req.creatorId))
}
if (!req.keyword.isNullOrBlank()) {
val pattern = Pattern.compile(req.keyword, Pattern.CASE_INSENSITIVE)
query.addCriteria(
Criteria().orOperator(
Criteria.where("name").regex(pattern),
Criteria.where("description").regex(pattern)
)
)
}
val copilotSets =
PageableExecutionUtils.getPage(mongoTemplate.find(query, CopilotSet::class.java), pageRequest) {
mongoTemplate.count(
query.limit(-1).skip(-1),
CopilotSet::class.java
)
}
val userIds = copilotSets
.map { obj: CopilotSet -> obj.creatorId }
.distinct()
.toList()
val userById = userRepository.findByUsersId(userIds)
return CopilotSetPageRes(
copilotSets.totalPages > req.page,
copilotSets.number + 1,
copilotSets.hasNext(),
copilotSets.totalPages,
copilotSets.totalElements,
copilotSets.map { cs: CopilotSet ->
val user = userById.getOrDefault(cs.creatorId, MaaUser.UNKNOWN)
Expand Down
30 changes: 11 additions & 19 deletions src/main/kotlin/plus/maa/backend/service/UserService.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package plus.maa.backend.service

import org.springframework.beans.BeanUtils
import org.springframework.dao.DuplicateKeyException
import org.springframework.data.repository.findByIdOrNull
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import plus.maa.backend.common.MaaStatusCode
Expand Down Expand Up @@ -78,9 +78,7 @@ class UserService(
originPassword: String? = null,
verifyOriginPassword: Boolean = true
) {
val userResult = userRepository.findById(userId)
if (userResult.isEmpty) return
val maaUser = userResult.get()
val maaUser = userRepository.findByIdOrNull(userId) ?: return
if (verifyOriginPassword) {
check(!originPassword.isNullOrEmpty()) {
"请输入原密码"
Expand All @@ -102,27 +100,22 @@ class UserService(
* @return 返回注册成功的用户摘要(脱敏)
*/
fun register(registerDTO: RegisterDTO): MaaUserInfo {
val encode = passwordEncoder.encode(registerDTO.password)

// 校验验证码
emailService.verifyVCode(registerDTO.email, registerDTO.registrationToken)

val encoded = passwordEncoder.encode(registerDTO.password)

val user = MaaUser(
userName = registerDTO.userName,
email = registerDTO.email,
password = registerDTO.password
password = encoded,
status = 1,
)
BeanUtils.copyProperties(registerDTO, user)
user.password = encode
user.status = 1
val userInfo: MaaUserInfo
try {
val save = userRepository.save(user)
userInfo = MaaUserInfo(save)
return try {
userRepository.save(user).run(::MaaUserInfo)
} catch (e: DuplicateKeyException) {
throw MaaResultException(MaaStatusCode.MAA_USER_EXISTS)
}
return userInfo
}

/**
Expand All @@ -132,10 +125,9 @@ class UserService(
* @param updateDTO 更新参数
*/
fun updateUserInfo(userId: String, updateDTO: UserInfoUpdateDTO) {
userRepository.findById(userId).ifPresent { maaUser: MaaUser ->
maaUser.updateAttribute(updateDTO)
userRepository.save(maaUser)
}
val maaUser = userRepository.findByIdOrNull(userId) ?: return
maaUser.userName = updateDTO.userName
userRepository.save(maaUser)
}

/**
Expand Down
Loading

0 comments on commit 134c7c5

Please sign in to comment.