content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.author
import cn.llonvne.entity.Author
import cn.llonvne.kvision.service.exception.AuthorAuthenticationUserIdNotExist
import cn.llonvne.kvision.service.exception.AuthorNotExist
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.query.map
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class AuthorRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
private val authenticationService: AuthenticationUserRepository
) {
private val authorMeta = Meta.author
suspend fun create(author: Author): Author {
// 检查 authenticationUserId 是否有效
isAuthenticationUserIdValid(author)
return db.runQuery {
QueryDsl.insert(authorMeta).single(author)
}
}
suspend fun isAuthorIdExist(id: Int): Boolean {
return db.runQuery {
QueryDsl.from(authorMeta)
.where {
authorMeta.authorId eq id
}.singleOrNull().map {
it != null
}
}
}
@Throws(AuthorNotExist::class)
suspend fun getByIdOrThrow(id: Int): Author {
return db.runQuery {
QueryDsl.from(authorMeta)
.where {
authorMeta.authorId eq id
}.singleOrNull().map {
it ?: throw AuthorNotExist()
}
}
}
suspend fun getByIdOrNull(id: Int?): Author? {
if (id == null) {
return null
}
return db.runQuery {
QueryDsl.from(authorMeta)
.where {
authorMeta.authorId eq id
}.singleOrNull()
}
}
private suspend fun isAuthenticationUserIdValid(author: Author) {
val id = author.authenticationUserId
// 如果 ID 为空,则不做检查
if (id != null) {
val isUserExistQuery = authenticationService.isIdExist(id)
if (!isUserExistQuery) {
throw AuthorAuthenticationUserIdNotExist()
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/AuthorRepository.kt | 952755645 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.problem.language
import cn.llonvne.database.entity.def.problem.problem
import cn.llonvne.database.entity.def.problem.tag.problemTag
import cn.llonvne.database.entity.problemSupportLanguage
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.ProblemTag
import cn.llonvne.entity.problem.context.Problem
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.operator.count
import org.komapper.core.dsl.operator.lower
import org.komapper.core.dsl.query.flatMap
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Service
@Service
class ProblemRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
) {
private val problemMeta = Meta.problem
private val problemTagMeta = Meta.problemTag
private val problemLanguageMeta = Meta.problemSupportLanguage
private val languageMeta = Meta.language
suspend fun isIdExist(id: Int?): Boolean {
if (id == null) {
return false
}
return db.runQuery {
QueryDsl.from(problemMeta).where {
problemMeta.problemId eq id
}.select(count())
} != 0.toLong()
}
suspend fun list(limit: Int = 500): List<Problem> = db.runQuery {
QueryDsl.from(problemMeta)
.limit(limit)
}
suspend fun getById(id: Int?): Problem? {
if (id == null) {
return null
}
return db.runQuery {
QueryDsl.from(problemMeta)
.where {
problemMeta.problemId eq id
}.singleOrNull()
}
}
suspend fun getProblemTags(problemId: Int): List<ProblemTag> = db.runQuery {
QueryDsl.from(problemTagMeta).where {
problemTagMeta.problemId eq problemId
}
}
suspend fun getSupportLanguage(problemId: Int, limit: Int = 500): List<Language> {
val q1 = QueryDsl.from(problemLanguageMeta).where {
problemLanguageMeta.problemId eq problemId
}
val q2 = q1.flatMap {
QueryDsl.from(languageMeta).where {
languageMeta.languageId inList it.map { it.languageId }
}
}
return db.runQuery { q2 }
}
suspend fun search(text: String): List<Problem> {
val toInt = text.toIntOrNull()
val lowerText = text.lowercase()
return db.runQuery {
QueryDsl.from(problemMeta)
.where {
or {
lower(problemMeta.problemName) contains lowerText
}
or {
lower(problemMeta.problemDescription) contains lowerText
}
if (toInt != null) {
or {
problemMeta.problemId eq toInt
}
or {
problemMeta.authorId eq toInt
}
}
}
}
}
suspend fun create(problem: Problem) = db.runQuery {
QueryDsl.insert(problemMeta).single(problem)
}
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/ProblemRepository.kt | 4075030679 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.contest
import cn.llonvne.entity.contest.Contest
import kotlinx.datetime.*
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.operator.count
import org.komapper.core.dsl.query.map
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Repository
import kotlin.time.Duration
@Repository
class ContestRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase
) {
private val contestMeta = Meta.contest
suspend fun create(contest: Contest): Contest {
return db.runQuery {
QueryDsl.insert(contestMeta).single(contest).returning()
}
}
suspend fun getById(id: Int): Contest? {
return db.runQuery {
QueryDsl.from(contestMeta).where {
contestMeta.contestId eq id
}.singleOrNull()
}
}
suspend fun getByHash(hash: String): Contest? {
return db.runQuery {
QueryDsl.from(contestMeta).where {
contestMeta.hashLink eq hash
}.singleOrNull()
}
}
suspend fun lastTwoWeekCount(): Int {
val today = Clock.System.now()
val last = today.minus(14, DateTimeUnit.DAY, TimeZone.currentSystemDefault()).toLocalDateTime(
TimeZone.currentSystemDefault()
)
return db.runQuery {
QueryDsl.from(contestMeta).where {
contestMeta.createdAt greaterEq last
}.select(count()).map {
it?.toInt() ?: 0
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/ContestRepository.kt | 1144943052 |
package cn.llonvne.database.aware
import cn.llonvne.database.aware.GroupInfoAwareProvider.GroupInfoAware
import cn.llonvne.database.resolver.group.GroupMembersResolver
import cn.llonvne.database.resolver.group.GroupRoleResolver
import cn.llonvne.entity.group.Group
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.GroupMemberDtoImpl
import org.springframework.stereotype.Service
/**
* 提供小组相关信息(不包括在 [Group] 内部的),一般通过 [GroupInfoAware] 作为 context 作为接收器参数
*/
@Service
class GroupInfoAwareProvider(
private val groupMembersResolver: GroupMembersResolver,
private val groupRoleResolver: GroupRoleResolver
) {
suspend fun <R> awareOf(groupId: GroupId, id: Int, group: Group, action: suspend GroupInfoAware.() -> R): R {
return GroupInfoAware(groupId, id, group).action()
}
inner class GroupInfoAware(
val groupId: GroupId,
val id: Int,
val group: Group
) {
suspend fun ownerName(): String {
return groupMembersResolver.fromRole(GroupOwner.GroupOwnerImpl(id)).firstOrNull()?.username ?: "<未找到>"
}
suspend fun membersOfGuest(): List<GroupMemberDtoImpl> {
return groupMembersResolver.fromGroupId(id).mapNotNull {
GroupMemberDtoImpl(
username = it.username,
role = groupRoleResolver.resolve(id, it) ?: return@mapNotNull null,
userId = it.id
)
}
}
suspend fun memberOfManager(): List<GroupMemberDtoImpl> {
return membersOfGuest()
}
suspend fun membersOfMember(): List<GroupMemberDtoImpl> {
return membersOfGuest()
}
suspend fun membersOfOwner() = membersOfMember()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/aware/GroupInfoAwareProvider.kt | 457826783 |
package cn.llonvne.database.aware
import cn.llonvne.database.repository.ProblemRepository
import cn.llonvne.entity.problem.context.Problem
import org.springframework.stereotype.Service
@Service
class ProblemAwareProvider(
private val problemRepository: ProblemRepository
) {
suspend fun <R> awareOf(
problem: Problem,
action: suspend context(ProblemAwarer) () -> R
): R {
val problemAwarer = ProblemAwarer(problem = problem)
return action(problemAwarer)
}
inner class ProblemAwarer(
val problem: Problem
)
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/aware/ProblemAwareProvider.kt | 2212906953 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.exts.now
import cn.llonvne.security.normalUserRole
import kotlinx.datetime.LocalDateTime
import org.springframework.security.crypto.password.PasswordEncoder
/**
* 创建新用户使用的函数,时间将自动设置为现在的时间
*/
context(PasswordEncoder)
fun AuthenticationUser.Companion.createAtNow(
username: String, rawPassword: String
) = AuthenticationUser(
username = username,
encryptedPassword = encode(rawPassword),
createdAt = LocalDateTime.now(),
updatedAt = LocalDateTime.now(),
role = normalUserRole()
)
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/AuthenticationUserExts.kt | 31570653 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeCommentType
import org.komapper.annotation.*
@KomapperEntityDef(entity = Code::class)
private data class CodeDef(
@KomapperId @KomapperAutoIncrement
val codeId: Nothing,
val authenticationUserId: Nothing,
val code: Nothing,
val languageId: Nothing,
val codeType: Nothing,
val visibilityType: Nothing,
val commentType: CodeCommentType,
val hashLink: String? = null,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Nothing,
@KomapperCreatedAt
val createdAt: Nothing,
@KomapperUpdatedAt
val updatedAt: Nothing
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/CodeDef.kt | 3596938471 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.group.Group
import cn.llonvne.entity.group.GroupType
import cn.llonvne.entity.group.GroupVisibility
import kotlinx.datetime.LocalDateTime
import org.komapper.annotation.*
@KomapperEntityDef(entity = Group::class)
@KomapperTable(name = "_group")
/**
* group 被 PostgresSQL 作为关键字故更改为 _group
* [cn.llonvne.entity.group.Group]
*/
private data class GroupDef(
@KomapperId
@KomapperAutoIncrement
val groupId: Int? = null,
val groupName: String,
val groupShortName: String,
val groupHash: String,
val visibility: GroupVisibility,
val type: GroupType,
val description: String,
@KomapperVersion
val version: Int? = null,
@KomapperCreatedAt
val createdAt: LocalDateTime? = null,
@KomapperUpdatedAt
val updatedAt: LocalDateTime? = null
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/GroupDef.kt | 1295735705 |
package cn.llonvne.database.entity.def.problem
import cn.llonvne.entity.problem.Language
import org.komapper.annotation.KomapperAutoIncrement
import org.komapper.annotation.KomapperEntityDef
import org.komapper.annotation.KomapperId
@KomapperEntityDef(entity = Language::class)
private data class LanguageDef(
@KomapperId @KomapperAutoIncrement
val languageId: Int,
val languageName: String,
val languageVersion: String
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/problem/LanguageDef.kt | 1416701612 |
@file:Suppress("unused")
package cn.llonvne.database.entity.def.problem
import cn.llonvne.entity.problem.Submission
import org.komapper.annotation.*
@KomapperEntityDef(entity = Submission::class)
private class SubmissionDef(
@KomapperId
@KomapperAutoIncrement
val submissionId: Nothing,
val problemId: Nothing,
val codeId: Nothing,
// 用户 ID
val authenticationUserId: Nothing,
// 可见性
val visibility: Nothing,
val contestId: Int?,
val status: Nothing,
// 以 Json 形式存在内部
val judgeResult: Nothing,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Nothing,
@KomapperCreatedAt
val createdAt: Nothing,
@KomapperUpdatedAt
val updatedAt: Nothing
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/problem/SubmissionDef.kt | 2505652023 |
package cn.llonvne.database.entity.def.problem
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.kvision.service.IProblemService.CreateProblemReq
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
private val json = Json
fun Problem.Companion.fromCreateReq(createProblemReq: CreateProblemReq, ownerId: Int) =
Problem(
authorId = createProblemReq.authorId,
problemName = createProblemReq.problemName,
memoryLimit = createProblemReq.memoryLimit,
timeLimit = createProblemReq.timeLimit,
problemDescription = createProblemReq.problemDescription,
visibility = createProblemReq.visibility,
type = createProblemReq.type,
contextJson = json.encodeToString(createProblemReq.problemContext),
ownerId = ownerId
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/problem/ProblemExts.kt | 418731745 |
package cn.llonvne.database.entity.def.problem
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemType
import cn.llonvne.entity.problem.context.ProblemVisibility
import org.komapper.annotation.*
@KomapperEntityDef(Problem::class)
private data class ProblemDef(
// 题目 ID
@KomapperId @KomapperAutoIncrement
val problemId: Nothing,
// 作者 ID
val authorId: Nothing,
val ownerId: Int,
// 题目名字
val problemName: Nothing,
// 题目描述
val problemDescription: Nothing,
// 时间限制
val timeLimit: Nothing,
// 内存限制
val memoryLimit: Nothing,
val visibility: ProblemVisibility,
val type: ProblemType,
val contextJson: String,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Nothing,
@KomapperCreatedAt
val createdAt: Nothing,
@KomapperUpdatedAt
val updatedAt: Nothing,
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/problem/ProblemDef.kt | 3038855467 |
package cn.llonvne.database.entity.def.problem.tag
import cn.llonvne.entity.problem.ProblemTag
import cn.llonvne.entity.types.badge.BadgeColor
import kotlinx.datetime.LocalDateTime
import org.komapper.annotation.*
@KomapperEntityDef(ProblemTag::class)
private data class ProblemTagDef(
@KomapperId @KomapperAutoIncrement
val problemTagId: Nothing,
val problemId: Int,
val tag: String,
val color: BadgeColor,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Int? = null,
@KomapperCreatedAt
val createdAt: LocalDateTime? = null,
@KomapperUpdatedAt
val updatedAt: LocalDateTime? = null
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/problem/tag/ProblemTagDef.kt | 4166876433 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.AuthenticationUser
import org.komapper.annotation.*
@KomapperEntityDef(AuthenticationUser::class)
private data class AuthenticationUserDef(
@KomapperId @KomapperAutoIncrement
val id: Nothing,
val username: Nothing,
val encryptedPassword: Nothing,
val role: Nothing,
@KomapperVersion
val version: Nothing,
@KomapperCreatedAt
val createdAt: Nothing,
@KomapperUpdatedAt
val updatedAt: Nothing,
)
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/AuthenticationUserDef.kt | 6712115 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.contest.Contest
import kotlinx.datetime.LocalDateTime
import org.komapper.annotation.*
@KomapperEntityDef(entity = Contest::class)
private data class ContestDef(
@KomapperId @KomapperAutoIncrement
val contestId: Int = -1,
val ownerId: Int,
val title: String,
val description: String = "",
val contestScoreType: Contest.ContestScoreType,
val startAt: LocalDateTime,
val endAt: LocalDateTime,
val rankType: Contest.ContestRankType,
val groupId: Int? = null,
val contextStr: String,
val hashLink: String,
@KomapperVersion
val version: Int? = null,
@KomapperCreatedAt
val createdAt: LocalDateTime? = null,
@KomapperUpdatedAt
val updatedAt: LocalDateTime? = null
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/Contest.kt | 1510771165 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.Author
import org.komapper.annotation.*
@KomapperEntityDef(Author::class)
private data class AuthorDef(
@KomapperId @KomapperAutoIncrement
val authorId: Nothing,
val authorName: Nothing,
val introduction: Nothing,
val authenticationUserId: Int? = null,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Nothing,
@KomapperCreatedAt
val createdAt: Nothing,
@KomapperUpdatedAt
val updatedAt: Nothing
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/AuthorDef.kt | 61022566 |
package cn.llonvne.database.entity.def
import cn.llonvne.entity.problem.ShareCodeComment
import kotlinx.datetime.LocalDateTime
import org.komapper.annotation.*
@KomapperEntityDef(ShareCodeComment::class)
private data class ShareCodeCommentDef(
@KomapperId @KomapperAutoIncrement
val commentId: Int? = null,
val committerAuthenticationUserId: Int,
val shareCodeId: Int,
val content: String,
val type: Nothing,
//--- 数据库信息区 ---//
@KomapperVersion
val version: Int? = null,
@KomapperCreatedAt
val createdAt: LocalDateTime? = null,
@KomapperUpdatedAt
val updatedAt: LocalDateTime? = null
) | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/def/ShareCodeComment.kt | 1819649087 |
package cn.llonvne.database.entity
import org.komapper.annotation.KomapperAutoIncrement
import org.komapper.annotation.KomapperEntity
import org.komapper.annotation.KomapperId
@KomapperEntity
data class ProblemSupportLanguage(
@KomapperId @KomapperAutoIncrement
val problemSupportId: Int? = null,
val problemId: Int,
val languageId: Int
)
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/entity/ProblemSupportLanguage.kt | 2658200915 |
package cn.llonvne.database.schema
import cn.llonvne.database.entity.def.problem.language
import cn.llonvne.entity.problem.Language
import cn.llonvne.gojudge.api.SupportLanguages
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.query.andThen
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Component
@Component
private class SupportLanguagesSyncer : SchemaInitializer {
private val languageMeta = Meta.language
override suspend fun init(db: R2dbcDatabase) {
val languages = SupportLanguages.entries.map {
Language(
it.languageId,
it.languageName,
it.languageVersion
)
}
db.runQuery {
QueryDsl.drop(languageMeta)
.andThen(
QueryDsl.create(languageMeta)
)
.andThen(
QueryDsl.insert(languageMeta).multiple(languages)
)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/schema/SupportLanguagesSyncer.kt | 992518797 |
package cn.llonvne.database.schema
import org.komapper.r2dbc.R2dbcDatabase
fun interface SchemaInitializer {
suspend fun init(db: R2dbcDatabase)
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/schema/SchemaInitializer.kt | 873208668 |
package cn.llonvne.database.schema
import kotlinx.coroutines.runBlocking
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
@Component
class Schema(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
private val schemaInitializer: List<SchemaInitializer>
) : ApplicationRunner {
override fun run(args: ApplicationArguments?) {
runBlocking {
db.runQuery {
QueryDsl.create(Meta.all())
}
schemaInitializer.forEach {
it.init(db)
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/schema/Schema.kt | 3848028604 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.aware.GroupInfoAwareProvider
import cn.llonvne.database.aware.GroupInfoAwareProvider.GroupInfoAware
import cn.llonvne.database.repository.GroupRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.*
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.*
import org.springframework.stereotype.Service
@Service
class GroupLoadResolver(
private val groupRepository: GroupRepository,
private val groupRoleResolver: GroupRoleResolver,
private val guestPasser: GroupGuestPassResolver,
private val groupInfoAwareProvider: GroupInfoAwareProvider
) {
suspend fun resolve(
originGroupId: GroupId,
groupId: Int,
authenticationUser: AuthenticationUser?
): LoadGroupResp {
val group = groupRepository.fromId(groupId) ?: return GroupIdNotFound(originGroupId)
return groupInfoAwareProvider.awareOf(originGroupId, groupId, group) {
if (authenticationUser == null) {
return@awareOf loadAsGuestOrReject()
}
val teamRole = groupRoleResolver.resolve(groupId, authenticationUser)
?: return@awareOf loadAsGuestOrReject()
return@awareOf when (teamRole) {
is DeleteTeam.DeleteTeamImpl -> loadAsGuestOrReject()
is GroupManager.GroupMangerImpl -> loadAsGroupManager()
is InviteMember.InviteMemberImpl -> loadAsGuestOrReject()
is KickMember.KickMemberImpl -> loadAsGuestOrReject()
is TeamMember.TeamMemberImpl -> loadAsMember()
is TeamSuperManager -> loadAsSuperManager()
is GroupOwner -> loadAsOwner()
is GroupManager -> loadAsGroupManager()
}
}
}
context(GroupInfoAware)
suspend fun loadAsGuestOrReject(): LoadGroupResp {
return guestPasser.resolve {
return@resolve GuestLoadGroup(
groupId = groupId,
groupName = group.groupName,
groupShortName = group.groupShortName,
visibility = group.visibility,
type = group.type,
ownerName = ownerName(),
members = membersOfGuest(),
description = group.description,
createAt = group.createdAt!!
)
}
}
context(GroupInfoAware)
suspend fun loadAsGroupManager(): LoadGroupResp {
return ManagerLoadGroup(
groupId = groupId,
groupName = group.groupName,
groupShortName = group.groupShortName,
visibility = group.visibility,
type = group.type,
ownerName = ownerName(),
members = memberOfManager(),
description = group.description,
createAt = group.createdAt!!
)
}
context(GroupInfoAware)
suspend fun loadAsMember(): LoadGroupResp {
return MemberLoadGroup(
groupId = groupId,
groupName = group.groupName,
groupShortName = group.groupShortName,
visibility = group.visibility,
type = group.type,
ownerName = ownerName(),
members = membersOfMember(),
description = group.description,
createAt = group.createdAt!!
)
}
context(GroupInfoAware)
suspend fun loadAsSuperManager(): LoadGroupResp {
TODO()
}
context(GroupInfoAware)
suspend fun loadAsOwner(): LoadGroupResp {
return OwnerLoadGroup(
groupId = groupId,
groupName = group.groupName,
groupShortName = group.groupShortName,
visibility = group.visibility,
type = group.type,
ownerName = ownerName(),
members = membersOfOwner(),
description = group.description,
createAt = group.createdAt!!
)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupLoadResolver.kt | 2132461189 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.repository.GroupRepository
import cn.llonvne.database.resolver.group.JoinGroupVisibilityCheckResolver.JoinGroupVisibilityCheckResult.*
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.entity.role.TeamMember
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.JoinGroupResp
import cn.llonvne.kvision.service.RoleService
import org.springframework.stereotype.Service
@Service
class JoinGroupResolver(
private val groupRepository: GroupRepository,
private val visibilityCheckResolver: JoinGroupVisibilityCheckResolver,
private val roleService: RoleService,
private val groupMembersResolver: GroupMembersResolver
) {
suspend fun resolve(groupId: GroupId, id: Int, authenticationUser: AuthenticationUser): JoinGroupResp {
val group = groupRepository.fromId(id) ?: return GroupIdNotFound(groupId)
return when (visibilityCheckResolver.resolve(
group.visibility, groupId
)) {
Accepted -> accept(authenticationUser, id, groupId)
Waiting -> waiting(id, groupId)
Rejected -> reject(groupId)
}
}
private suspend fun reject(groupId: GroupId): JoinGroupResp {
return JoinGroupResp.Reject(groupId)
}
private suspend fun accept(authenticationUser: AuthenticationUser, id: Int, groupId: GroupId): JoinGroupResp {
roleService.addRole(authenticationUser.id, TeamMember.TeamMemberImpl(id))
return JoinGroupResp.Joined(groupId)
}
private suspend fun waiting(id: Int, groupId: GroupId): JoinGroupResp {
// 找到组管理员
val managers = groupMembersResolver.fromRoles(TeamIdRole.getManagerRoles(id))
if (managers.isEmpty()) {
return JoinGroupResp.NoManagersFound(groupId = groupId)
} else {
TODO()
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/JoinGroupResolver.kt | 4100043077 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.resolver.group.JoinGroupVisibilityCheckResolver.JoinGroupVisibilityCheckResult.*
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.group.GroupVisibility
import org.springframework.stereotype.Service
/**
* 检查 [GroupVisibility] 与 [GroupId] 的关系并确定是否允许加入/审批加入,遵从 [GroupVisibility.chinese] 的说明
*/
@Service
class JoinGroupVisibilityCheckResolver {
/**
* [Accepted] 直接加入
* [Waiting] 发送申请
* [Rejected] 拒绝加入
*/
enum class JoinGroupVisibilityCheckResult {
Accepted, Waiting, Rejected
}
fun resolve(
visibility: GroupVisibility, groupId: GroupId
): JoinGroupVisibilityCheckResult {
return when (visibility) {
GroupVisibility.Public -> Accepted
GroupVisibility.Private -> Rejected
GroupVisibility.Restrict -> onRestrict(groupId)
}
}
private fun onRestrict(groupId: GroupId): JoinGroupVisibilityCheckResult {
return when (groupId) {
is GroupId.HashGroupId -> Accepted
is GroupId.IntGroupId -> Waiting
is GroupId.ShortGroupName -> Waiting
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/JoinGroupVisibilityCheckResolver.kt | 3368134004 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.resolver.group.GroupMemberUpgradeResolver.GroupMemberUpgradeResult.*
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.kvision.service.RoleService
import org.springframework.stereotype.Service
@Service
class GroupMemberUpgradeResolver(
private val roleService: RoleService
) {
enum class GroupMemberUpgradeResult {
UpdateToIdNotMatchToGroupId,
UserAlreadyHasThisRole,
BeUpdatedUserNotFound,
Success
}
suspend fun resolve(
groupId: GroupId,
groupIntId: Int,
updater: AuthenticationUser,
beUpdatedUserId: Int,
updateTo: TeamIdRole
): GroupMemberUpgradeResult {
if (updateTo.teamId != groupIntId) {
return UpdateToIdNotMatchToGroupId
}
val beUpdatedUserRole = roleService.get(beUpdatedUserId) ?: return BeUpdatedUserNotFound
if (beUpdatedUserRole.roles.contains(updateTo)) {
return UserAlreadyHasThisRole
}
return if (roleService.addRole(beUpdatedUserId, updateTo)){
Success
} else {
BeUpdatedUserNotFound
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupMemberUpgradeResolver.kt | 14834698 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.aware.GroupInfoAwareProvider.GroupInfoAware
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.group.GroupVisibility
import cn.llonvne.entity.group.GroupVisibility.*
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.PermissionDenied
import org.springframework.stereotype.Service
/**
* 用于确定在以未登入用户加载小组信息时是否显示,遵从 [GroupVisibility] 的说明
*/
@Service
class GroupGuestPassResolver {
context(GroupInfoAware)
suspend fun resolve(
loadAsGuest: suspend () -> LoadGroupResp
): LoadGroupResp {
return when (group.visibility) {
Public -> loadAsGuest()
Private -> {
PermissionDenied
}
Restrict -> {
when (groupId) {
is GroupId.HashGroupId -> loadAsGuest()
is GroupId.IntGroupId -> PermissionDenied
is GroupId.ShortGroupName -> PermissionDenied
}
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupGuestPassResolver.kt | 2622957490 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.repository.GroupRepository
import cn.llonvne.entity.group.GroupId
import org.springframework.stereotype.Service
/**
* 将 [GroupId] 转换为 数字ID 并保证该ID存在,否则返回 null
*/
@Service
class GroupIdResolver(
private val groupRepository: GroupRepository
) {
suspend fun resolve(groupId: GroupId): Int? {
val intId = when (groupId) {
is GroupId.HashGroupId -> fromHashGroupId(groupId.id)
is GroupId.IntGroupId -> groupId.id
is GroupId.ShortGroupName -> fromShortName(groupId.shortName)
}
return validateGroupId(intId)
}
private suspend fun validateGroupId(id: Int?): Int? {
if (id == null) {
return null
}
return if (groupRepository.isIdExist(id)) {
id
} else {
null
}
}
private suspend fun fromHashGroupId(hash: String): Int? {
return groupRepository.fromHashToId(hash)
}
private suspend fun fromShortName(shortname: String): Int? {
return groupRepository.fromShortname(shortname)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupIdResolver.kt | 3615758495 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.security.asJson
import cn.llonvne.security.check
import cn.llonvne.security.userRole
import org.springframework.stereotype.Service
/**
* 用于从用户表查找对应权限的成员
*/
@Service
class GroupMembersResolver(private val userRepository: AuthenticationUserRepository) {
/**
* 查找一个具有[TeamIdRole]且匹配[TeamIdRole.teamId]的成员
* @param need 需要的权限
* @return 匹配的成员
* 该函数使用精确匹配在数据库内部查询权限,速度较快
*/
suspend fun fromRole(need: TeamIdRole): List<AuthenticationUser> {
val str = need.asJson
val matchedUser = userRepository.matchRoleStr(str).filter { user -> user.check(need) }
return matchedUser
}
/**
* 查找一个具有[oneOf]中任何一个权限的成员并且匹配[TeamIdRole.teamId]
* @param oneOf 需要的权限集合(匹配其中一个即可)
* @return 匹配的成员
* 该函数首先查找所有具有 [TeamIdRole.teamId] 权限的成员,然后再筛选出匹配的成员
*/
suspend fun fromRoles(oneOf: List<TeamIdRole>): List<AuthenticationUser> {
val groupId = oneOf.firstOrNull()?.teamId ?: return emptyList()
val allMembers = fromGroupId(groupId)
return allMembers.filter { user -> oneOf.any { role -> user.check(role) } }
}
/**
* 查找所有具有 [TeamIdRole.teamId] 权限的成员
*/
suspend fun fromGroupId(groupId: Int): List<AuthenticationUser> {
val matchedUser = userRepository.matchRoleStr(""""teamId":$groupId""".trimIndent()).filter {
it.userRole.roles.filterIsInstance<TeamIdRole>().any { idRole -> idRole.teamId == groupId }
}
return matchedUser
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupMembersResolver.kt | 2227292904 |
package cn.llonvne.database.resolver.group
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.GroupManager
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.kvision.service.IGroupService.KickGroupResp
import cn.llonvne.kvision.service.IGroupService.KickGroupResp.*
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import cn.llonvne.kvision.service.RoleService
import cn.llonvne.security.check
import org.springframework.stereotype.Service
@Service
class GroupKickResolver(
private val userRepository: AuthenticationUserRepository,
private val roleService: RoleService
) {
suspend fun resolve(
groupId: GroupId,
groupIntId: Int,
kicker: AuthenticationUser,
kickedId: Int
): KickGroupResp {
val kicked = userRepository.getByIdOrNull(kickedId) ?: return KickMemberNotFound(kickedId)
val kickedRole =
roleService.get(kickedId)?.groupIdRoles(groupIntId) ?: return KickMemberGroupIdRoleFound(kickedId, groupId)
return if (kickedRole.filterIsInstance<GroupManager>().isNotEmpty()) {
if (!kicker.check(GroupOwner.GroupOwnerImpl(groupIntId))) {
PermissionDeniedWithMessage("您没有权限踢出管理员")
} else {
doKick(kicked, kickedRole)
}
} else {
doKick(kicked, kickedRole)
}
}
private suspend fun doKick(
kicked: AuthenticationUser,
kickedRole: List<TeamIdRole>
): Kicked {
roleService.removeRole(kicked, kickedRole)
return Kicked
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupKickResolver.kt | 2570789654 |
package cn.llonvne.database.resolver.group
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.DeleteTeam.DeleteTeamImpl
import cn.llonvne.entity.role.GroupManager.GroupMangerImpl
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.entity.role.InviteMember.InviteMemberImpl
import cn.llonvne.entity.role.KickMember.KickMemberImpl
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.entity.role.TeamMember.TeamMemberImpl
import cn.llonvne.entity.role.TeamSuperManager
import cn.llonvne.kvision.service.RoleService
import org.springframework.stereotype.Service
@Service
class GroupRoleResolver(
private val roleService: RoleService,
) {
private val highest: (TeamIdRole) -> Int = {
when (it) {
is DeleteTeamImpl -> 0
is GroupMangerImpl -> 100
is InviteMemberImpl -> 0
is KickMemberImpl -> 0
is TeamMemberImpl -> 50
is TeamSuperManager -> 1000
is GroupOwner -> 10000
}
}
suspend fun resolve(groupId: Int, authenticationUser: AuthenticationUser): TeamIdRole? {
val role = roleService.get(authenticationUser.id)?.roles ?: return null
return role.filterIsInstance<TeamIdRole>()
.filter { it.teamId == groupId || it is TeamSuperManager }
.sortedByDescending(highest).firstOrNull()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupRoleResolver.kt | 1407616973 |
package cn.llonvne.database.resolver.group
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.GroupManager
import cn.llonvne.kvision.service.RoleService
import org.springframework.stereotype.Service
@Service
class GroupMangerDowngradeResolver(
private val roleService: RoleService
) {
enum class GroupManagerDowngradeResult {
DowngradeToIdNotMatchToGroupId,
BeDowngradeUserNotFound,
UserAlreadyHasThisRole,
Success
}
suspend fun resolve(
groupId: GroupId,
groupIntId: Int,
operator: AuthenticationUser,
beDowngradeUserId: Int,
): GroupManagerDowngradeResult {
val beDowngradeUserRole =
roleService.get(beDowngradeUserId) ?: return GroupManagerDowngradeResult.BeDowngradeUserNotFound
val removedRoles = beDowngradeUserRole.roles.filterIsInstance<GroupManager.GroupMangerImpl>()
return if (roleService.removeRole(beDowngradeUserId, removedRoles)) {
GroupManagerDowngradeResult.Success
} else {
GroupManagerDowngradeResult.BeDowngradeUserNotFound
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/group/GroupMangerDowngradeResolver.kt | 2335994661 |
package cn.llonvne.database.resolver.code
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.kvision.service.CodeService
import cn.llonvne.security.AuthenticationToken
import kotlinx.serialization.Serializable
import org.springframework.stereotype.Service
@Service
class GetCodeSafetyCheckResolver(
) {
@Serializable
sealed interface GetCodeSafetyCheckResult<out R> {
data object PermissionDenied : GetCodeSafetyCheckResult<Nothing>
data class GetCodeSafetyCheckPassed<R>(val result: R) : GetCodeSafetyCheckResult<R>
}
suspend fun <R> resolve(
getCodeId: CodeService.GetCodeId,
code: Code,
value: AuthenticationToken?,
onPass: () -> R
): GetCodeSafetyCheckResult<R> {
TODO()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/code/GetCodeSafetyCheckResolver.kt | 4026719975 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.Backend
import cn.llonvne.getLogger
import cn.llonvne.kvision.service.IAuthenticationService
import cn.llonvne.security.check
import org.springframework.stereotype.Service
@Service
class MineRoleCheckResolver(
private val backendMineResolver: BackendMineResolver,
private val normalMineResolver: NormalMineResolver
) {
private val logger = getLogger()
suspend fun resolve(user: AuthenticationUser): IAuthenticationService.MineResp {
logger.info("用户${user.id} 读取个人界面,检查 Backend 权限")
return if (user.check(Backend.BackendImpl)) {
logger.info("用户${user.id} 拥有 Backend 权限,读取后台界面")
backendMineResolver.resolve(user)
} else {
logger.info("用户${user.id} 未拥有 Backend 权限,读取个人界面")
normalMineResolver.resolve(user)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/MineRoleCheckResolver.kt | 2527400440 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.kvision.service.IAuthenticationService
import org.springframework.stereotype.Service
@Service
class BackendMineResolver {
suspend fun resolve(user: AuthenticationUser): IAuthenticationService.MineResp {
return IAuthenticationService.MineResp.AdministratorMineResp(Unit)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/BackendMineResolver.kt | 1111617255 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.kvision.service.IMineService
import cn.llonvne.kvision.service.IMineService.DashboardResp.JudgeServerInfo
import cn.llonvne.kvision.service.JudgeService
import org.springframework.stereotype.Service
@Service
class JudgeServerInfoResolver(
private val judgeService: JudgeService
) {
suspend fun resolve(): JudgeServerInfo {
return judgeService.info().let {
JudgeServerInfo(
name = it.name,
host = it.host,
port = it.port,
cpuCoresCount = it.cpuCoresCount,
cpuUsage = it.cpuUsage,
isOnline = it.isOnline,
memoryUsage = it.memoryUsage
)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/JudgeServerInfoResolver.kt | 3199532581 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.database.repository.ContestRepository
import cn.llonvne.database.repository.SubmissionRepository
import cn.llonvne.exts.now
import cn.llonvne.kvision.service.IMineService
import cn.llonvne.kvision.service.IMineService.DashboardResp.OnlineJudgeStatistics
import kotlinx.datetime.*
import org.springframework.stereotype.Service
@Service
class OnlineJudgeStatisticsResolver(
private val userRepository: AuthenticationUserRepository,
private val submissionRepository: SubmissionRepository,
private val contestRepository: ContestRepository
) {
suspend fun resolve(): OnlineJudgeStatistics {
val todayEnd = LocalDateTime.now()
val todayStart = todayEnd.toJavaLocalDateTime().minusDays(1).toKotlinLocalDateTime()
return OnlineJudgeStatistics(
totalUserCount = userRepository.count(),
totalSubmissionToday = submissionRepository.getByTimeRange(
todayStart,
todayEnd
).size,
totalContestLastTwoWeek = contestRepository.lastTwoWeekCount()
)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/OnlineJudgeStatisticsResolver.kt | 1734877903 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.database.repository.SubmissionRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.entity.problem.Submission
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.exts.now
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.toKotlinLocalDateTime
import org.springframework.stereotype.Service
@Service
class UserSubmissionRangeResolver(
private val submissionRepository: SubmissionRepository
) {
suspend fun resolve(
authenticationUser: AuthenticationUser,
from: LocalDateTime,
to: LocalDateTime = LocalDateTime.now()
): List<Submission> {
return submissionRepository.getByAuthenticationUserID(
authenticationUser.id,
codeType = Code.CodeType.Problem
)
.filter {
it.createdAt != null && it.createdAt in from..to
}
}
suspend fun acceptedIn(user: AuthenticationUser, days: Long): Int {
return resolve(
user, java.time.LocalDateTime.now().minusDays(days).toKotlinLocalDateTime()
).filter {
it.result is ProblemJudgeResult
}.count {
(it.result as ProblemJudgeResult).passerResult.pass
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/UserSubmissionRangeResolver.kt | 1024368770 |
package cn.llonvne.database.resolver.mine
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.exts.now
import cn.llonvne.kvision.service.IAuthenticationService
import cn.llonvne.kvision.service.IAuthenticationService.MineResp.NormalUserMineResp
import cn.llonvne.ll
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.toKotlinLocalDateTime
import org.springframework.stereotype.Service
@Service
class NormalMineResolver(
private val userSubmissionRangeResolver: UserSubmissionRangeResolver
) {
suspend fun resolve(user: AuthenticationUser): IAuthenticationService.MineResp {
return coroutineScope {
val total = async {
userSubmissionRangeResolver.resolve(
user, java.time.LocalDateTime.MIN.toKotlinLocalDateTime()
).filter {
it.result is ProblemJudgeResult
}.count {
(it.result as ProblemJudgeResult).passerResult.pass
}
}
val at7Days = async { userSubmissionRangeResolver.acceptedIn(user, 7) }
val atToday = async { userSubmissionRangeResolver.acceptedIn(user, 1) }
val at30Day = async { userSubmissionRangeResolver.acceptedIn(user, 30) }
return@coroutineScope NormalUserMineResp(
user.username, user.createdAt?.ll() ?: LocalDateTime.now().ll(),
acceptedTotal = total.await(),
accepted7Days = at7Days.await(),
acceptedToday = atToday.await(),
accepted30Days = at30Day.await()
)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/NormalMineResolver.kt | 3857128120 |
@file:Suppress("SpringJavaInjectionPointsAutowiringInspection")
package cn.llonvne.database.resolver.mine
import cn.llonvne.kvision.service.IMineService.DashboardResp.BackendInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.springframework.core.env.Environment
import org.springframework.stereotype.Service
import java.lang.management.ManagementFactory
import java.net.InetAddress
@Service
class BackendInfoResolver(
env: Environment,
private val backendName: String = env.getProperty("oj.name") ?: throw RuntimeException("后端未定义"),
private val port: String = env.getProperty("server.port") ?: "8080",
private val runtime: Runtime = Runtime.getRuntime()
) {
private val availableProcessors by lazy {
runtime.availableProcessors()
}
suspend fun resolve(): BackendInfo {
return BackendInfo(
name = backendName,
host = withContext(Dispatchers.IO) {
InetAddress.getLocalHost()
}.hostAddress,
port = port,
cpuCoresCount = availableProcessors,
cpuUsage = ManagementFactory.getOperatingSystemMXBean().systemLoadAverage,
usedMemory = runtime.maxMemory().toInt() - runtime.freeMemory().toInt(),
totalMemory = runtime.maxMemory().toInt(),
isOnline = true
)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/mine/BackendInfoResolver.kt | 433187092 |
package cn.llonvne.database.resolver.contest
import cn.llonvne.database.repository.ContestRepository
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.contest.HashId
import cn.llonvne.entity.contest.IntId
import org.springframework.stereotype.Service
@Service
class ContestIdGetResolver(
private val contestRepository: ContestRepository
) {
suspend fun resolve(id: ContestId): Contest? {
return when (id) {
is HashId -> contestRepository.getByHash(id.hash)
is IntId -> contestRepository.getById(id.id)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/contest/ContestIdGetResolver.kt | 3150083110 |
package cn.llonvne.database.resolver.contest
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemVisibility.*
import org.springframework.stereotype.Service
@Service
class ContestProblemVisibilityCheckResolver {
enum class ContestProblemVisibilityCheckResult {
Pass,
Reject
}
fun check(authenticationUser: AuthenticationUser, problem: Problem): ContestProblemVisibilityCheckResult {
return when (problem.visibility) {
Public -> ContestProblemVisibilityCheckResult.Pass
Private -> {
if (authenticationUser.id == problem.ownerId) {
ContestProblemVisibilityCheckResult.Pass
} else {
ContestProblemVisibilityCheckResult.Reject
}
}
Restrict -> {
ContestProblemVisibilityCheckResult.Reject
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/contest/ContestProblemVisibilityCheckResolver.kt | 2300791959 |
package cn.llonvne.database.resolver.authentication
import org.springframework.stereotype.Service
@Service
class BannedUsernameCheckResolver {
private val bannedUsernameKeyWords = listOf("admin")
enum class BannedUsernameCheckResult {
Pass,
Failed
}
fun resolve(username: String): BannedUsernameCheckResult {
bannedUsernameKeyWords.forEach { bannedKeyWord ->
if (username.lowercase().contains(bannedKeyWord)) {
return BannedUsernameCheckResult.Failed
}
}
return BannedUsernameCheckResult.Pass
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/authentication/BannedUsernameCheckResolver.kt | 2124663009 |
package cn.llonvne.database.resolver.submission
import cn.llonvne.database.aware.ProblemAwareProvider
import cn.llonvne.database.repository.ProblemRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemType.Group
import cn.llonvne.entity.problem.context.ProblemType.Individual
import cn.llonvne.kvision.service.ISubmissionService.*
import org.springframework.stereotype.Service
@Service
class ProblemSubmissionPassResolver(
private val problemRepository: ProblemRepository,
private val groupProblemPassResolver: GroupProblemPassResolver,
private val individualProblemPassResolver: IndividualProblemPassResolver,
private val problemAwareProvider: ProblemAwareProvider
) {
suspend fun resolve(
authenticationUser: AuthenticationUser,
problemSubmissionReq: ProblemSubmissionReq,
onPass: suspend (Problem) -> ProblemSubmissionResp
): ProblemSubmissionResp {
val problem = problemRepository.getById(problemSubmissionReq.problemId) ?: return ProblemNotFound
// 如果是以 Contest 形式提交,则无需检查群组/个人权限
if (problemSubmissionReq.contestId != null) {
return onPass(problem)
}
// 否则检查权限
return problemAwareProvider.awareOf(problem) {
when (problem.type) {
Individual -> individualProblemPassResolver.resolve(
authenticationUser, problemSubmissionReq, onPass
)
Group -> groupProblemPassResolver.resolve(
authenticationUser, problemSubmissionReq, onPass
)
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/submission/ProblemSubmissionPassResolver.kt | 1540411506 |
package cn.llonvne.database.resolver.submission
import cn.llonvne.database.repository.CodeRepository
import cn.llonvne.database.repository.SubmissionRepository
import cn.llonvne.database.resolver.contest.ContestIdGetResolver
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.entity.problem.Submission
import cn.llonvne.entity.problem.SubmissionStatus
import cn.llonvne.entity.problem.SubmissionVisibilityType.*
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeVisibilityType
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionReq
import org.springframework.stereotype.Service
@Service
class ProblemSubmissionPersistenceResolver(
private val codeRepository: CodeRepository,
private val submissionRepository: SubmissionRepository,
private val contestIdGetResolver: ContestIdGetResolver
) {
sealed interface ProblemSubmissionPersistenceResult {
data class Success(val submissionId: Int, val codeId: Int) : ProblemSubmissionPersistenceResult
data object NotNeedToPersist : ProblemSubmissionPersistenceResult
data class Failed(val reason: String) : ProblemSubmissionPersistenceResult
}
suspend fun resolve(
user: AuthenticationUser,
result: ISubmissionService.ProblemSubmissionRespNotPersist,
problemSubmissionReq: ProblemSubmissionReq,
language: SupportLanguages
): ProblemSubmissionPersistenceResult {
if (problemSubmissionReq.contestId != null) {
return persistAsContestSubmission(
user,
result,
problemSubmissionReq,
language,
contestId = problemSubmissionReq.contestId
)
}
return persist(user, result, problemSubmissionReq, language)
}
private suspend fun persistAsContestSubmission(
user: AuthenticationUser,
result: ISubmissionService.ProblemSubmissionRespNotPersist,
problemSubmissionReq: ProblemSubmissionReq,
language: SupportLanguages,
contestId: ContestId
): ProblemSubmissionPersistenceResult {
val code = codeRepository.save(
Code(
codeId = null,
authenticationUserId = user.id,
code = problemSubmissionReq.code,
codeType = Code.CodeType.Problem,
languageId = problemSubmissionReq.languageId,
visibilityType = CodeVisibilityType.Restrict,
commentType = CodeCommentType.ContestCode,
)
)
if (code.codeId == null) {
return ProblemSubmissionPersistenceResult.Failed("Code 在持久化后 id 仍然为空·")
}
val passerResult = result.problemTestCases.passer.pass(result.submissionTestCases)
val submission = submissionRepository.save(
Submission(
submissionId = null,
authenticationUserId = user.id,
codeId = code.codeId,
judgeResult = ProblemJudgeResult(
result.problemTestCases,
result.submissionTestCases,
passerResult = passerResult
).json(),
problemId = problemSubmissionReq.problemId,
status = SubmissionStatus.Finished,
contestId = contestIdGetResolver.resolve(contestId)?.contestId
?: return ProblemSubmissionPersistenceResult.Failed("无效的 ContestId")
)
)
if (submission.submissionId == null) {
return ProblemSubmissionPersistenceResult.Failed("Submission 在持久后 id 仍然为空")
}
return ProblemSubmissionPersistenceResult.Success(
submissionId = submission.submissionId,
codeId = code.codeId
)
}
private suspend fun persist(
user: AuthenticationUser,
result: ISubmissionService.ProblemSubmissionRespNotPersist,
problemSubmissionReq: ProblemSubmissionReq,
language: SupportLanguages
): ProblemSubmissionPersistenceResult {
val code = codeRepository.save(
Code(
codeId = null,
authenticationUserId = user.id,
code = problemSubmissionReq.code,
codeType = Code.CodeType.Problem,
languageId = problemSubmissionReq.languageId,
visibilityType = when (problemSubmissionReq.visibilityType) {
PUBLIC -> CodeVisibilityType.Public
PRIVATE -> CodeVisibilityType.Private
Contest -> CodeVisibilityType.Restrict
}
)
)
if (code.codeId == null) {
return ProblemSubmissionPersistenceResult.Failed("Code 在持久化后 id 仍然为空·")
}
val passerResult = result.problemTestCases.passer.pass(result.submissionTestCases)
val submission = submissionRepository.save(
Submission(
submissionId = null,
authenticationUserId = user.id,
codeId = code.codeId,
judgeResult = ProblemJudgeResult(
result.problemTestCases,
result.submissionTestCases,
passerResult = passerResult
).json(),
problemId = problemSubmissionReq.problemId,
status = SubmissionStatus.Finished,
contestId = if (problemSubmissionReq.contestId == null) {
null
} else {
contestIdGetResolver.resolve(problemSubmissionReq.contestId)?.contestId
}
)
)
if (submission.submissionId == null) {
return ProblemSubmissionPersistenceResult.Failed("Submission 在持久后 id 仍然为空")
}
return ProblemSubmissionPersistenceResult.Success(
submissionId = submission.submissionId,
codeId = code.codeId
)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/submission/ProblemSubmissionPersistenceResolver.kt | 2604504757 |
package cn.llonvne.database.resolver.submission
import cn.llonvne.database.aware.ProblemAwareProvider.ProblemAwarer
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemVisibility.*
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import org.springframework.stereotype.Service
@Service
class GroupProblemPassResolver {
context(ProblemAwarer)
suspend fun resolve(
authenticationUser: AuthenticationUser,
problemSubmissionReq: ISubmissionService.ProblemSubmissionReq,
onPass: suspend (Problem) -> ISubmissionService.ProblemSubmissionResp
): ISubmissionService.ProblemSubmissionResp {
return when (problem.visibility) {
Public -> onPass(problem)
Private -> {
return if (problem.ownerId == authenticationUser.id) {
onPass(problem)
} else {
PermissionDeniedWithMessage("你无权提交该题目")
}
}
Restrict -> {
TODO()
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/submission/GroupProblemPassResolver.kt | 176444350 |
package cn.llonvne.database.resolver.submission
import cn.llonvne.database.aware.ProblemAwareProvider.ProblemAwarer
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemVisibility.*
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionResp
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import org.springframework.stereotype.Service
@Service
class IndividualProblemPassResolver(
) {
context(ProblemAwarer)
suspend fun resolve(
authenticationUser: AuthenticationUser,
problemSubmissionReq: ISubmissionService.ProblemSubmissionReq,
pass: suspend (Problem) -> ProblemSubmissionResp
): ProblemSubmissionResp {
return when (problem.visibility) {
Public -> {
pass(problem)
}
Private -> {
if (problem.ownerId == authenticationUser.id) {
pass(problem)
} else {
PermissionDeniedWithMessage("你无法提交该题目,应该该题目为私有")
}
}
Restrict -> {
TODO()
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/submission/IndividualProblemPassResolver.kt | 2424341254 |
package cn.llonvne.database.resolver.submission
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.SubmissionTestCases
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionReq
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionRespNotPersist
import cn.llonvne.kvision.service.JudgeService
import org.springframework.stereotype.Service
/**
* 执行判题程序,不做权限判断
*/
@Service
class ProblemJudgeResolver(
private val judgeService: JudgeService,
) {
suspend fun resolve(
problem: Problem,
submissionSubmit: ProblemSubmissionReq,
language: SupportLanguages,
): ProblemSubmissionRespNotPersist {
val results = problem.context.testCases.canJudge().map { testcase ->
testcase to judgeService.judge(
languages = language,
stdin = testcase.input,
code = submissionSubmit.code
)
}.map { (problemTestcase, output) ->
SubmissionTestCases.SubmissionTestCase.from(problemTestcase, output)
}
return ProblemSubmissionRespNotPersist(
problem.context.testCases,
SubmissionTestCases(results)
)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/resolver/submission/ProblemJudgeResolver.kt | 965099201 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.database.repository.CodeRepository
import cn.llonvne.database.repository.LanguageRepository
import cn.llonvne.database.resolver.code.GetCodeSafetyCheckResolver
import cn.llonvne.dtos.CodeDto
import cn.llonvne.dtos.CreateCommentDto
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.problem.ShareCodeComment
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeVisibilityType
import cn.llonvne.entity.problem.share.CodeVisibilityType.*
import cn.llonvne.kvision.service.ICodeService.*
import cn.llonvne.kvision.service.ICodeService.GetCodeResp.SuccessfulGetCode
import cn.llonvne.kvision.service.ICodeService.GetCommitsOnCodeResp.SuccessfulGetCommits
import cn.llonvne.kvision.service.ICodeService.SaveCodeResp.SuccessfulSaveCode
import cn.llonvne.kvision.service.ICodeService.SetCodeCommentTypeResp.SuccessSetCommentType
import cn.llonvne.kvision.service.ICodeService.SetCodeCommentVisibilityTypeResp.SuccessSetCodeCommentVisibilityType
import cn.llonvne.kvision.service.ICodeService.SetCodeVisibilityResp.SuccessToPublicOrPrivate
import cn.llonvne.kvision.service.ICodeService.SetCodeVisibilityResp.SuccessToRestrict
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import com.benasher44.uuid.uuid4
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class CodeService(
private val codeRepository: CodeRepository,
private val languageRepository: LanguageRepository,
private val authenticationUserRepository: AuthenticationUserRepository,
private val authentication: RedisAuthenticationService,
private val getCodeSafetyCheckResolver: GetCodeSafetyCheckResolver
) : ICodeService {
override suspend fun saveCode(
token: AuthenticationToken?,
saveCodeReq: SaveCodeReq
): SaveCodeResp {
val user = authentication.validate(token) {
requireLogin()
} ?: return PermissionDenied
if (saveCodeReq.languageId != null) {
if (!languageRepository.isIdExist(saveCodeReq.languageId)) {
return LanguageNotFound
}
}
return SuccessfulSaveCode(codeRepository.save(saveCodeReq.toCode(user)))
}
enum class GetCodeId {
HashLink, Id
}
private suspend fun getCodeSafetyCheck(
getCodeId: GetCodeId,
code: Code,
value: AuthenticationToken?
): GetCodeResp {
when (code.visibilityType) {
Public -> {
}
Private -> {
val user = authentication.getAuthenticationUser(value)
if (user == null) {
return PermissionDenied
} else if (user.id != codeRepository
.getCodeOwnerId(code.codeId ?: return CodeNotFound)
) {
return PermissionDenied
}
}
Restrict -> {
val user = authentication.getAuthenticationUser(value)
when {
getCodeId == GetCodeId.HashLink -> {}
user == null -> {
return PermissionDenied
}
user.id == codeRepository.getCodeOwnerId(code.codeId ?: return CodeNotFound) -> {
}
}
}
}
return SuccessfulGetCode(
CodeDto(
codeId = code.codeId ?: return CodeNotFound,
rawCode = code.code,
language = languageRepository.getByIdOrNull(code.languageId),
shareUserId = code.authenticationUserId,
shareUsername = authenticationUserRepository.getByIdOrNull(code.authenticationUserId)?.username
?: "未知",
visibilityType = code.visibilityType,
commentType = code.commentType,
hashLink = code.hashLink,
codeType = code.codeType
)
)
}
override suspend fun getCode(value: AuthenticationToken?, shareId: Int): GetCodeResp {
val code = codeRepository.get(shareId) ?: return CodeNotFound
return getCodeSafetyCheck(GetCodeId.Id, code, value)
}
override suspend fun getCodeByHash(value: AuthenticationToken?, hash: String): GetCodeResp {
val code = codeRepository.getCodeByHash(hash) ?: return CodeNotFound
return getCodeSafetyCheck(GetCodeId.HashLink, code, value)
}
override suspend fun setCodeCommentType(
token: AuthenticationToken?, shareId: Int, type: CodeCommentType
): SetCodeCommentTypeResp {
if (!codeRepository.isIdExist(shareId)) {
return CodeNotFound
}
val user = authentication.getAuthenticationUser(token)
if (user?.id != codeRepository.getCodeOwnerId(shareId)) {
return PermissionDenied
}
if (codeRepository.setCodeCommentType(shareId, type) != 1L) {
return CodeNotFound
}
return SuccessSetCommentType
}
override suspend fun setCodeCommentVisibilityType(
token: AuthenticationToken?, shareId: Int, commentId: Int, type: ShareCodeCommentType
): SetCodeCommentVisibilityTypeResp {
val user = authentication.getAuthenticationUser(token)
if (user == null) {
return PermissionDenied
} else if (user.id != codeRepository.getCodeOwnerId(shareId)) {
return PermissionDenied
}
if (!codeRepository.isCommentIdExist(commentId)) {
return CommentNotFound
}
codeRepository.setShareCodeCommentVisibilityType(commentId, type)
return SuccessSetCodeCommentVisibilityType
}
private suspend fun SaveCodeReq.toCode(user: AuthenticationUser): Code {
return Code(
authenticationUserId = user.id,
code = code,
languageId = languageId,
codeType = Code.CodeType.Share
)
}
override suspend fun commit(commitOnCodeReq: CommitOnCodeReq): CommitOnCodeResp {
if (commitOnCodeReq.token == null) {
return PermissionDenied
}
val user = authentication.getAuthenticationUser(commitOnCodeReq.token) ?: return PermissionDenied
val result = codeRepository.comment(
ShareCodeComment(
committerAuthenticationUserId = user.id,
content = commitOnCodeReq.content,
shareCodeId = commitOnCodeReq.codeId,
type = commitOnCodeReq.type
)
)
if (result.commentId == null) {
return InternalError("CommitId 在插入后仍不存在...")
}
if (result.createdAt == null) {
return InternalError("ShareCodeComment.CreateAt 在插入后仍不存在")
}
return CommitOnCodeResp.SuccessfulCommit(
CreateCommentDto(
result.commentId,
user.username,
commitOnCodeReq.codeId,
commitOnCodeReq.content,
createdAt = result.createdAt,
visibilityType = result.type
)
)
}
override suspend fun getComments(
authenticationToken: AuthenticationToken?, sharCodeId: Int
): GetCommitsOnCodeResp {
if (!codeRepository.isIdExist(sharCodeId)) {
return CodeNotFound
} else {
return codeRepository.getComments(sharCodeId).mapNotNull {
val committerUsername = authenticationUserRepository.getByIdOrNull(it.committerAuthenticationUserId)
?: return@mapNotNull null
val sharCodeOwnerId = codeRepository.getCodeOwnerId(sharCodeId)
val user =
authentication.getAuthenticationUser(authenticationToken) ?: return@mapNotNull null
if (it.type == ShareCodeCommentType.Private) {
if (authenticationToken == null) {
return@mapNotNull null
} else if (!(it.committerAuthenticationUserId == user.id || user.id == sharCodeOwnerId)) {
return@mapNotNull null
}
}
CreateCommentDto(
it.commentId ?: return@mapNotNull null,
committerUsername.username,
sharCodeId,
it.content,
createdAt = it.createdAt ?: return@mapNotNull null,
visibilityType = it.type
)
}.let { SuccessfulGetCommits(it) }
}
}
override suspend fun deleteComments(commentIds: List<Int>): List<Int> {
return codeRepository.deleteComment(commentIds).mapNotNull {
it.commentId
}
}
override suspend fun setCodeVisibility(
token: AuthenticationToken?, shareId: Int, result: CodeVisibilityType
): SetCodeVisibilityResp {
val user = authentication.getAuthenticationUser(token) ?: return PermissionDenied
val codeOwnerId = codeRepository.getCodeOwnerId(shareId) ?: return CodeNotFound
if (codeOwnerId != user.id) {
return PermissionDenied
}
val changeLine = codeRepository.setCodeVisibility(shareId, result)
if (changeLine != 1L) {
return CodeNotFound
}
return when (result) {
Public -> onNotRestrictType(shareId)
Private -> onNotRestrictType(shareId)
Restrict -> onRestrictType(shareId)
}
}
private suspend fun onNotRestrictType(shareId: Int): SuccessToPublicOrPrivate {
codeRepository.setHashLink(shareId = shareId, null)
return SuccessToPublicOrPrivate
}
private suspend fun onRestrictType(shareId: Int): SuccessToRestrict {
val hashLink = uuid4().toString()
codeRepository.setHashLink(shareId = shareId, hashLink)
return SuccessToRestrict(hashLink)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/CodeService.kt | 3498892658 |
package cn.llonvne.kvision.service
import cn.llonvne.database.entity.def.problem.fromCreateReq
import cn.llonvne.database.repository.AuthorRepository
import cn.llonvne.database.repository.LanguageRepository
import cn.llonvne.database.repository.ProblemRepository
import cn.llonvne.database.repository.SubmissionRepository
import cn.llonvne.dtos.ProblemListDto
import cn.llonvne.entity.problem.PlaygroundJudgeResult
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.entity.problem.ProblemListShowType
import cn.llonvne.entity.problem.ProblemListShowType.*
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.kvision.service.IProblemService.CreateProblemResp.AuthorIdNotExist
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.ProblemNotFound
import cn.llonvne.kvision.service.exception.ProblemIdDoNotExistAfterCreation
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import org.komapper.core.dsl.operator.trim
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class ProblemService(
private val authorRepository: AuthorRepository,
private val problemRepository: ProblemRepository,
private val submissionRepository: SubmissionRepository,
private val languageRepository: LanguageRepository,
private val authentication: RedisAuthenticationService
) : IProblemService {
override suspend fun list(
authenticationToken: AuthenticationToken?,
showType: ProblemListShowType
): List<ProblemListDto> {
return problemRepository.list()
.filter { problem ->
when (showType) {
All -> true
Accepted -> {
val user = authentication.validate(authenticationToken) {
requireLogin()
} ?: return listOf()
val submission = submissionRepository.getByAuthenticationUserID(
user.id,
codeType = Code.CodeType.Problem
)
val set = submission.filter {
when (it.result) {
is PlaygroundJudgeResult -> false
is ProblemJudgeResult -> (it.result as ProblemJudgeResult).passerResult.pass
}
}
.mapNotNull { it.problemId }.toSet()
problem.problemId in set
}
Attempted -> {
val user = authentication.validate(authenticationToken) {
requireLogin()
} ?: return listOf()
val submission = submissionRepository.getByAuthenticationUserID(
user.id,
codeType = Code.CodeType.Problem
)
val set = submission.filter {
when (it.result) {
is PlaygroundJudgeResult -> false
is ProblemJudgeResult -> true
}
}
.mapNotNull { it.problemId }.toSet()
problem.problemId in set
}
Favorite -> {
TODO()
}
}
}
.mapNotNull { it.listDto(authenticationToken) }
}
override suspend fun create(
authenticationToken: AuthenticationToken?, createProblemReq: IProblemService.CreateProblemReq
): IProblemService.CreateProblemResp {
if (authenticationToken == null) {
return PermissionDenied
}
if (!authorRepository.isAuthorIdExist(createProblemReq.authorId)) {
return AuthorIdNotExist(createProblemReq.authorId)
}
val problem = problemRepository.create(
Problem.fromCreateReq(
createProblemReq,
ownerId = authenticationToken.id
)
)
if (problem.problemId == null) {
throw ProblemIdDoNotExistAfterCreation()
}
languageRepository.setSupportLanguages(problem.problemId,
createProblemReq.supportLanguages.map { it.languageId })
return IProblemService.CreateProblemResp.Ok(problem.problemId)
}
override suspend fun getById(id: Int): ProblemGetByIdResult {
val problem = problemRepository.getById(id)
return if (problem == null) {
ProblemNotFound
} else {
GetProblemByIdOk(problem, problemRepository.getSupportLanguage(id), problemRepository.getProblemTags(id))
}
}
override suspend fun search(token: AuthenticationToken?, text: String): List<ProblemListDto> {
return problemRepository.search(text).mapNotNull {
it.listDto(token)
}
}
private suspend fun Problem.listDto(token: AuthenticationToken?): ProblemListDto? {
return onIdNotNull(null) { id, problem ->
ProblemListDto(
problem,
id,
authorRepository.getByIdOrThrow(authorId),
submissionRepository.getUserProblemStatus(token, id),
problemRepository.getProblemTags(id)
)
}
}
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/ProblemService.kt | 1936080937 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.database.resolver.authentication.BannedUsernameCheckResolver
import cn.llonvne.database.resolver.authentication.BannedUsernameCheckResolver.BannedUsernameCheckResult
import cn.llonvne.database.resolver.authentication.BannedUsernameCheckResolver.BannedUsernameCheckResult.Pass
import cn.llonvne.database.resolver.mine.MineRoleCheckResolver
import cn.llonvne.kvision.service.IAuthenticationService.*
import cn.llonvne.kvision.service.IAuthenticationService.GetLoginInfoResp.*
import cn.llonvne.kvision.service.IAuthenticationService.GetLogoutResp.Logout
import cn.llonvne.kvision.service.IAuthenticationService.RegisterResult.Failed
import cn.llonvne.kvision.service.IAuthenticationService.RegisterResult.SuccessfulRegistration
import cn.llonvne.message.Message
import cn.llonvne.message.MessageLevel
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class AuthenticationService(
private val userRepository: AuthenticationUserRepository,
private val authentication: RedisAuthenticationService,
private val bannedUsernameCheckResolver: BannedUsernameCheckResolver,
private val mineResolver: MineRoleCheckResolver
) : IAuthenticationService {
override suspend fun register(username: String, password: String): RegisterResult {
when (bannedUsernameCheckResolver.resolve(username)) {
Pass -> {}
BannedUsernameCheckResult.Failed -> return Failed(
Message.ToastMessage(MessageLevel.Danger, "名称包含违禁词")
)
}
// 检查用户名是否可用
return if (userRepository.usernameAvailable(username)) {
val user = userRepository.new(username, password)
// 返回成功注册
SuccessfulRegistration(authentication.login(user), username)
} else {
// 提示用户名已经存在
Failed(Message.ToastMessage(MessageLevel.Warning, "用户名:$username 已经存在"))
}
}
override suspend fun login(username: String, password: String): LoginResult {
return userRepository.login(username, password)
}
override suspend fun getLoginInfo(token: AuthenticationToken?): GetLoginInfoResp {
if (token == null) {
return NotLogin
}
val user = authentication.validate(token) { requireLogin() }
if (user == null) {
return LoginExpired
}
return Login(user.username, user.id)
}
override suspend fun logout(token: AuthenticationToken?): GetLogoutResp {
authentication.logout(token)
return Logout
}
override suspend fun mine(value: AuthenticationToken?): MineResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
return mineResolver.resolve(user)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/AuthenticationService.kt | 2117749612 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.GroupRepository
import cn.llonvne.database.resolver.group.*
import cn.llonvne.database.resolver.group.GroupMangerDowngradeResolver.GroupManagerDowngradeResult
import cn.llonvne.database.resolver.group.GroupMangerDowngradeResolver.GroupManagerDowngradeResult.BeDowngradeUserNotFound
import cn.llonvne.database.resolver.group.GroupMangerDowngradeResolver.GroupManagerDowngradeResult.DowngradeToIdNotMatchToGroupId
import cn.llonvne.database.resolver.group.GroupMemberUpgradeResolver.GroupMemberUpgradeResult.*
import cn.llonvne.database.resolver.group.GroupMemberUpgradeResolver.GroupMemberUpgradeResult.UserAlreadyHasThisRole
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.role.CreateGroup
import cn.llonvne.entity.role.GroupManager
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.entity.role.KickMember
import cn.llonvne.getLogger
import cn.llonvne.kvision.service.IGroupService.*
import cn.llonvne.kvision.service.IGroupService.CreateGroupResp.CreateGroupOk
import cn.llonvne.kvision.service.IGroupService.UpgradeGroupManagerResp.UpgradeManagerOk
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import cn.llonvne.security.userRole
import cn.llonvne.track
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class GroupService(
private val authentication: RedisAuthenticationService,
private val groupRepository: GroupRepository,
private val roleService: RoleService,
private val groupIdResolver: GroupIdResolver,
private val groupLoadResolver: GroupLoadResolver,
private val joinGroupResolver: JoinGroupResolver,
private val groupKickResolver: GroupKickResolver,
private val memberUpgradeResolver: GroupMemberUpgradeResolver,
private val groupMangerDowngradeResolver: GroupMangerDowngradeResolver
) : IGroupService {
private val logger = getLogger()
override suspend fun createTeam(
authenticationToken: AuthenticationToken, createGroupReq: CreateGroupReq
): CreateGroupResp {
val user = authentication.validate(authenticationToken) {
check(CreateGroup.require(createGroupReq.groupType))
} ?: return PermissionDenied
if (!groupRepository.shortNameAvailable(createGroupReq.groupShortName)) {
return GroupShortNameUnavailable(createGroupReq.groupShortName)
}
return logger.track(authenticationToken, createGroupReq.groupName, createGroupReq.groupShortName) {
info("$authenticationToken try to create $createGroupReq")
val group = groupRepository.create(createGroupReq)
info("$authenticationToken created ${createGroupReq.groupName},id is ${group.groupId}")
roleService.addRole(
user.id, GroupOwner.GroupOwnerImpl(
group.groupId ?: return@track InternalError("创建小组后仍然 id 为空")
)
)
return@track CreateGroupOk(group)
}
}
override suspend fun load(
authenticationToken: AuthenticationToken?, groupId: GroupId
): LoadGroupResp = logger.track(authenticationToken, groupId) {
val id = groupIdResolver.resolve(groupId) ?: return@track GroupIdNotFound(groupId)
val user = authentication.getAuthenticationUser(authenticationToken)
return@track groupLoadResolver.resolve(groupId, id, user)
}
override suspend fun join(groupId: GroupId, authenticationToken: AuthenticationToken): JoinGroupResp {
val id = groupIdResolver.resolve(groupId) ?: return GroupIdNotFound(groupId)
val user = authentication.validate(authenticationToken) { requireLogin() }
if (user == null) {
return PermissionDenied
}
return joinGroupResolver.resolve(groupId, id, user)
}
override suspend fun quit(groupId: GroupId, value: AuthenticationToken?): QuitGroupResp {
val user = authentication.validate(value) { requireLogin() } ?: return PermissionDenied
val id = groupIdResolver.resolve(groupId) ?: return GroupIdNotFound(groupId)
roleService.removeRole(user, user.userRole.groupIdRoles(id))
return QuitOk
}
override suspend fun kick(token: AuthenticationToken?, groupId: GroupId, kickMemberId: Int): KickGroupResp {
val groupIntId = groupIdResolver.resolve(groupId) ?: return GroupIdNotFound(groupId)
val kicker = authentication.validate(token) {
check(KickMember.KickMemberImpl(groupIntId))
} ?: return PermissionDeniedWithMessage("你没有权限踢人哦")
return groupKickResolver.resolve(groupId, groupIntId, kicker, kickMemberId)
}
override suspend fun upgradeGroupManager(
token: AuthenticationToken?,
groupId: GroupId,
updatee: Int
): UpgradeGroupManagerResp {
val groupIntId = groupIdResolver.resolve(groupId) ?: return GroupIdNotFound(groupId)
val owner = authentication.validate(token) {
check(GroupOwner.GroupOwnerImpl(groupIntId))
} ?: return PermissionDeniedWithMessage("你没有权限升级管理员哦")
val result =
memberUpgradeResolver.resolve(groupId, groupIntId, owner, updatee, GroupManager.GroupMangerImpl(groupIntId))
return when (result) {
UpdateToIdNotMatchToGroupId -> UpOrDowngradeToIdNotMatchToGroupId(updatee)
UserAlreadyHasThisRole -> IGroupService.UserAlreadyHasThisRole(updatee)
BeUpdatedUserNotFound -> BeUpOrDowngradedUserNotfound(updatee)
Success -> UpgradeManagerOk
}
}
override suspend fun downgradeToMember(
authenticationToken: AuthenticationToken?,
groupId: GroupId,
userId: Int
): DowngradeToMemberResp {
val groupIntid = groupIdResolver.resolve(groupId) ?: return GroupIdNotFound(groupId)
val owner = authentication.validate(authenticationToken) {
check(GroupOwner.GroupOwnerImpl(groupIntid))
} ?: return PermissionDeniedWithMessage("你没有权限降级管理员哦")
return when (groupMangerDowngradeResolver.resolve(
groupId,
groupIntid,
owner,
userId,
)) {
DowngradeToIdNotMatchToGroupId -> IGroupService.UserAlreadyHasThisRole(userId)
BeDowngradeUserNotFound -> BeUpOrDowngradedUserNotfound(userId)
GroupManagerDowngradeResult.Success -> DowngradeToMemberResp.DowngradeToMemberOk(userId)
GroupManagerDowngradeResult.UserAlreadyHasThisRole -> IGroupService.UserAlreadyHasThisRole(userId)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/GroupService.kt | 687993073 |
package cn.llonvne.kvision.service
import org.springframework.stereotype.Service
import java.util.*
@Service
class GroupHashService {
fun hash(): String {
return UUID.randomUUID().toString()
}
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/GroupHashService.kt | 4131954614 |
package cn.llonvne.kvision.service
import cn.llonvne.gojudge.api.JudgeServerApi
import cn.llonvne.gojudge.api.LanguageDispatcher
import cn.llonvne.gojudge.api.LanguageFactory
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.api.task.Output
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.core.env.Environment
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT", "SpringJavaInjectionPointsAutowiringInspection")
actual class JudgeService(
env: Environment,
private val judgeUrl: String = env.getProperty("oj.url") ?: throw RuntimeException("无法获得 oj.url "),
private val languageDispatcher: LanguageDispatcher = default(judgeUrl),
private val judgeServerApi: JudgeServerApi = JudgeServerApi.get(judgeUrl, httpClient)
) : IJudgeService {
override suspend fun judge(languages: SupportLanguages, stdin: String, code: String): Output {
return languageDispatcher.dispatch(languages) {
judge(code, stdin)
}
}
suspend fun info() = judgeServerApi.info()
companion object {
private val httpClient: HttpClient = HttpClient(OkHttp) {
install(ContentNegotiation) {
json(Json)
}
}
private fun default(judgeUrl: String): LanguageDispatcher {
return LanguageDispatcher.get(
LanguageFactory.get(
judgeUrl,
httpClient = httpClient
)
)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/JudgeService.kt | 3262167905 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.RoleRepository
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.Role
import cn.llonvne.security.RedisAuthenticationService
import cn.llonvne.security.UserRole
import cn.llonvne.security.fromUserRoleString
import cn.llonvne.security.userRole
import org.springframework.stereotype.Service
@Service
class RoleService(
private val roleRepository: RoleRepository,
private val redisAuthentication: RedisAuthenticationService
) {
suspend fun addRole(userId: Int, vararg role: Role): Boolean {
val userRoleStr = roleRepository.getRoleStrByUserId(userId) ?: return false
val originRole = fromUserRoleString(userRoleStr) ?: UserRole.default()
val newRole = UserRole((originRole.roles + role).toSet().toList())
roleRepository.setRoleStrByUserId(userId, newRole)
saveToRedis(userId, newRole)
return true
}
private suspend fun saveToRedis(userId: Int, newRole: UserRole) {
val redisUser = redisAuthentication.getAuthenticationUser(userId)
if (redisUser != null) {
redisAuthentication.update(redisUser.copy(role = newRole.asJson))
}
}
suspend fun get(userId: Int): UserRole? {
val roleStr = roleRepository.getRoleStrByUserId(userId) ?: return null
return fromUserRoleString(roleStr) ?: UserRole.default()
}
suspend fun removeRole(user: AuthenticationUser, roles: List<Role>): Boolean {
val userRoles = user.userRole.roles
val newRoles = UserRole(userRoles.filter { it !in userRoles })
roleRepository.setRoleStrByUserId(user.id, newRoles)
saveToRedis(userId = user.id, newRoles)
return true
}
suspend fun removeRole(userId: Int, roles: List<Role>): Boolean {
val userRoleStr = roleRepository.getRoleStrByUserId(userId) ?: return false
val originRole = fromUserRoleString(userRoleStr) ?: UserRole.default()
val newRole = UserRole((originRole.roles - roles.toSet()).toList())
roleRepository.setRoleStrByUserId(userId, newRole)
saveToRedis(userId, newRole)
return true
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/RoleService.kt | 702399307 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.*
import cn.llonvne.database.resolver.contest.ContestIdGetResolver
import cn.llonvne.database.resolver.submission.ProblemJudgeResolver
import cn.llonvne.database.resolver.submission.ProblemSubmissionPassResolver
import cn.llonvne.database.resolver.submission.ProblemSubmissionPersistenceResolver
import cn.llonvne.database.resolver.submission.ProblemSubmissionPersistenceResolver.ProblemSubmissionPersistenceResult.Failed
import cn.llonvne.database.resolver.submission.ProblemSubmissionPersistenceResolver.ProblemSubmissionPersistenceResult.NotNeedToPersist
import cn.llonvne.dtos.AuthenticationUserDto
import cn.llonvne.dtos.SubmissionListDto
import cn.llonvne.dtos.ViewCodeDto
import cn.llonvne.entity.problem.*
import cn.llonvne.entity.problem.context.ProblemTestCases.ProblemTestCase
import cn.llonvne.entity.problem.context.SubmissionTestCases
import cn.llonvne.entity.problem.context.TestCaseType
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeVisibilityType.*
import cn.llonvne.exts.now
import cn.llonvne.getLogger
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.api.fromId
import cn.llonvne.gojudge.api.spec.runtime.GoJudgeFile
import cn.llonvne.gojudge.api.task.Output.Failure
import cn.llonvne.gojudge.api.task.Output.Failure.CompileResultIsNull
import cn.llonvne.gojudge.api.task.Output.Failure.TargetFileNotExist
import cn.llonvne.gojudge.api.task.Output.Success
import cn.llonvne.kvision.service.ISubmissionService.*
import cn.llonvne.kvision.service.ISubmissionService.CreateSubmissionReq.PlaygroundCreateSubmissionReq
import cn.llonvne.kvision.service.ISubmissionService.GetLastNPlaygroundSubmissionResp.PlaygroundSubmissionDto
import cn.llonvne.kvision.service.ISubmissionService.GetLastNPlaygroundSubmissionResp.SuccessGetLastNPlaygroundSubmission
import cn.llonvne.kvision.service.ISubmissionService.GetLastNProblemSubmissionResp.GetLastNProblemSubmissionRespImpl
import cn.llonvne.kvision.service.ISubmissionService.GetParticipantContestResp.GetParticipantContestOk
import cn.llonvne.kvision.service.ISubmissionService.GetSupportLanguageByProblemIdResp.SuccessfulGetSupportLanguage
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto.FailureOutput
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto.FailureReason.*
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto.SuccessOutput
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.SuccessPlaygroundOutput
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionResp.ProblemSubmissionRespImpl
import cn.llonvne.kvision.service.ISubmissionService.SubmissionGetByIdResp.SuccessfulGetById
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import com.fasterxml.jackson.databind.ObjectMapper
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.flow.toSet
import kotlinx.datetime.LocalDateTime
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
import cn.llonvne.database.resolver.submission.ProblemSubmissionPersistenceResolver.ProblemSubmissionPersistenceResult.Success as PersisitSuccess
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class SubmissionService(
private val submissionRepository: SubmissionRepository,
private val languageRepository: LanguageRepository,
private val problemRepository: ProblemRepository,
private val authenticationUserRepository: AuthenticationUserRepository,
private val judgeService: JudgeService,
private val codeRepository: CodeRepository,
private val authentication: RedisAuthenticationService,
private val problemSubmissionPassResolver: ProblemSubmissionPassResolver,
private val problemJudgeResolver: ProblemJudgeResolver,
private val problemSubmissionPersistenceResolver: ProblemSubmissionPersistenceResolver,
private val contestIdGetResolver: ContestIdGetResolver,
private val contestRepository: ContestRepository,
private val contestService: ContestService
) : ISubmissionService {
private val logger = getLogger()
override suspend fun list(req: ListSubmissionReq): List<SubmissionListDto> {
return submissionRepository.list()
.mapNotNull { submission ->
when (val result = submission.listDto()) {
is SuccessfulGetById -> result.submissionListDto
else -> null
}
}
}
override suspend fun getById(id: Int): SubmissionGetByIdResp {
val submission =
submissionRepository.getById(id) ?: return SubmissionNotFound
return submission.listDto()
}
override suspend fun getViewCode(id: Int): ViewCodeGetByIdResp {
val submission = submissionRepository.getById(id) ?: return SubmissionNotFound
val result = runCatching {
submission.result
}
val problem =
problemRepository.getById(submission.problemId) ?: return ProblemNotFound
val code = codeRepository.get(
submission.codeId
) ?: return CodeNotFound
return ViewCodeGetByIdResp.SuccessfulGetById(
ViewCodeDto(
rawCode = code.code,
language = languageRepository.getByIdOrNull(code.languageId)
?: return LanguageNotFound,
problemName = problem.problemName,
problemId = problem.problemId ?: return ProblemNotFound,
status = submission.status,
submissionId = submission.submissionId ?: return SubmissionNotFound,
judgeResult = result.getOrNull() ?: return JudgeResultParseError
)
)
}
private suspend fun Submission.listDto(): SubmissionGetByIdResp {
val problem = problemRepository.getById(problemId) ?: return ProblemNotFound
return problem.onIdNotNull(ProblemNotFound) { problemId, problem ->
val languageId = codeRepository.getCodeLanguageId(codeId)
SuccessfulGetById(
SubmissionListDto(
language = languageRepository.getByIdOrNull(languageId) ?: return@onIdNotNull LanguageNotFound,
user = AuthenticationUserDto(
authenticationUserRepository.getByIdOrNull(authenticationUserId)?.username
?: return@onIdNotNull UserNotFound,
),
problemId = problemId,
problemName = problem.problemName,
submissionId = this.submissionId ?: return@onIdNotNull SubmissionNotFound,
status = this.status,
codeLength = codeRepository.getCodeLength(codeId)?.toLong() ?: return@onIdNotNull CodeNotFound,
submitTime = this.createdAt ?: LocalDateTime.now(),
passerResult = (this.result as ProblemJudgeResult).passerResult,
codeId = codeId
)
)
}
}
override suspend fun getSupportLanguageId(
authenticationToken: AuthenticationToken?,
problemId: Int
): GetSupportLanguageByProblemIdResp {
if (!problemRepository.isIdExist(problemId)) {
return ProblemNotFound
}
return SuccessfulGetSupportLanguage(
problemRepository.getSupportLanguage(problemId)
)
}
override suspend fun create(
authenticationToken: AuthenticationToken?,
createSubmissionReq: CreateSubmissionReq
): CreateSubmissionResp {
val language = SupportLanguages.fromId(createSubmissionReq.languageId) ?: return LanguageNotFound
val user = authentication.validate(authenticationToken) { requireLogin() } ?: return PermissionDenied
val code = codeRepository.save(
Code(
authenticationUserId = user.id,
code = createSubmissionReq.rawCode,
languageId = createSubmissionReq.languageId,
visibilityType = Private,
codeType = createSubmissionReq.codeType
)
)
return when (createSubmissionReq) {
is PlaygroundCreateSubmissionReq -> onPlaygroundCreateSubmission(
code, language, createSubmissionReq
)
}
}
override suspend fun getOutputByCodeId(
authenticationToken: AuthenticationToken?,
codeId: Int
): GetJudgeResultByCodeIdResp {
val visibilityType = codeRepository.getCodeVisibilityType(codeId) ?: return CodeNotFound
val codeOwnerId = codeRepository.getCodeOwnerId(codeId) ?: return CodeNotFound
when (visibilityType) {
Public -> {
}
Private -> {
val user = authentication.validate(authenticationToken) {
requireLogin()
} ?: return PermissionDenied
if (user.id != codeOwnerId) {
return PermissionDenied
}
}
Restrict -> {
}
}
val submission = submissionRepository.getByCodeId(codeId) ?: return SubmissionNotFound
val output = kotlin.runCatching {
submission.result
}
val languageId = codeRepository.getCodeLanguageId(codeId) ?: return LanguageNotFound
val language = SupportLanguages.fromId(languageId) ?: return LanguageNotFound
output.onFailure {
return JudgeResultParseError
}.onSuccess { output ->
when (output) {
is PlaygroundJudgeResult -> {
return SuccessPlaygroundOutput(
when (val output = output.output) {
is Failure.CompileError -> {
FailureOutput(
CompileError(output.compileResult.files?.get("stderr").toString()),
language
)
}
is CompileResultIsNull -> {
FailureOutput(
CompileResultNotFound,
language
)
}
is Failure.RunResultIsNull -> FailureOutput(
RunResultIsNull,
language
)
is TargetFileNotExist -> FailureOutput(
TargetResultNotFound,
language
)
is Success -> SuccessOutput(
stdin = output.runRequest.cmd.first().files?.filterIsInstance<GoJudgeFile.MemoryFile>()
?.first()?.content.toString(),
stdout = output.runResult.files?.get("stdout").toString(),
language
)
}
)
}
is ProblemJudgeResult -> {
return ProblemOutput.SuccessProblemOutput(output)
}
}
}
error("这不应该发生")
}
override suspend fun getLastNPlaygroundSubmission(
authenticationToken: AuthenticationToken?,
last: Int
): GetLastNPlaygroundSubmissionResp {
val user = authentication.getAuthenticationUser(authenticationToken) ?: return PermissionDenied
return submissionRepository.getByAuthenticationUserID(
user.id,
Code.CodeType.Playground,
last
).map { sub ->
val languageId = codeRepository.getCodeLanguageId(sub.codeId) ?: return LanguageNotFound
val language = languageRepository.getByIdOrNull(languageId) ?: return LanguageNotFound
PlaygroundSubmissionDto(
language = language,
codeId = sub.codeId,
status = sub.status,
submissionId = sub.submissionId ?: return InternalError("Submission 被查询出来,但不存在 Id"),
submitTime = sub.createdAt ?: return InternalError("Submission 被查询出来,但不存在创建时间"),
user = AuthenticationUserDto(
username = authenticationUserRepository.getByIdOrNull(sub.authenticationUserId)?.username
?: return InternalError("Submission 被查询出来,但不存在 User")
)
)
}.let {
SuccessGetLastNPlaygroundSubmission(it)
}
}
private suspend fun onPlaygroundCreateSubmission(
code: Code,
language: SupportLanguages,
req: PlaygroundCreateSubmissionReq
): CreateSubmissionResp {
val output = runCatching {
judgeService.judge(
languages = language,
code = code.code,
stdin = req.stdin
)
}.onFailure {
return JudgeError(it.cause.toString())
}
val playgroundJudgeResult = SubmissionTestCases(
listOf(
SubmissionTestCases.SubmissionTestCase.from(
ProblemTestCase("Playgroud", "Playgroud", req.stdin, "", TestCaseType.OnlyForJudge),
output = output.getOrNull()!!
)
)
).let {
PlaygroundJudgeResult(it)
}
val judgeResult = playgroundJudgeResult.json()
val submission = submissionRepository.save(
Submission(
authenticationUserId = code.authenticationUserId,
judgeResult = judgeResult,
problemId = null,
codeId = code.codeId ?: return InternalError("CodeId 在插入后仍不存在"),
status = SubmissionStatus.Finished
)
)
return CreateSubmissionResp.SuccessfulCreateSubmissionResp(
submission.submissionId
?: return InternalError("插入 Submission 后 SubmissionId 仍不存在"),
code.codeId
)
}
override suspend fun submit(
value: AuthenticationToken?,
submissionSubmit: ProblemSubmissionReq
): ProblemSubmissionResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
logger.info("判题请求已收到来自用户 ${user.id} 在题目 ${submissionSubmit.problemId} 语言是 ${submissionSubmit.languageId} 代码是 ${submissionSubmit.code}")
val language = languageRepository.getByIdOrNull(submissionSubmit.languageId).let {
SupportLanguages.fromId(it?.languageId ?: return LanguageNotFound)
} ?: return LanguageNotFound
logger.info("判题语言是 ${language.languageName}:${language.languageVersion}")
return problemSubmissionPassResolver.resolve(user, submissionSubmit) { problem ->
val result = problemJudgeResolver.resolve(problem, submissionSubmit, language)
return@resolve when (val persistenceResult =
problemSubmissionPersistenceResolver.resolve(user, result, submissionSubmit, language)) {
is Failed -> {
return@resolve InternalError("评测结果持久化失败")
}
NotNeedToPersist -> {
return@resolve InternalError("评测结果无法持久化,TrackId-${Objects.hash(value, submissionSubmit)}")
}
is PersisitSuccess -> {
logger.info("成功持久化判题结果,SubmissionId:${persistenceResult.submissionId},CodeId:${persistenceResult.codeId}")
ProblemSubmissionRespImpl(
persistenceResult.codeId,
result.problemTestCases,
result.submissionTestCases
)
}
}
}
}
override suspend fun getLastNProblemSubmission(
value: AuthenticationToken?,
problemId: Int,
lastN: Int
): GetLastNProblemSubmissionResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
logger.info("用户 ${user.id} 正在请求题目 $problemId 的前 $lastN 次提交记录")
val problem = problemRepository.getById(problemId) ?: return ProblemNotFound.also {
logger.info("题目 $problemId 不存在,请求失败")
}
val result =
submissionRepository.getByAuthenticationUserID(user.id, codeType = Code.CodeType.Problem, lastN)
.filter {
it.problemId != null && it.problemId == problemId
}.filter {
it.result is ProblemJudgeResult
}
.map { sub ->
val languageId = codeRepository.getCodeLanguageId(sub.codeId) ?: return LanguageNotFound
val language = languageRepository.getByIdOrNull(languageId) ?: return LanguageNotFound
GetLastNProblemSubmissionResp.ProblemSubmissionListDto(
language = language,
codeId = sub.codeId,
submitTime = sub.createdAt ?: LocalDateTime.now(),
passerResult = (sub.result as ProblemJudgeResult).passerResult
)
}
return GetLastNProblemSubmissionRespImpl(result).also {
logger.info("共找到 ${result.size} 条记录")
}
}
override suspend fun getParticipantContest(
value: AuthenticationToken?,
): GetParticipantContestResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
val contests = submissionRepository.getByAuthenticationUserID(
user.id, codeType = Code.CodeType.Problem
).mapNotNull {
it.contestId
}.toSet().mapNotNull {
contestRepository.getById(it)
}
return GetParticipantContestOk(contests.sortedByDescending { it.endAt }.take(5))
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/SubmissionService.kt | 1759196893 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.database.resolver.mine.BackendInfoResolver
import cn.llonvne.database.resolver.mine.JudgeServerInfoResolver
import cn.llonvne.database.resolver.mine.OnlineJudgeStatisticsResolver
import cn.llonvne.entity.ModifyUserForm
import cn.llonvne.entity.role.Backend
import cn.llonvne.entity.role.Banned
import cn.llonvne.entity.role.IUserRole
import cn.llonvne.entity.role.check
import cn.llonvne.exts.*
import cn.llonvne.kvision.service.IMineService.DashboardResp.DashboardRespImpl
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import cn.llonvne.security.check
import cn.llonvne.security.userRole
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class MineService(
private val authentication: RedisAuthenticationService,
private val onlineJudgeStatisticsResolver: OnlineJudgeStatisticsResolver,
private val backendInfoResolver: BackendInfoResolver,
private val judgeServerInfoResolver: JudgeServerInfoResolver,
private val authenticationUserRepository: AuthenticationUserRepository,
private val roleService: RoleService
) : IMineService {
override suspend fun dashboard(authenticationToken: AuthenticationToken?): IMineService.DashboardResp {
val user = authentication.validate(authenticationToken) {
requireLogin()
check(Backend.BackendImpl)
} ?: return PermissionDenied
return DashboardRespImpl(
statistics = onlineJudgeStatisticsResolver.resolve(),
backendInfo = backendInfoResolver.resolve(),
judgeServerInfo = judgeServerInfoResolver.resolve()
)
}
override suspend fun users(): IMineService.UsersResp {
val user = authenticationUserRepository.all()
.map {
IMineService.UsersResp.UserManageListUserDto(
userId = it.id,
username = it.username,
userRole = IUserRole(it.userRole.roles),
createAt = it.createdAt ?: kotlinx.datetime.LocalDateTime.now()
)
}
return IMineService.UsersResp.UsersRespImpl(
users = user
)
}
override suspend fun deleteUser(value: AuthenticationToken?, id: Int): Boolean {
return authenticationUserRepository.deleteById(id)
}
override suspend fun modifyUser(value: AuthenticationToken?, result: ModifyUserForm): Boolean {
val id = result.userId.toIntOrNull() ?: return false
val user = authentication.getAuthenticationUser(id) ?: return false
if (result.isBanned) {
if (!user.check(Banned.BannedImpl)) {
return roleService.addRole(id, Banned.BannedImpl)
}
} else {
return roleService.removeRole(user, listOf(Banned.BannedImpl))
}
return false
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/MineService.kt | 1097128845 |
package cn.llonvne.kvision.service
import cn.llonvne.database.repository.AuthenticationUserRepository
import cn.llonvne.database.repository.ContestRepository
import cn.llonvne.database.repository.ProblemRepository
import cn.llonvne.database.repository.SubmissionRepository
import cn.llonvne.database.resolver.contest.ContestIdGetResolver
import cn.llonvne.database.resolver.contest.ContestProblemVisibilityCheckResolver
import cn.llonvne.database.resolver.contest.ContestProblemVisibilityCheckResolver.ContestProblemVisibilityCheckResult.Pass
import cn.llonvne.database.resolver.contest.ContestProblemVisibilityCheckResolver.ContestProblemVisibilityCheckResult.Reject
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestContext
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.kvision.service.IContestService.AddProblemResp.AddOkResp
import cn.llonvne.security.AuthenticationToken
import cn.llonvne.security.RedisAuthenticationService
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class ContestService(
private val authentication: RedisAuthenticationService,
private val problemRepository: ProblemRepository,
private val contestProblemVisibilityCheckResolver: ContestProblemVisibilityCheckResolver,
private val contestRepository: ContestRepository,
private val contestIdGetResolver: ContestIdGetResolver,
private val authenticationUserRepository: AuthenticationUserRepository,
private val submissionRepository: SubmissionRepository
) : IContestService {
override suspend fun addProblem(value: AuthenticationToken?, problemId: String): IContestService.AddProblemResp {
val user = authentication.validate(value) { requireLogin() } ?: return PermissionDenied
val problem = problemRepository.getById(problemId.toIntOrNull() ?: return ProblemIdInvalid)
?: return ISubmissionService.ProblemNotFound
when (contestProblemVisibilityCheckResolver.check(user, problem)) {
Pass -> return AddOkResp(
problem.problemId ?: return InternalError("Problem Id 不存在"), problem.problemName
)
Reject -> return AddProblemPermissionDenied
}
}
override suspend fun create(
authenticationToken: AuthenticationToken?, createContestReq: IContestService.CreateContestReq
): IContestService.CreateContestResp = coroutineScope {
val userDeferred = async(Dispatchers.IO) {
authentication.validate(authenticationToken) {
requireLogin()
}
}
val problemsSet = createContestReq.problems.associateBy { it.problemId }
val problemsDeferred = async {
runCatching {
createContestReq.problems.asFlow()
.cancellable().buffer(10)
.map { problemRepository.getById(it.problemId) }
.map { it ?: throw CancellationException("ProblemId 无效") }
.catch { e -> cancel(e.message ?: "") }
.flowOn(Dispatchers.IO).toList()
}.getOrNull()
}
val user = userDeferred.await() ?: return@coroutineScope PermissionDenied
val problems = problemsDeferred.await() ?: return@coroutineScope ProblemIdInvalid
val contest = contestRepository.create(
Contest(
ownerId = user.id,
title = createContestReq.title,
description = createContestReq.description,
rankType = createContestReq.rankType,
contestScoreType = createContestReq.contestScoreType,
startAt = createContestReq.startAt,
endAt = createContestReq.endAt,
contextStr = ContestContext(
problems = problems.map {
val id = it.problemId ?: return@coroutineScope ProblemIdInvalid
ContestContext.ContestProblem(
id,
problemsSet[id]?.weight ?: return@coroutineScope InternalError("weight 通过非空检查却为空"),
problemsSet[id]?.alias ?: return@coroutineScope InternalError("alias 通过非空检查却为空")
)
}
).json(),
hashLink = UUID.randomUUID().toString()
)
)
return@coroutineScope IContestService.CreateContestResp.CreateOk(contest)
}
override suspend fun load(value: AuthenticationToken?, contestId: ContestId): IContestService.LoadContestResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
val contest = contestIdGetResolver.resolve(contestId) ?: return ContestNotFound
val username = authenticationUserRepository.getByIdOrNull(
contest.ownerId
)?.username ?: return ContestOwnerNotFound
return IContestService.LoadContestResp.LoadOk(contest, username)
}
override suspend fun contextSubmission(
value: AuthenticationToken?,
contestId: ContestId
): IContestService.ContextSubmissionResp {
val user = authentication.validate(value) {
requireLogin()
} ?: return PermissionDenied
val contestId = contestIdGetResolver.resolve(contestId)?.contestId ?: return ContestNotFound
val submissions = submissionRepository.getByContestId(contestId)
return IContestService.ContextSubmissionResp.ContextSubmissionOk(submissions)
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/kvision/service/ContestService.kt | 3960403295 |
package cn.llonvne.config
import org.springframework.context.annotation.Configuration
import org.springframework.web.reactive.config.EnableWebFlux
import org.springframework.web.reactive.config.WebFluxConfigurer
@EnableWebFlux
@Configuration
class WebConfig : WebFluxConfigurer | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/config/WebConfig.kt | 3726414449 |
package cn.llonvne.security
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.Banned
import cn.llonvne.entity.role.Role
import cn.llonvne.getLogger
import cn.llonvne.redis.Redis
import cn.llonvne.redis.get
import cn.llonvne.redis.set
import org.slf4j.Logger
import org.springframework.core.env.Environment
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import java.util.*
/**
* 基于 Redis 的登入服务类
* [redis] 提供 Redis 实现,默认 Redis 实现在 [Redis],使用 kotlinx-serialization 进行序列化
* [passwordEncoder] 提供加密方案
*/
@Service
class RedisAuthenticationService(
private val redis: Redis,
private val passwordEncoder: PasswordEncoder,
env: Environment,
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
private val redisKeyPrefix: String = env.getProperty("oj.redis.user.prefix") ?: "user-id"
) {
val log: Logger = getLogger()
private val AuthenticationUser.asRedisKey get() = "$redisKeyPrefix-$id-" + UUID.randomUUID()
suspend fun login(user: AuthenticationUser): AuthenticationToken {
val token = user.asRedisKey
redis.set(token, user)
return RedisToken(user.id, token)
}
suspend fun isLogin(token: AuthenticationToken?): Boolean {
val user = getAuthenticationUser(token) ?: return false
return !user.check(Banned.BannedImpl)
}
suspend fun getAuthenticationUser(id: Int): AuthenticationUser? {
return redis.keys("$redisKeyPrefix-$id-*").firstOrNull()?.let { redis.get(it) }
}
suspend fun getAuthenticationUser(token: AuthenticationToken?): AuthenticationUser? {
if (token == null) {
return null
}
return redis.get(token.token)
}
suspend fun logout(token: AuthenticationToken?) {
if (token != null) {
redis.clear(token.token)
}
}
fun interface Validator {
suspend fun validate(): Boolean
}
inner class UserValidatorDsl(
val token: AuthenticationToken?
) {
private val validators = mutableListOf<Validator>()
/**
* 检查的 ID 将会在日日志中展示用于 Debug
*/
val validateId = UUID.randomUUID().toString().substring(0..6)
/**
* 要求用户为登入状态
*/
suspend fun requireLogin() {
addValidator {
isLogin(token)
}
}
/**
* 检查用户权限中是否包含 [required],该方案将自动检查用户是否登入,未登入时将自动失败
*/
suspend inline fun <reified R : Role> check(required: R) {
addValidator {
val user = getAuthenticationUser(token) ?: return@addValidator false
log.info("[$validateId] require $required for user ${user.id} provides ${user.userRole}")
user.check(required).also {
if (!it) {
log.info("[$validateId] check failed")
}
}
}
}
fun addValidator(validator: Validator) {
validators.add(validator)
}
internal suspend fun result(): Boolean {
return validators.all { it.validate() }
}
}
suspend fun validate(
authenticationToken: AuthenticationToken?, action: suspend UserValidatorDsl.() -> Unit
): AuthenticationUser? {
val userValidatorDsl = UserValidatorDsl(authenticationToken)
log.info("[${userValidatorDsl.validateId}] validate for $authenticationToken")
userValidatorDsl.action()
return if (!userValidatorDsl.result()) {
null
} else {
log.info("[${userValidatorDsl.validateId}] pass")
getAuthenticationUser(authenticationToken)
}
}
suspend fun update(user: AuthenticationUser) {
redis.keys("$redisKeyPrefix-${user.id}-*").singleOrNull()
?.let {
redis.set(it, user)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/security/RedisAuthenticationService.kt | 128319638 |
@file:UseContextualSerialization
package cn.llonvne.security
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseContextualSerialization
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
private val json = Json {
encodeDefaults = true
}
fun normalUserRole() = json.encodeToString(UserRole.default())
inline fun <reified R : Role> List<Role>.check(required: R): Boolean {
return map { provide ->
required.check(provide)
}.contains(true)
}
val Role.asJson: String
get() = json.encodeToString(this)
inline fun <reified R : Role> AuthenticationUser.check(required: R): Boolean {
return userRole.roles.check(required)
}
@Serializable
data class UserRole(val roles: List<Role> = listOf()) {
companion object {
fun default() = UserRole(
TeamRole.default()
)
}
override fun toString(): String {
return roles.toString()
}
/**
* 将 [UserRole] 转换为 json 字符串
*/
val asJson get() = json.encodeToString(this)
/**
* 获取所有的 [TeamIdRole]
* @param teamId 如果为 null 则返回所有的 [TeamIdRole],否则返回 [TeamIdRole.teamId] 为 [teamId] 的 [TeamIdRole]
*/
fun groupIdRoles(teamId: Int? = null): List<TeamIdRole> {
val teamIdRoles = roles.filterIsInstance<TeamIdRole>()
return if (teamId == null) {
teamIdRoles
} else {
teamIdRoles.filter { it.teamId == teamId }
}
}
}
val AuthenticationUser.userRole: UserRole
get() = fromUserRoleString(role = role) ?: UserRole.default()
fun fromUserRoleString(role: String): UserRole? = runCatching {
json.decodeFromString<UserRole>(role)
}.getOrNull() | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/security/Role.kt | 2583330 |
package cn.llonvne.security
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
@Configuration
class BPasswordEncoder {
@Bean
fun passwordEncoder(): BCryptPasswordEncoder = BCryptPasswordEncoder()
companion object {
suspend operator fun <R> PasswordEncoder.invoke(block: suspend context(PasswordEncoder) () -> R): R =
block(this)
}
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/security/BPasswordEncoder.kt | 3514491718 |
package cn.llonvne.redis
import io.lettuce.core.RedisClient
import io.lettuce.core.api.async.RedisAsyncCommands
import kotlinx.coroutines.future.await
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.springframework.stereotype.Component
import kotlin.experimental.ExperimentalTypeInference
interface Redis {
suspend fun getString(key: String): String?
suspend fun set(key: String, value: String): String
suspend fun clear(key: String)
suspend fun keys(pattern: String): Set<String>
}
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
internal suspend inline fun <reified T> Redis.get(key: String): T? {
return this.getString(key).let { v ->
runCatching {
Json.decodeFromString<T>(v ?: return@let null)
}.getOrNull()
}
}
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
internal suspend inline fun <reified T> Redis.set(key: String, value: T): String {
return set(key, Json.encodeToString(value))
}
@Component
private class RedisImpl : Redis {
private val redisClient: RedisAsyncCommands<String, String> =
RedisClient.create("redis://localhost:6379").connect().async()
private suspend fun <R> onRedis(block: suspend RedisAsyncCommands<String, String>.() -> R): R {
return block(redisClient)
}
override suspend fun getString(key: String) = onRedis {
get(key).await()
}
override suspend fun set(key: String, value: String) = onRedis {
set(key, value).await()
}
override suspend fun clear(key: String) = onRedis {
del(key).await()
Unit
}
override suspend fun keys(pattern: String): Set<String> = onRedis {
keys(pattern).await().toSet()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/redis/Redis.kt | 3679579872 |
package cn.llonvne
import io.kvision.remote.getAllServiceManagers
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@SpringBootApplication(
exclude = [org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration::class,
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration::class]
)
class KVApplication {
@Bean
fun getManagers() = getAllServiceManagers()
}
fun main(args: Array<String>) {
runApplication<KVApplication>(*args)
}
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class PingService : IPingService {
override suspend fun ping(message: String): String = "Hello From Backend"
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/Main.kt | 1704078787 |
package cn.llonvne
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* 获得 Logger 实例,默认使用 [LoggerFactory.getLogger] 构建
*/
inline fun <reified T> T.getLogger(): Logger = LoggerFactory.getLogger(T::class.java)
/**
* 将 [value] 的 hashcode 作为标识符,执行 [action]
*/
@OptIn(ExperimentalContracts::class)
suspend fun <T, R> Logger.track(vararg value: T, action: suspend Logger.() -> R): R {
contract {
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
}
return TrackedLogger(this, value.toList()).action()
}
/**
* 带有标识符号(Hashcode)的Logger
*/
class TrackedLogger<T>(private val logger: Logger, private val value: T) : Logger by logger {
override fun info(msg: String?) {
logger.info("[id-${value.hashCode()}] $msg")
}
override fun warn(msg: String?) {
logger.warn("[id-${value.hashCode()}] $msg")
}
override fun error(msg: String?) {
logger.error("[id-${value.hashCode()}] $msg")
}
override fun debug(msg: String?) {
logger.debug("[id-${value.hashCode()}] $msg")
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/Logger.kt | 1336195559 |
package cn.llonvne
import cn.llonvne.database.entity.def.authenticationUser
import cn.llonvne.entity.AuthenticationUser
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Suppress("ACTUAL_WITHOUT_EXPECT")
actual class UserService(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val database: R2dbcDatabase
) : IUserService {
private val userMeta = Meta.authenticationUser
class UserNotFound : Exception()
override suspend fun byId(id: Int): AuthenticationUser {
val query = QueryDsl.from(userMeta)
.where {
userMeta.id.eq(id)
}
return database.runQuery(query).firstOrNull() ?: throw UserNotFound()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/UserService.kt | 153757383 |
package cn.llonvne
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.constants.Frontend
import cn.llonvne.entity.group.GroupId
import cn.llonvne.model.RoutingModule
import cn.llonvne.site.*
import cn.llonvne.site.contest.ContestDetail
import cn.llonvne.site.contest.contest
import cn.llonvne.site.contest.createContest
import cn.llonvne.site.mine.mine
import cn.llonvne.site.problem.createProblem
import cn.llonvne.site.problem.detail.detail
import cn.llonvne.site.problem.problems
import cn.llonvne.site.share.CodeLoader
import cn.llonvne.site.share.share
import cn.llonvne.site.team.TeamIndex
import cn.llonvne.site.team.show.showGroup
import cn.llonvne.site.team.teamCreate
import io.kvision.*
import io.kvision.html.div
import io.kvision.navigo.Match
import io.kvision.navigo.Navigo
import io.kvision.routing.Routing
import io.kvision.theme.ThemeManager
import kotlinx.browser.window
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlin.js.RegExp
val AppScope = CoroutineScope(window.asCoroutineDispatcher())
class App : Application() {
init {
ThemeManager.init()
}
private fun failTo404(routing: Routing, block: () -> Unit) = kotlin.runCatching { block() }.onFailure {
routing.navigate("/404")
throw it
}
override fun start(state: Map<String, Any>) {
val routing = RoutingModule.routing
routing.on(Frontend.Index.uri, {
layout(routing) {
index(routing)
}
}).on(Frontend.Problems.uri, {
layout(routing) {
problems(routing)
}
}).on(Frontend.Register.uri, {
layout(routing) {
registerPanel(routing)
}
}).on(Frontend.Problems.Create.uri, {
layout(routing) {
createProblem(routing)
}
}).on(RegExp("^problems/(.*)"), { match: Match ->
failTo404(routing) {
layout(routing) {
detail(div { }, (match.data[0] as String).toInt())
}
}
}).on(Frontend.Mine.uri, {
layout(routing) {
mine()
}
}).on(Frontend.Submission.uri, {
layout(routing) {
submission(routing)
}
}).on("/playground", { match: Match ->
layout(routing) {
playground()
}
}).on(RegExp("^code/(.*)"), { match: Match ->
failTo404(routing) {
layout(routing) {
submissionDetail(routing, (match.data[0] as String).toInt())
}
}
}).on("/contest/create", {
failTo404(routing) {
layout(routing) {
createContest()
}
}
})
.on("/contest", {
failTo404(routing) {
layout(routing) {
contest()
}
}
})
.on(RegExp("^contest/(.*)"), {
failTo404(routing) {
layout(routing) {
ContestDetail.from(it.data[0] as String).show(div { })
}
}
})
.on(RegExp("^share/(.*)"), {
failTo404(routing) {
layout(routing) {
val id = it.data[0] as String
val intId = id.toIntOrNull()
if (intId != null) {
share(
intId, CodeLoader.id()
)
} else {
share(
id, CodeLoader.hash()
)
}
}
}
}).injectTeam(routing).on("/404", {
layout(routing) {
alert(AlertType.Danger) {
+"解析失败了"
}
}
}).notFound(
{
routing.navigate("/404")
},
).resolve()
Unit
}
private fun Navigo.injectTeam(routing: Routing): Navigo {
return on("/team", {
failTo404(routing) {
layout(routing) {
TeamIndex.from().show(div { })
}
}
}).on("/team/create", {
failTo404(routing) {
layout(routing) {
teamCreate(this, routing)
}
}
}).on(RegExp("^team/(.*)"), { match: Match ->
failTo404(routing) {
layout(routing) {
val id = match.data[0] as String
val intId = id.toIntOrNull()
if (intId != null) {
showGroup(div { }, GroupId.IntGroupId(intId), routing)
} else if (id.length == 36) {
showGroup(div { }, GroupId.HashGroupId(id), routing)
} else {
showGroup(div { }, GroupId.ShortGroupName(id), routing)
}
}
}
})
}
}
fun main() {
startApplication(
::App,
module.hot,
BootstrapModule,
BootstrapCssModule,
CoreModule,
TabulatorModule,
TabulatorCssBootstrapModule,
ChartModule,
FontAwesomeModule,
ToastifyModule,
TomSelectModule,
)
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/App.kt | 3957283671 |
package cn.llonvne.message
import cn.llonvne.message.Message.ToastMessage
import cn.llonvne.message.MessageLevel.*
import io.kvision.toast.Toast
import io.kvision.toast.ToastOptions
import io.kvision.toast.ToastPosition
object Messager {
fun send(message: Message) = when (message) {
is ToastMessage -> {
toastByLevel(message.level, message.message)
}
}
/**
* 将 [cn.llonvne.message.MessageLevel] 转换成 Toast 的登记并发出
*/
private fun toastByLevel(level: MessageLevel, rawMessage: String) {
when (level) {
Info -> Toast.info(rawMessage, options = ToastOptions(ToastPosition.BOTTOMRIGHT))
Warning -> Toast.warning(rawMessage, options = ToastOptions(ToastPosition.BOTTOMRIGHT))
Danger -> Toast.danger(rawMessage, options = ToastOptions(ToastPosition.BOTTOMRIGHT))
Success -> Toast.success(rawMessage, options = ToastOptions(ToastPosition.BOTTOMRIGHT))
}
}
fun toastInfo(message: String) = send(
ToastMessage(
Info, message
)
)
fun toastError(message: String) = send(
ToastMessage(Danger, message)
)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/message/Messager.kt | 4022765798 |
package cn.llonvne.compoent
import cn.llonvne.constants.Authentication
import io.kvision.form.FormPanel
import io.kvision.form.text.Password
import io.kvision.form.text.Text
import kotlin.reflect.KProperty1
inline fun <reified K : Any> FormPanel<K>.addUsername(key: KProperty1<K, String?>) =
add(key,
Text(label = "username") { placeholder = "输入你的用户名" },
required = true,
requiredMessage = "必须输入你的用户名",
validator = { text: Text -> Authentication.User.Name.check(text.getValue()).isOk() },
validatorMessage = { text -> Authentication.User.Name.reason(text.getValue()) })
inline fun <reified K : Any> FormPanel<K>.addPassword(key: KProperty1<K, String?>) = add(
key,
Password(label = "password"),
required = true,
requiredMessage = "密码不得为空",
validator = { password -> Authentication.User.Password.check(password.value).isOk() },
validatorMessage = { password -> Authentication.User.Password.reason(password.value) }
) | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/UserCompoents.kt | 3490255969 |
package cn.llonvne.compoent
import io.kvision.core.Container
import io.kvision.html.Div
import io.kvision.html.code
import io.kvision.html.customTag
import io.kvision.html.div
fun Container.codeHighlighter(code: String, init: Div.() -> Unit = {}) = div {
customTag("pre") {
code(code) {
}
}.addAfterInsertHook {
js("hljs.highlightAll()")
Unit
}
init()
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/Highlighter.kt | 307796248 |
package cn.llonvne.compoent.layout
import io.kvision.core.Container
import io.kvision.navbar.NavbarType
import io.kvision.navbar.nav
import io.kvision.navbar.navLink
import io.kvision.navbar.navbar
import io.kvision.theme.Theme
import io.kvision.theme.ThemeManager
fun Container.footer() {
navbar(type = NavbarType.FIXEDBOTTOM) {
nav {
navLink("Llonvne/OnlineJudge","https://github.com/Llonvne/OnlineJudge")
}
nav(rightAlign = true) {
navLink("浅色") {
onClick {
ThemeManager.theme = Theme.LIGHT
}
}
navLink("深色") {
onClick {
ThemeManager.theme = Theme.DARK
}
}
navLink("自动") {
onClick {
ThemeManager.theme = Theme.AUTO
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/layout/Footer.kt | 2544238678 |
package cn.llonvne.compoent.layout
import cn.llonvne.AppScope
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.constants.Frontend
import cn.llonvne.kvision.service.IAuthenticationService.GetLoginInfoResp.Login
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.site.loginPanel
import io.kvision.core.Container
import io.kvision.dropdown.dropDown
import io.kvision.html.div
import io.kvision.navbar.*
import io.kvision.routing.Routing
import io.kvision.state.ObservableValue
import io.kvision.state.bind
import kotlinx.coroutines.launch
private fun Navbar.showNavigator(routing: Routing) {
nav {
navLink("主页", icon = "fas fa-house fa-solid") {
onClick {
routing.navigate(Frontend.Index.uri)
}
}
navLink("题库", icon = "fas fa-code fa-solid") {
onClick {
routing.navigate(Frontend.Problems.uri)
}
}
navLink("提交", icon = "fas fa-bars") {
onClick {
routing.navigate(Frontend.Submission.uri)
}
}
dropDown(
"比赛",
listOf(
"比赛信息" to "#/contest",
"创建" to "#/contest/create"
),
icon = "fas fa-star",
forNavbar = true
)
navLink("训练场", icon = "fas fa-play") {
onClick {
routing.navigate(Frontend.PlayGround.uri)
}
}
dropDown(
"队伍",
listOf(
"队伍" to "#/team",
"创建" to "#/team/create",
),
icon = "fas fa-star",
forNavbar = true
)
}
}
fun Container.header(routing: Routing) {
div { }.bind(AuthenticationModel.userToken) { token ->
navbar("OnlineJudge", type = NavbarType.STICKYTOP) {
showNavigator(routing)
if (token == null) {
nav(rightAlign = true) {
navLink("注册", icon = "fab fa-windows") {
onClick {
routing.navigate(Frontend.Register.uri)
}
}
navLink("登入", icon = "fab fa-windows") {
onClick {
loginPanel()
}
}
}
} else {
observableOf<Login>(null) {
setUpdater {
AuthenticationModel.info()
}
sync(nav(rightAlign = true) { }) { info ->
dropDown(
info?.username.toString(),
listOf(
"我的主页" to "#/me",
"Forms" to "#!/forms",
),
icon = "fas fa-star",
forNavbar = true
)
navLink("登出") {
onClick {
Messager.toastInfo(AuthenticationModel.logout().toString())
}
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/layout/Header.kt | 771267140 |
package cn.llonvne.compoent
import cn.llonvne.constants.Site
import io.kvision.core.Container
import io.kvision.html.button
import io.kvision.routing.Routing
fun Container.navigateButton(routing: Routing, to: Site) {
button(to.name) {
onClick {
routing.navigate(to.uri)
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/NavigatorButton.kt | 635938340 |
package cn.llonvne.compoent
import io.kvision.core.Component
import io.kvision.tabulator.ColumnDefinition
fun <T : Any> defineColumn(title: String, format: (data: T) -> Component): ColumnDefinition<T> {
return ColumnDefinition(title, formatterComponentFunction = { _, _, e ->
format(e)
})
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/ColumnDefinition.kt | 1690206708 |
package cn.llonvne.compoent
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.entity.types.badge.BadgeColorGetter
import cn.llonvne.entity.types.badge.cssClass
import io.kvision.core.Container
import io.kvision.html.Span
import io.kvision.html.span
import io.kvision.state.ObservableValue
import io.kvision.state.bind
fun <E : BadgeColorGetter> Container.badgeGroup(
lst: Collection<E>, display: Span.(E) -> Unit
) {
span {
lst.forEach { tag ->
span {
display(tag)
addCssClass("badge")
addCssClass("p-2")
addCssClass("border")
addCssClass(
tag.color.cssClass
)
}
}
}
}
fun Container.badge(badgeColor: BadgeColor, display: Span.() -> Unit) = span {
display()
addCssClass("badge")
addCssClass("p-2")
addCssClass("border")
addCssClass(
badgeColor.cssClass
)
}
interface BadgesDsl {
fun add(
color: BadgeColor? = null, action: Span.() -> Unit
)
fun <V> addBind(observableValue: ObservableValue<V>, action: Span.(V) -> Unit)
}
private class BadgesImpl(private val target: Container) : BadgesDsl {
private var index = 0
override fun add(color: BadgeColor?, action: Span.() -> Unit) {
target.badge(color ?: BadgeColor.entries[index++ % BadgeColor.entries.size]) {
action()
}
}
override fun <V> addBind(observableValue: ObservableValue<V>, action: Span.(V) -> Unit) {
target.badge(BadgeColor.entries[index++ % BadgeColor.entries.size]) {}.bind(observableValue) {
action(it)
}
}
}
fun Container.badges(action: BadgesDsl.() -> Unit) {
BadgesImpl(this).action()
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/BadgeGroup.kt | 3954579926 |
package cn.llonvne.compoent.team
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.KickGroupResp.*
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
class KickMemberResolver(
private val groupId: GroupId,
) {
suspend fun resolve(kickedMemberId: Int) {
when (val resp = TeamModel.kick(groupId, kickedMemberId)) {
is GroupIdNotFound -> Messager.toastInfo("小组不存在,可能是小组已经被删除")
is KickMemberGroupIdRoleFound -> Messager.toastInfo("尝试踢出的成员未拥有本组权限(可能已经退出或已经被踢出)")
is KickMemberNotFound -> Messager.toastInfo("被踢出的成员不存在")
Kicked -> Messager.toastInfo("踢出成功")
PermissionDenied -> Messager.toastInfo("您还未登入,或者登入凭证已失效")
is PermissionDeniedWithMessage -> Messager.toastInfo(resp.message)
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/team/KickMemberResolver.kt | 1484669337 |
package cn.llonvne.compoent.team
import cn.llonvne.AppScope
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.JoinGroupResp.*
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
import cn.llonvne.security.AuthenticationToken
import io.kvision.routing.Routing
import kotlinx.coroutines.launch
class JoinGroupResolver(private val routing: Routing) {
fun resolve(groupId: GroupId, groupName: String, token: AuthenticationToken) {
AppScope.launch {
when (TeamModel.join(token, groupId)) {
is GroupIdNotFound -> Messager.toastError("小组不存在,可能是小组已经被删除")
is Joined -> joined(groupName, groupId)
PermissionDenied -> Messager.toastError("您还未登入,或者登入凭证已失效")
is Reject -> Messager.toastInfo("你的加入请求被拒绝")
is NoManagersFound -> Messager.toastInfo("没有找到管理员,无法审批加入(这有可能是该小组管理员处于异常状态)")
}
}
}
private fun joined(groupName: String, groupId: GroupId) {
Messager.toastInfo("加入成功,$groupName 欢迎您")
routing.navigate("/team/${groupId.path}")
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/team/JoinGroupResolver.kt | 2903551447 |
package cn.llonvne.compoent.team
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.BeUpOrDowngradedUserNotfound
import cn.llonvne.kvision.service.IGroupService.DowngradeToMemberResp.DowngradeToMemberOk
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.GroupMemberDto
import cn.llonvne.kvision.service.IGroupService.UserAlreadyHasThisRole
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
class DowngradeToGroupMemberResolver(private val groupId: GroupId) {
suspend fun resolve(user: GroupMemberDto) {
when (val resp = TeamModel.downgradeToMember(groupId, user.userId)) {
is BeUpOrDowngradedUserNotfound -> Messager.toastInfo("用户不存在")
is DowngradeToMemberOk -> Messager.toastInfo("降级成功")
is GroupIdNotFound -> Messager.toastInfo("团队不存在")
is PermissionDeniedWithMessage -> Messager.toastInfo(resp.message)
is UserAlreadyHasThisRole -> Messager.toastInfo("用户已经是成员")
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/team/DowngradeToGroupMemberResolver.kt | 1098336671 |
package cn.llonvne.compoent.team
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.html.button
class GroupMemberQuitResolver(
private val groupId: GroupId
) {
fun load(root: Container) {
root.button("退出小组") {
onClickLaunch {
when (val resp = TeamModel.quit(groupId)) {
is GroupIdNotFound -> Messager.toastError("小组${resp.groupId}不存在")
PermissionDenied -> Messager.toastError("权限不足")
IGroupService.QuitOk -> Messager.toastInfo("退出成功")
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/team/GroupMemberQuitResolver.kt | 1303395303 |
package cn.llonvne.compoent.team
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.GroupMemberDto
import cn.llonvne.kvision.service.IGroupService.UpgradeGroupManagerResp.UpgradeManagerOk
import cn.llonvne.kvision.service.PermissionDeniedWithMessage
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
class UpgradeToGroupManagerResolver(private val groupId: GroupId) {
suspend fun resolve(user: GroupMemberDto) {
when (val resp = TeamModel.upgradeGroupManger(groupId, user.userId)) {
is GroupIdNotFound -> Messager.toastInfo("未找到该小组-${groupId}")
is PermissionDeniedWithMessage -> Messager.toastInfo(resp.message)
is IGroupService.UpOrDowngradeToIdNotMatchToGroupId -> Messager.toastInfo("更新的角色不匹配")
UpgradeManagerOk -> Messager.toastInfo("升级成功")
is IGroupService.UserAlreadyHasThisRole -> Messager.toastInfo("该用户已经是管理员了")
is IGroupService.BeUpOrDowngradedUserNotfound -> Messager.toastInfo("未找到该用户在该小组-${user.username}")
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/team/UpgradeToGroupManagerResolver.kt | 2623815774 |
package cn.llonvne.compoent
import cn.llonvne.entity.types.ProblemStatus
import cn.llonvne.entity.types.ProblemStatus.*
import io.kvision.core.Col
import io.kvision.core.Color
import io.kvision.core.Container
import io.kvision.html.span
fun Container.problemStatus(status: ProblemStatus) = span {
when (status) {
NotLogin -> {
+"未登入"
}
NotBegin -> {
+"未作答"
}
Accepted -> {
+status.name
color = Color.name(Col.GREEN)
}
WrongAnswer -> {
+status.name
color = Color.name(Col.RED)
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/ProblemStatus.kt | 3257297088 |
package cn.llonvne.compoent
import io.kvision.core.Container
import io.kvision.html.I
import io.kvision.html.i
private fun fa(name: String) = "fa-$name"
private fun fas(vararg names: String) = names.map {
fa(it)
}.joinToString(" ")
private const val SOLID = "solid"
private const val SHAKE = "shake"
private fun Container.faIcon(vararg names: String, init: I.() -> Unit) {
i(className = fas(*names)) {
init()
}
}
fun Container.circleCheck(init: I.() -> Unit = {}) {
faIcon(SOLID, "circle-check", init = init)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/Icon.kt | 1121379542 |
package cn.llonvne.compoent
import io.kvision.core.Container
import io.kvision.html.Div
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.p
enum class AlertType(val id: String) {
Primary("primary"),
Secondary("secondary"),
Success("success"),
Danger("danger"),
Warning("warning"),
Info("info"),
Light("light"),
Dark("dark")
}
fun Container.alert(type: AlertType, init: Div.() -> Unit) {
div(className = "p-2") {
div(className = "alert alert-${type.id}") {
setAttribute("role", "alert")
init()
}
}
}
fun Container.loading() {
alert(AlertType.Light) {
h1 { +"正在加载中" }
p {
+"请耐心等待哦..."
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/Loading.kt | 3810791418 |
package cn.llonvne.compoent.observable
import cn.llonvne.AppScope
import cn.llonvne.compoent.loading
import io.kvision.core.Container
import io.kvision.state.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.experimental.ExperimentalTypeInference
data class ObservableDsl<V>(
private val obv: ObservableValue<V?>,
private var updater: suspend () -> V? = { null }
) : ObservableState<V?> {
fun setUpdater(updater: suspend () -> V?) {
this.updater = updater
}
fun getUpdater() = updater
fun setObv(value: V?) {
obv.value = value
}
fun <T : Container> T.sync(action: T.(V?) -> Unit): T {
this.bind(this@ObservableDsl) {
action(it)
}
return this
}
fun <T : Container> sync(container: T, action: T.(V?) -> Unit): T {
container.sync(action)
return container
}
fun Container.syncNotNull(action: Container.(V) -> Unit) {
this.bind(this@ObservableDsl) {
if (it != null) {
action(it)
}
}
}
fun <T : Container> syncNotNull(
container: T,
onNull: T.() -> Unit = { loading() },
action: T.(V) -> Unit
) {
container.sync { value ->
if (value != null) {
action(value)
} else {
onNull()
}
}
}
override fun getState(): V? {
return obv.getState()
}
override fun subscribe(observer: (V?) -> Unit): () -> Unit {
return obv.subscribe(observer)
}
}
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
fun <V> observableOf(
initialValue: V?,
updater: suspend () -> V? = { null },
coroutineScope: CoroutineScope = AppScope,
action: ObservableDsl<V>.() -> Unit,
): ObservableDsl<V> {
val observableDsl = ObservableDsl(
obv = ObservableValue(initialValue),
updater = updater,
)
action(observableDsl)
coroutineScope.launch {
observableDsl.setObv(observableDsl.getUpdater().invoke())
}
return observableDsl
}
data class ObservableListDsl<V>(
private val obvListWrapper: ObservableListWrapper<V>,
private var updater: suspend () -> List<V> = { emptyList() },
private val coroutineScope: CoroutineScope
) : ObservableList<V> by obvListWrapper, ObservableState<List<V>> by obvListWrapper {
fun setUpdater(updater: suspend () -> List<V>) {
this.updater = updater
}
fun updateList(updater: suspend () -> List<V>) {
coroutineScope.launch {
obvListWrapper.clear()
obvListWrapper.addAll(updater.invoke())
}
}
fun setObList(value: List<V>) {
obvListWrapper.clear()
obvListWrapper.addAll(value)
}
fun getUpdater() = updater
override fun getState(): List<V> {
return obvListWrapper
}
override fun subscribe(observer: (List<V>) -> Unit): () -> Unit {
obvListWrapper.onUpdate += observer
observer(this)
return {
obvListWrapper.onUpdate -= observer
}
}
}
fun <V> observableListOf(
initialValue: MutableList<V> = mutableListOf(),
updater: suspend () -> List<V> = { emptyList<V>() },
coroutineScope: CoroutineScope = AppScope,
action: ObservableListDsl<V>.() -> Unit
) {
val observableListDsl = ObservableListDsl(
ObservableListWrapper(initialValue), updater, coroutineScope
)
action(observableListDsl)
coroutineScope.launch {
observableListDsl.setObList(observableListDsl.getUpdater().invoke())
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/observable/ObservableUtils.kt | 1874550701 |
package cn.llonvne.compoent.submission
import cn.llonvne.dtos.SubmissionSubmit
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.problem.SubmissionVisibilityType
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.message.Messager
import cn.llonvne.model.SubmissionModel
class SubmitProblemResolver(
private val contestId: ContestId? = null
) {
suspend fun resolve(problemId: Int, data: SubmissionSubmit) {
val submissionVisibilityType = data.visibilityTypeStr.let {
SubmissionVisibilityType.entries[it?.toIntOrNull() ?: return Messager.toastInfo("提交可见性ID无效")]
}
SubmissionModel.submit(
ISubmissionService.ProblemSubmissionReq(
problemId = problemId,
code = data.code ?: return Messager.toastInfo("代码不可以为空"),
visibilityType = submissionVisibilityType,
languageId = data.languageId?.toIntOrNull() ?: return Messager.toastInfo("语言无效或为空"),
contestId = contestId
)
) {
val passerResult = it.problemTestCases.passer.pass(it.submissionTestCases)
PasserResultShower.from(passerResult, codeId = it.codeId).show()
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/submission/SubmitProblemResolver.kt | 1685890355 |
package cn.llonvne.compoent.submission
import cn.llonvne.compoent.badges
import cn.llonvne.entity.problem.context.passer.PasserResult
import cn.llonvne.model.RoutingModule
import cn.llonvne.site.BooleanPasserResultDisplay
import io.kvision.core.onClickLaunch
import io.kvision.modal.Dialog
interface PasserResultShower {
suspend fun show()
companion object {
fun from(passerResult: PasserResult, codeId: Int): PasserResultShower {
return when (passerResult) {
is PasserResult.BooleanResult -> BooleanResultPasserResultShower(
codeId, passerResult
)
}
}
}
}
private class BooleanResultPasserResultShower(
private val codeId: Int,
private val passerResult: PasserResult.BooleanResult
) :
PasserResultShower {
val booleanPasserResultDisplay = BooleanPasserResultDisplay(passerResult)
val dialog = Dialog<Unit>(caption = "评测结果") {
booleanPasserResultDisplay.load(this)
badges {
add {
+"详情"
onClickLaunch {
RoutingModule.routing.navigate("/share/$codeId")
}
}
}
}
override suspend fun show() {
dialog.show()
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/submission/PasserResultShower.kt | 2471169506 |
package cn.llonvne.compoent
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.p
interface NotFoundAble {
val header: String
val notice: String
val errorCode: String
}
fun Container.notFound(header: String, notice: String, errorCode: String) {
div(className = "p-2") {
div(className = "alert alert-danger") {
setAttribute("role", "alert")
h1 {
+header
}
p(className = "p-1") {
+notice
}
div {
+"ErrorCode:${errorCode}"
}
}
}
}
fun <T : NotFoundAble> Container.notFound(notFoundAble: T) {
div(className = "p-2") {
div(className = "alert alert-danger") {
setAttribute("role", "alert")
h1 {
+notFoundAble.header
}
p(className = "p-1") {
+notFoundAble.notice
}
div {
+"ErrorCode:${notFoundAble.errorCode}"
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/compoent/NotFound.kt | 678620623 |
package cn.llonvne.loader
import cn.llonvne.AppScope
import io.kvision.state.ObservableValue
import kotlinx.coroutines.launch
import kotlin.experimental.ExperimentalTypeInference
interface Loadable<Data> {
suspend fun load(): ObservableValue<Data?>
companion object {
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
fun <Data : Any> load(loader: suspend () -> Data): Loadable<Data> {
return LoadableImpl(loader)
}
}
}
private class LoadableImpl<Data : Any>(private val loader: suspend () -> Data) : Loadable<Data> {
private val observableData = ObservableValue<Data?>(null)
override suspend fun load(): ObservableValue<Data?> {
AppScope.launch {
observableData.value = loader.invoke()
}
return observableData
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/loader/Loadable.kt | 2768785658 |
package cn.llonvne.loader
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/loader/DataLoader.kt | 2608015915 |
package cn.llonvne.model
import kotlinx.browser.localStorage
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.w3c.dom.get
import org.w3c.dom.set
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
object Storage {
interface RememberObject<K> : ReadWriteProperty<Any?, K> {
fun get(): K
fun set(k: K)
fun clear()
}
inline fun <reified K> remember(
initial: K,
key: String,
): RememberObject<K> {
if (localStorage[key] == "" && localStorage[key] == null) {
localStorage[key] = Json.encodeToString(initial)
}
return object : RememberObject<K> {
private val observers = mutableListOf<(K) -> Unit>()
override fun getValue(thisRef: Any?, property: KProperty<*>): K {
return get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: K) {
observers.forEach { it.invoke(value) }
set(value)
}
override fun get(): K {
val result = localStorage[key] ?: return initial
return Json.decodeFromString(result)
}
override fun set(k: K) {
if (k == null) {
clear()
} else {
localStorage[key] = Json.encodeToString(k)
}
}
override fun clear() {
localStorage.removeItem(key)
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/Storage.kt | 3119292873 |
package cn.llonvne.model
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestContext
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.kvision.service.IContestService
import cn.llonvne.site.contest.CreateContestForm
import io.kvision.remote.getService
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toKotlinInstant
import kotlinx.datetime.toLocalDateTime
object ContestModel {
private val contestService = getService<IContestService>()
suspend fun addProblem(problemId: String) = contestService.addProblem(
AuthenticationModel.userToken.value, problemId
)
suspend fun create(
createContestForm: CreateContestForm, problems: List<ContestContext.ContestProblem>
): IContestService.CreateContestResp {
return contestService.create(
authenticationToken = AuthenticationModel.userToken.value, IContestService.CreateContestReq(
title = createContestForm.title,
description = createContestForm.description,
startAt = createContestForm.startAt.toKotlinInstant()
.toLocalDateTime(timeZone = TimeZone.currentSystemDefault()),
endAt = createContestForm.endAt.toKotlinInstant()
.toLocalDateTime(timeZone = TimeZone.currentSystemDefault()),
contestScoreType = Contest.ContestScoreType.valueOf(createContestForm.contestScoreTypeStr),
problems = problems,
rankType = Contest.ContestRankType.valueOf(createContestForm.rankTypeStr)
)
)
}
suspend fun load(contestId: ContestId) = contestService.load(
AuthenticationModel.userToken.value, contestId
)
suspend fun contextSubmissions(contestId: ContestId) = contestService.contextSubmission(
AuthenticationModel.userToken.value, contestId
)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/ContestModel.kt | 794816151 |
package cn.llonvne.model
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.group.GroupLoader
import cn.llonvne.kvision.service.ClientError
import cn.llonvne.kvision.service.IGroupService
import cn.llonvne.kvision.service.IGroupService.*
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.kvision.service.Validatable.Companion.Failed
import cn.llonvne.kvision.service.Validatable.Companion.Ok
import cn.llonvne.message.Messager
import cn.llonvne.security.AuthenticationToken
import io.kvision.remote.getService
object TeamModel {
private val teamService = getService<IGroupService>()
suspend fun create(create: CreateGroupReq): CreateGroupResp {
val token = AuthenticationModel.userToken.value ?: return PermissionDenied
when (val result = create.validate()) {
Ok -> return teamService.createTeam(token, create)
is Failed -> {
Messager.toastInfo(result.message)
return ClientError(result.message)
}
}
}
fun GroupLoader.Companion.of(groupId: GroupId): GroupLoader {
return GroupLoader {
load(groupId)
}
}
suspend fun load(groupId: GroupId): LoadGroupResp {
return teamService.load(AuthenticationModel.userToken.value, groupId)
}
suspend fun join(authenticationToken: AuthenticationToken, groupId: GroupId): JoinGroupResp {
return teamService.join(groupId, authenticationToken)
}
suspend fun quit(groupId: GroupId): QuitGroupResp {
return teamService.quit(groupId, AuthenticationModel.userToken.value)
}
suspend fun kick(groupId: GroupId, kickMemberId: Int): KickGroupResp {
return teamService.kick(AuthenticationModel.userToken.value, groupId, kickMemberId)
}
suspend fun upgradeGroupManger(groupId: GroupId, userId: Int): UpgradeGroupManagerResp {
return teamService.upgradeGroupManager(AuthenticationModel.userToken.value, groupId, userId)
}
suspend fun downgradeToMember(groupId: GroupId, userId: Int): DowngradeToMemberResp {
return teamService.downgradeToMember(AuthenticationModel.userToken.value, groupId, userId)
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/TeamModel.kt | 2874508436 |
package cn.llonvne.model
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeVisibilityType
import cn.llonvne.kvision.service.ICodeService
import cn.llonvne.kvision.service.ICodeService.*
import io.kvision.remote.getService
object CodeModel {
private val codeService = getService<ICodeService>()
suspend fun saveCode(
rawCode: String,
languageId: Int?
): SaveCodeResp = codeService.saveCode(
AuthenticationModel.userToken.value,
SaveCodeReq(rawCode, languageId = languageId, CodeVisibilityType.Public)
)
suspend fun getCode(shareId: Int) = codeService.getCode(
AuthenticationModel.userToken.value, shareId
)
suspend fun getCode(hash: String) = codeService.getCodeByHash(AuthenticationModel.userToken.value, hash)
suspend fun commit(sharCodeId: Int, content: String, type: ShareCodeCommentType) =
codeService.commit(CommitOnCodeReq(AuthenticationModel.userToken.value, content, sharCodeId, type))
suspend fun getCommentByCodeId(sharCodeId: Int) =
codeService.getComments(AuthenticationModel.userToken.value, sharCodeId)
suspend fun deleteCommentByIds(commentIds: List<Int>) = codeService.deleteComments(commentIds)
suspend fun setCodeVisibility(shareId: Int, result: CodeVisibilityType) =
codeService.setCodeVisibility(AuthenticationModel.userToken.value, shareId, result)
suspend fun setCodeCommentType(shareId: Int, type: CodeCommentType) =
codeService.setCodeCommentType(AuthenticationModel.userToken.value, shareId, type)
suspend fun setCodeCommentVisibilityType(
shareId: Int,
commentId: Int,
type: ShareCodeCommentType
) =
codeService.setCodeCommentVisibilityType(
AuthenticationModel.userToken.value,
shareId = shareId,
commentId = commentId, type
)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/CodeModel.kt | 4073373071 |
package cn.llonvne.model
import cn.llonvne.AppScope
import cn.llonvne.kvision.service.IAuthenticationService
import cn.llonvne.kvision.service.IAuthenticationService.GetLoginInfoResp.*
import cn.llonvne.kvision.service.IAuthenticationService.GetLogoutResp.Logout
import cn.llonvne.kvision.service.IAuthenticationService.LoginResult
import cn.llonvne.kvision.service.IAuthenticationService.LoginResult.SuccessfulLogin
import cn.llonvne.message.Messager
import cn.llonvne.security.AuthenticationToken
import io.kvision.remote.getService
import io.kvision.state.ObservableValue
import kotlinx.browser.localStorage
import kotlinx.coroutines.launch
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
object AuthenticationModel {
private val authenticationService = getService<IAuthenticationService>()
var userToken: ObservableValue<AuthenticationToken?> = ObservableValue(null)
init {
restore()
}
suspend fun register(username: String, password: String) = authenticationService.register(username, password)
suspend fun login(username: String, password: String): LoginResult {
val result = authenticationService.login(username, password)
when (result) {
is SuccessfulLogin -> {
userToken.value = result.token
save()
}
LoginResult.IncorrectUsernameOrPassword -> {
Messager.toastInfo("用户名或密码错误")
}
LoginResult.UserDoNotExist -> {
Messager.toastInfo("用户不存在")
}
LoginResult.BannedUser -> Messager.send(result.message)
}
return result
}
fun logout() {
AppScope.launch {
when (authenticationService.logout(userToken.value)) {
Logout -> {
Messager.toastInfo("登出成功")
}
}
}
userToken.value = null
clear()
restore()
}
private const val key = "authentication-key"
private fun save() {
localStorage.setItem(
key, Json.encodeToString(userToken.value)
)
}
private fun clear() {
localStorage.setItem(key, "")
}
private fun restore() {
val tokenStr = localStorage.getItem(key)
if (tokenStr.isNullOrEmpty()) {
return
}
userToken.value = Json.decodeFromString<AuthenticationToken?>(tokenStr)
AppScope.launch {
info()?.let { Messager.toastInfo("欢迎回来,${it.username}") }
?: run { userToken.value = null }
}
}
suspend fun info(): Login? {
return when (val resp = authenticationService.getLoginInfo(this.userToken.value)) {
is Login -> resp
LoginExpired -> null
NotLogin -> null
}
}
suspend fun mine() = authenticationService.mine(userToken.value)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/AuthenticationModel.kt | 1327053527 |
package cn.llonvne.model
import cn.llonvne.kvision.service.IJudgeService
import io.kvision.remote.getService
object JudgeModel {
private val judgeService = getService<IJudgeService>()
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/JudgeModel.kt | 3942560051 |
package cn.llonvne.model
import cn.llonvne.dtos.ProblemListDto
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.ProblemListShowType
import cn.llonvne.entity.problem.context.ProblemContext
import cn.llonvne.entity.problem.context.ProblemTestCases
import cn.llonvne.entity.problem.context.ProblemType
import cn.llonvne.entity.problem.context.ProblemVisibility
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.api.fromId
import cn.llonvne.kvision.service.IProblemService
import cn.llonvne.kvision.service.IProblemService.CreateProblemReq
import cn.llonvne.kvision.service.IProblemService.CreateProblemResp
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Message.ToastMessage
import cn.llonvne.message.MessageLevel
import cn.llonvne.message.Messager
import cn.llonvne.site.problem.CreateProblemForm
import io.kvision.remote.getService
object ProblemModel {
private val problemService = getService<IProblemService>()
suspend fun listProblem(
showType: ProblemListShowType = ProblemListShowType.All
) = problemService.list(AuthenticationModel.userToken.value,showType)
suspend fun create(problemForm: CreateProblemForm, testCases: ProblemTestCases): CreateProblemResp {
if (AuthenticationModel.userToken.value == null) {
Messager.send(ToastMessage(MessageLevel.Warning, "必须要登入才能发送消息哦"))
return PermissionDenied
}
return problemService.create(
AuthenticationModel.userToken.value,
CreateProblemReq(
problemForm.problemName,
problemForm.problemDescription,
ProblemContext(
inputDescription = problemForm.inputDescr,
outputDescription = problemForm.outputDescr,
hint = problemForm.hint,
testCases = testCases,
overall = problemForm.overall
),
authorId = problemForm.authorId,
memoryLimit = problemForm.memoryLimit,
timeLimit = problemForm.timeLimit,
visibility = problemForm.problemVisibilityInt.let {
ProblemVisibility.entries[it.toInt()]
},
type = problemForm.problemTypeInt.let {
ProblemType.entries[it.toInt()]
},
supportLanguages = problemForm.problemSupportLanguages.split(",")
.map { it.toInt() }.mapNotNull {
SupportLanguages.fromId(it)
}.map {
Language(
languageId = it.languageId,
languageName = it.languageName,
languageVersion = it.languageVersion
)
}
)
)
}
suspend fun getById(id: Int) = problemService.getById(id)
suspend fun search(text: String): List<ProblemListDto> {
return problemService.search(AuthenticationModel.userToken.value, text)
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/ProblemModel.kt | 3081363515 |
package cn.llonvne.model
import cn.llonvne.entity.ModifyUserForm
import cn.llonvne.kvision.service.IMineService
import io.kvision.remote.getService
object MineModel {
private val mineService = getService<IMineService>()
suspend fun dashboard() = mineService.dashboard(
AuthenticationModel.userToken.value
)
suspend fun users() = mineService.users()
suspend fun deleteUser(id: Int) = mineService.deleteUser(AuthenticationModel.userToken.value, id)
suspend fun modifyUser(result: ModifyUserForm?): Boolean {
if (result == null) {
return false
}
return mineService.modifyUser(AuthenticationModel.userToken.value, result)
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/MineModel.kt | 4155754027 |
package cn.llonvne.model
import io.kvision.routing.Routing
object RoutingModule {
val routing = Routing.init()
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/RoutingModule.kt | 1026730697 |
package cn.llonvne.model
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.kvision.service.*
import cn.llonvne.kvision.service.ISubmissionService.*
import cn.llonvne.kvision.service.ISubmissionService.CreateSubmissionReq.PlaygroundCreateSubmissionReq
import cn.llonvne.kvision.service.ISubmissionService.ProblemSubmissionResp.ProblemSubmissionRespImpl
import cn.llonvne.message.Messager
import cn.llonvne.site.PlaygroundSubmission
import io.kvision.remote.getService
object SubmissionModel {
private val submissionService = getService<ISubmissionService>()
suspend fun list() = submissionService.list(
ListSubmissionReq(AuthenticationModel.userToken.value)
)
suspend fun getById(id: Int): SubmissionGetByIdResp = submissionService.getById(id)
suspend fun codeGetById(id: Int) = submissionService.getViewCode(id)
suspend fun getSupportLanguage(problemId: Int) =
submissionService.getSupportLanguageId(AuthenticationModel.userToken.value, problemId)
suspend fun submit(playgroundSubmission: PlaygroundSubmission): CreateSubmissionResp {
return submissionService.create(
AuthenticationModel.userToken.value,
PlaygroundCreateSubmissionReq(
languageId = playgroundSubmission.language.toInt(),
rawCode = playgroundSubmission.code,
stdin = playgroundSubmission.stdin ?: "",
codeType = Code.CodeType.Playground
)
)
}
suspend fun getJudgeResultByCodeID(codeId: Int) =
submissionService.getOutputByCodeId(AuthenticationModel.userToken.value, codeId)
suspend fun getLastNPlaygroundSubmission(lastN: Int = 5) =
submissionService.getLastNPlaygroundSubmission(
AuthenticationModel.userToken.value, lastN
)
suspend fun getLastNProblemSubmission(
problemId: Int,
lastN: Int = 5
) = submissionService.getLastNProblemSubmission(
AuthenticationModel.userToken.value, problemId, lastN
)
suspend fun submit(
problemSubmissionReq: ProblemSubmissionReq,
onSuccess: suspend (ProblemSubmissionRespImpl) -> Unit
) {
when (val resp = submissionService.submit(AuthenticationModel.userToken.value, problemSubmissionReq)) {
LanguageNotFound -> Messager.toastInfo("提交的语言不受支持,请刷新网页重新提交")
PermissionDenied -> Messager.toastInfo("你还未登入,或者登入已经过期")
is PermissionDeniedWithMessage -> Messager.toastInfo(resp.message)
ProblemNotFound -> Messager.toastInfo("你提交的题目不存在或者设置了权限")
is ProblemSubmissionRespImpl -> onSuccess(resp)
is InternalError -> Messager.toastInfo(resp.reason)
}
}
suspend fun getParticipantContest(): GetParticipantContestResp {
return submissionService.getParticipantContest(AuthenticationModel.userToken.value)
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/model/SubmissionModel.kt | 1037643095 |
package cn.llonvne.site
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badge
import cn.llonvne.compoent.badges
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.kvision.service.CodeNotFound
import cn.llonvne.kvision.service.ISubmissionService.GetJudgeResultByCodeIdResp
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto.FailureReason.*
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.OutputDto.SuccessOutput
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput.SuccessPlaygroundOutput
import cn.llonvne.kvision.service.ISubmissionService.ProblemOutput.SuccessProblemOutput
import cn.llonvne.kvision.service.ISubmissionService.SubmissionNotFound
import cn.llonvne.kvision.service.JudgeResultParseError
import cn.llonvne.kvision.service.LanguageNotFound
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.SubmissionModel
import io.kvision.core.Container
import io.kvision.html.*
interface JudgeResultDisplay {
fun load(root: Container)
companion object {
fun empty() = object : JudgeResultDisplay {
override fun load(root: Container) {}
}
fun playground(codeId: Int, root: Container): JudgeResultDisplay = PlaygroundJudgeResultDisplay(codeId)
.also { it.load(root) }
fun problem(codeId: Int, div: Div): JudgeResultDisplay = ProblemJudgeResultDisplay(codeId)
.also { it.load(root = div) }
}
}
private class ProblemJudgeResultDisplay(
private val codeId: Int,
private val errorHandler: ErrorHandler<Int> = JudgeResultDisplayErrorHandler.getHandler()
) : JudgeResultDisplay {
override fun load(root: Container) {
observableOf<GetJudgeResultByCodeIdResp>(null) {
setUpdater { SubmissionModel.getJudgeResultByCodeID(codeId) }
root.syncNotNull { resp ->
when (resp) {
LanguageNotFound -> errorHandler.handleLanguageNotFound(this, codeId)
CodeNotFound -> errorHandler.handleCodeNotFound(this, codeId)
JudgeResultParseError -> errorHandler.handleJudgeResultParseError(this, codeId)
PermissionDenied -> Messager.toastInfo("请登入来查看对应评测结果")
SubmissionNotFound -> errorHandler.handleSubmissionNotFound(this, codeId)
is SuccessPlaygroundOutput -> error("这不应该发生")
is SuccessProblemOutput -> display(root, resp.problem)
}
}
}
}
private fun display(root: Container, judgeResult: ProblemJudgeResult) {
root.alert(AlertType.Dark) {
PasserResultDisplay.from(judgeResult.passerResult).load(root)
h4 {
+"测评详细结果"
}
p {
+"本处仅展示部分公开的测试用例"
addCssClass("small")
}
judgeResult.submissionTestCases.showOnJudgeResultDisplay
.forEach { testcase ->
alert(AlertType.Light) {
div {
p {
+"输入:"
customTag("pre") {
customTag("code") {
+testcase.input
}
}
+"期望输出:"
customTag("pre") {
customTag("code") {
+testcase.expect
}
}
+"实际输出:"
customTag("pre") {
customTag("code") {
+(testcase.outputStr ?: "<Null>")
}
}
}
}
badges {
if (testcase.outputStr?.trimIndent() == testcase.expect) {
add(BadgeColor.Green) {
+"通过"
}
} else {
add(BadgeColor.Red) {
+"失败"
}
}
}
}
}
}
}
}
private class PlaygroundJudgeResultDisplay(
private val codeId: Int,
private val errorHandler: ErrorHandler<Int> = JudgeResultDisplayErrorHandler.getHandler(),
) : JudgeResultDisplay {
override fun load(root: Container) {
observableOf<GetJudgeResultByCodeIdResp>(null) {
setUpdater { SubmissionModel.getJudgeResultByCodeID(codeId) }
root.syncNotNull { resp ->
when (resp) {
LanguageNotFound -> errorHandler.handleLanguageNotFound(this, codeId)
CodeNotFound -> errorHandler.handleCodeNotFound(this, codeId)
JudgeResultParseError -> errorHandler.handleJudgeResultParseError(this, codeId)
PermissionDenied -> Messager.toastInfo("请登入来查看对应评测结果")
SubmissionNotFound -> errorHandler.handleSubmissionNotFound(this, codeId)
is SuccessPlaygroundOutput -> display(this, resp.outputDto)
is SuccessProblemOutput -> error("这不应该发生")
}
}
}
}
fun onCompilerError(root: Container, compileError: CompileError) {
root.alert(AlertType.Danger) {
h3 {
+"编译错误"
}
p {
+compileError.compileErrMessage
}
}
}
fun onCompileResultNotFound(root: Container, compileResultNotFound: CompileResultNotFound) {
root.alert(AlertType.Danger) {
h3 {
+"未找到编译结果"
}
p {
+"这应该不是您的问题,请尝试重新提交"
}
}
}
fun onRunResultIsNull(root: Container, runResultIsNull: RunResultIsNull) {
root.alert(AlertType.Danger) {
h3 {
+"未找到运行结果"
}
p {
+"这应该不是您的问题,请尝试重新提交"
}
}
}
fun onTargetResultNotFound(root: Container, targetFileNotExist: TargetResultNotFound) {
root.alert(AlertType.Danger) {
h3 {
+"未找到运行目标"
}
p {
+"这应该不是您的问题,请尝试重新提交"
}
}
}
fun onSuccess(root: Container, successOutput: SuccessOutput) {
root.alert(AlertType.Success) {
h4 {
+"运行成功"
}
badge(BadgeColor.Blue) {
}
label {
+"标准输入"
}
p {
customTag("pre") {
code {
+successOutput.stdin
}
}
}
label {
+"标准输出"
}
p {
customTag("pre") {
code {
+successOutput.stdout
}
}
}
}
}
fun display(root: Container, outputDto: OutputDto) {
when (outputDto) {
is OutputDto.FailureOutput -> {
when (val reason = outputDto.reason) {
is CompileError -> onCompilerError(root, reason)
is CompileResultNotFound -> onCompileResultNotFound(root, reason)
is RunResultIsNull -> onRunResultIsNull(root, reason)
is TargetResultNotFound -> onTargetResultNotFound(root, reason)
}
}
is SuccessOutput -> onSuccess(root, outputDto)
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/JudgeResultDisplay.kt | 23617106 |
package cn.llonvne.site.problem
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.problem.context.ProblemTestCases
import cn.llonvne.entity.problem.context.ProblemTestCases.ProblemTestCase
import cn.llonvne.entity.problem.context.ProblemType
import cn.llonvne.entity.problem.context.ProblemVisibility
import cn.llonvne.entity.problem.context.TestCaseType
import cn.llonvne.entity.problem.context.passer.ProblemPasser
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.ProblemModel
import cn.llonvne.site.problem.detail.TestCasesShower
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onClickLaunch
import io.kvision.form.formPanel
import io.kvision.form.number.Numeric
import io.kvision.form.select.TomSelect
import io.kvision.form.text.RichText
import io.kvision.form.text.Text
import io.kvision.html.*
import io.kvision.routing.Routing
import io.kvision.state.bind
import io.kvision.utils.px
import kotlinx.serialization.Serializable
@Serializable
data class CreateProblemForm(
val problemName: String,
val problemDescription: String,
val timeLimit: Long,
val memoryLimit: Long,
val authorId: Int,
val problemVisibilityInt: String,
val problemTypeInt: String,
val overall: String,
val inputDescr: String,
val outputDescr: String,
val hint: String,
val problemSupportLanguages: String,
)
@Serializable
data class ProblemTestCaseForm(
val name: String,
val input: String,
val output: String,
val visibilityStr: String,
)
fun Container.createProblem(routing: Routing) {
alert(AlertType.Success) {
h1 {
+"创建题目"
}
p {
+"创建属于您自己的题目以供训练"
}
}
val testCases = ProblemTestCases(
listOf(), ProblemPasser.PassAllCases()
)
observableOf(ProblemTestCases(listOf(), ProblemPasser.PassAllCases())) {
div(className = "row") {
div(className = "col") {
alert(AlertType.Light) {
val panel = formPanel {
add(CreateProblemForm::problemName, Text(label = "题目名字"))
add(CreateProblemForm::problemDescription, Text(label = "题目描述"))
add(CreateProblemForm::timeLimit, Numeric(min = 0, max = 1_0000_0000, label = "时间限制"))
add(CreateProblemForm::memoryLimit, Numeric(min = 0, max = 1_0000_0000, label = "内存限制"))
add(CreateProblemForm::authorId, Numeric(min = 0, label = "作者ID"))
add(CreateProblemForm::overall, RichText(label = "题目要求"))
add(CreateProblemForm::inputDescr, Text(label = "输入描述"))
add(CreateProblemForm::outputDescr, Text(label = "输出描述"))
add(CreateProblemForm::hint, Text(label = "题目提示"))
add(
CreateProblemForm::problemVisibilityInt, TomSelect(
options = ProblemVisibility.entries.map {
it.ordinal.toString() to it.chinese
},
label = "题目可见性设置"
)
)
add(
CreateProblemForm::problemTypeInt, TomSelect(
options = ProblemType.entries.map {
it.ordinal.toString() to it.name
},
label = "题目类型"
)
)
add(
CreateProblemForm::problemSupportLanguages, TomSelect(
options = SupportLanguages.entries.map {
it.languageId.toString() to it.toString()
},
multiple = true,
label = "题目支持的语言类型"
)
)
}
panel.getChildren().forEach {
it.addCssClass("small")
}
sync(div { }) { testCases ->
button("提交").bind(AuthenticationModel.userToken) { token ->
if (token == null) {
disabled = true
Messager.toastInfo("您还没有登入,暂时无法创建问题")
}
onClickLaunch {
Messager.toastInfo("已经提交请求,请稍等")
Messager.toastInfo(
ProblemModel.create(
panel.getData(),
testCases ?: return@onClickLaunch Messager.toastInfo("内部错误")
).toString()
)
}
}
}
}
}
div(className = "col") {
alert(AlertType.Light) {
h4 {
+"测试样例"
}
sync(div { }) { cases ->
console.log(cases)
if (cases != null) {
TestCasesShower.from(cases.testCases, withoutTitle = true) { case ->
add {
+"删除"
onClick {
setObv(cases.copy(testCases = cases.testCases - case, passer = cases.passer))
}
}
}.load(this)
}
val testCaseForm = formPanel<ProblemTestCaseForm> {
add(ProblemTestCaseForm::name, Text(label = "测试样例名称"), required = true)
add(ProblemTestCaseForm::input, Text(label = "输入"), required = true)
add(ProblemTestCaseForm::output, Text(label = "输出"), required = true)
add(ProblemTestCaseForm::visibilityStr, TomSelect(
label = "类型",
options = TestCaseType.entries.map {
it.ordinal.toString() to it.chinese
}
), required = true)
getChildren().forEach { it.addCssClass("small") }
}
button("增加一个样例") {
onClickLaunch {
setObv(
testCases.copy(
(cases?.testCases ?: listOf()) +
testCaseForm.getData().let { form ->
ProblemTestCase(
"",
form.name,
form.input,
form.output,
form.visibilityStr.let {
TestCaseType.entries[it.toIntOrNull()
?: return@onClickLaunch Messager.toastInfo("测试样例类型无效")]
})
}
)
)
}
}
}
}
}
}
}
div {
marginBottom = 30.px
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/CreateProblem.kt | 374664952 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.