content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ru.alexadler9.weatherfetcher.data.local
import android.app.Application
/**
* Source for accessing user settings.
*/
class AppPreferencesSource(private val application: Application) {
/**
* Get the last city specified by user.
*/
fun getCity() = application.requireAppPreferences().getCity()
/**
* Save the city.
* @param city City name.
*/
fun setCity(city: String) {
application.requireAppPreferences().setCity(city)
}
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/data/local/AppPreferencesSource.kt | 1866574594 |
package ru.alexadler9.weatherfetcher.data
/**
* Repository for working with local app settings.
*/
interface PreferencesRepository {
/**
* Get the last city specified by user.
*/
fun getCity(): String
/**
* Save the city.
* @param city City name.
*/
fun setCity(city: String)
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/data/PreferencesRepository.kt | 3836854833 |
package ru.alexadler9.weatherfetcher.base
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
abstract class BaseViewModel<VIEW_STATE, VIEW_EVENT> : ViewModel() {
protected abstract val initialViewState: VIEW_STATE
/**
* Describes what screen state should be displayed right now (flows from ViewModel to View).
*/
private val _viewState by lazy { MutableStateFlow(initialViewState) }
val viewState: StateFlow<VIEW_STATE>
get() = _viewState
/**
* One-time events like showing Snackbar or Dialog, etc (flows from ViewModel to View).
*/
private val _viewEvents = Channel<VIEW_EVENT?>(Channel.BUFFERED)
val viewEvents = _viewEvents.receiveAsFlow()
/**
* Actions is the only legal way to tell something to ViewModel from a View (flows from View to ViewModel).
*/
private val actions = Channel<Action>(Channel.BUFFERED)
abstract fun reduce(action: Action, previousState: VIEW_STATE): VIEW_STATE?
init {
viewModelScope.launch {
actions.consumeEach { action ->
updateViewState(action)
}
}
}
fun processUiAction(action: Action) = viewModelScope.launch {
actions.send(action)
}
protected fun processDataAction(action: Action) = viewModelScope.launch {
actions.send(action)
}
protected fun sendViewEvent(event: VIEW_EVENT) = viewModelScope.launch {
_viewEvents.send(event)
_viewEvents.send(null)
}
private fun updateViewState(action: Action) {
val newViewState = reduce(action, _viewState.value)
if (newViewState != null) {
_viewState.value = newViewState
}
}
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/BaseViewModel.kt | 1940835347 |
package ru.alexadler9.weatherfetcher.base
inline fun <reified T> attempt(func: () -> T): Either<Throwable, T> = try {
Either.Right(func.invoke())
} catch (e: Throwable) {
Either.Left(e)
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/ext/EitherExt.kt | 3995508775 |
package ru.alexadler9.weatherfetcher.base
import android.text.Editable
fun String.toEditable(): Editable = Editable.Factory.getInstance().newEditable(this) | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/ext/StringExt.kt | 3408551038 |
package ru.alexadler9.weatherfetcher.base
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager
val Context.inputMethodManager: InputMethodManager
get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
fun Activity.hideKeyboard() {
inputMethodManager.hideSoftInputFromWindow(window.decorView.windowToken, 0)
}
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet
context.inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up
if (hasFocus) {
[email protected]()
// It’s very important to remove this listener once we are done
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/ext/KeyboardExt.kt | 835334017 |
package ru.alexadler9.weatherfetcher.base
sealed class Either<out LEFT, out RIGHT> {
class Left<LEFT>(val value: LEFT) : Either<LEFT, Nothing>()
class Right<RIGHT>(val value: RIGHT) : Either<Nothing, RIGHT>()
val isRight: Boolean
get() = this is Right
val isLeft: Boolean
get() = this is Left
inline fun <TYPE> fold(onError: (LEFT) -> TYPE, onSuccess: (RIGHT) -> TYPE): TYPE =
when (this) {
is Left -> onError(this.value)
is Right -> onSuccess(this.value)
}
inline fun <TYPE> map(transform: (RIGHT) -> TYPE): Either<LEFT, TYPE> = when (this) {
is Left -> Left(this.value)
is Right -> Right(transform(this.value))
}
inline fun <TYPE> mapLeft(transform: (LEFT) -> TYPE): Either<TYPE, RIGHT> = when (this) {
is Left -> Left(transform(this.value))
is Right -> Right(this.value)
}
}
inline fun <TYPE, LEFT, RIGHT> Either<LEFT, RIGHT>.flatMap(
transform: (RIGHT) -> Either<LEFT, TYPE>
): Either<LEFT, TYPE> = when (this) {
is Either.Left -> Either.Left(value)
is Either.Right -> transform(value)
} | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/Either.kt | 880030798 |
package ru.alexadler9.weatherfetcher.base
interface Action | weather-fetcher/app/src/main/java/ru/alexadler9/weatherfetcher/base/Action.kt | 2068824082 |
@file:OptIn(DelicateCoroutinesApi::class)
package cn.llonvne
import cn.llonvne.gojudge.api.LanguageDispatcher
import cn.llonvne.gojudge.api.LanguageFactory
import cn.llonvne.gojudge.api.SupportLanguages
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.benchmark.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.serialization.json.Json
import org.openjdk.jmh.annotations.Fork
import org.openjdk.jmh.annotations.Threads
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.timerTask
import kotlin.math.cos
import kotlin.math.sqrt
import kotlin.system.measureTimeMillis
import kotlin.time.Duration
@State(Scope.Benchmark)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
class JudgerBenchmark {
private lateinit var languageDispatcher: LanguageDispatcher
private val httpClient: HttpClient = HttpClient(OkHttp) {
install(ContentNegotiation) {
json(Json)
}
}
private fun default(judgeUrl: String): LanguageDispatcher {
return LanguageDispatcher.get(
LanguageFactory.get(
judgeUrl, httpClient = httpClient
)
)
}
@Setup
fun setUp() {
languageDispatcher = default("http://localhost:8081/")
}
@Benchmark
@Threads(20)
fun cppHelloWorld() = runBlocking {
languageDispatcher.dispatch(SupportLanguages.Cpp11) {
judge(
"""
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
""".trimIndent(), ""
)
}
}
@Benchmark
@Threads(20)
fun kotlinHelloWorld() = runBlocking {
languageDispatcher.dispatch(SupportLanguages.Kotlin) {
judge("""println(""Hello, World!")""", "")
}
}
}
private lateinit var languageDispatcher: LanguageDispatcher
private val httpClient: HttpClient = HttpClient(OkHttp) {
install(ContentNegotiation) {
json(Json)
}
}
private fun default(judgeUrl: String): LanguageDispatcher {
return LanguageDispatcher.get(
LanguageFactory.get(
judgeUrl, httpClient = httpClient
)
)
}
suspend fun main() {
languageDispatcher = default("http://localhost:8081/")
listOf(10, 20, 50, 100, 200, 500, 1000).forEach { times ->
measureTimeMillis {
withContext(Dispatchers.IO) {
(1..times).map {
async {
languageDispatcher.dispatch(SupportLanguages.Cpp11) {
judge(
"""
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
""".trimIndent(), ""
)
}
}
}.awaitAll()
}
}.also {
println("$times $it")
}
}
} | OnlineJudge/benchmark/src/main/kotlin/Main.kt | 1808853315 |
package cn.llonvne.kvision.service
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.api.task.Output
import io.kvision.annotations.KVService
@KVService
interface IJudgeService {
suspend fun judge(languages: SupportLanguages, stdin: String, code: String): Output
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IJudgeService.kt | 338772785 |
package cn.llonvne.kvision.service
import cn.llonvne.message.Message
import cn.llonvne.message.Message.ToastMessage
import cn.llonvne.message.MessageLevel
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.serialization.Serializable
@KVService
interface IAuthenticationService {
@Serializable
sealed interface RegisterResult {
val message: ToastMessage
fun isOk() = this is SuccessfulRegistration
@Serializable
data class SuccessfulRegistration(val token: AuthenticationToken, val username: String) : RegisterResult {
override val message: ToastMessage = ToastMessage(
MessageLevel.Success, "成功注册,欢迎新用户:${username}"
)
}
@Serializable
data class Failed(override val message: ToastMessage) : RegisterResult
}
suspend fun register(username: String, password: String): RegisterResult
@Serializable
sealed interface LoginResult {
val message: Message
@Serializable
data object BannedUser : LoginResult {
override val message: Message
get() = ToastMessage(MessageLevel.Danger, "您的账号已经被管理员封禁")
}
@Serializable
data class SuccessfulLogin(val token: AuthenticationToken, val username: String) : LoginResult {
override val message: Message =
ToastMessage(MessageLevel.Success, "登入成功,欢迎:${username}")
}
@Serializable
data object IncorrectUsernameOrPassword : LoginResult {
override val message: Message = ToastMessage(MessageLevel.Warning, "用户名或者密码错误")
}
@Serializable
data object UserDoNotExist : LoginResult {
override val message: Message = ToastMessage(MessageLevel.Warning, "用户不存在")
}
}
suspend fun login(username: String, password: String): LoginResult
@Serializable
sealed interface GetLoginInfoResp {
@Serializable
data object NotLogin : GetLoginInfoResp
@Serializable
data object LoginExpired : GetLoginInfoResp
@Serializable
data class Login(val username: String, val id: Int) : GetLoginInfoResp
}
suspend fun getLoginInfo(token: AuthenticationToken?): GetLoginInfoResp
@Serializable
sealed interface GetLogoutResp {
@Serializable
data object Logout : GetLogoutResp
}
suspend fun logout(token: AuthenticationToken?): GetLogoutResp
@Serializable
sealed interface MineResp {
@Serializable
data class NormalUserMineResp(
val username: String,
val createAt: String,
val acceptedTotal: Int,
val accepted7Days: Int,
val accepted30Days: Int,
val acceptedToday: Int
) : MineResp
@Serializable
data class AdministratorMineResp(val placeholder: Unit) : MineResp
}
suspend fun mine(value: AuthenticationToken?): MineResp
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IAuthenticationService.kt | 3966835291 |
@file:UseContextualSerialization
package cn.llonvne.kvision.service
import cn.llonvne.dtos.AuthenticationUserDto
import cn.llonvne.dtos.SubmissionListDto
import cn.llonvne.dtos.ViewCodeDto
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.ProblemJudgeResult
import cn.llonvne.entity.problem.SubmissionStatus
import cn.llonvne.entity.problem.SubmissionVisibilityType
import cn.llonvne.entity.problem.context.ProblemTestCases
import cn.llonvne.entity.problem.context.SubmissionTestCases
import cn.llonvne.entity.problem.context.passer.PasserResult
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseContextualSerialization
@KVService
interface ISubmissionService {
@Serializable
data class ListSubmissionReq(
val token: AuthenticationToken? = null,
)
suspend fun list(req: ListSubmissionReq): List<SubmissionListDto>
@Serializable
sealed interface SubmissionGetByIdResp {
@Serializable
data class SuccessfulGetById(val submissionListDto: SubmissionListDto) : SubmissionGetByIdResp
}
suspend fun getById(id: Int): SubmissionGetByIdResp
@Serializable
sealed interface ViewCodeGetByIdResp {
@Serializable
data class SuccessfulGetById(val viewCodeDto: ViewCodeDto) : ViewCodeGetByIdResp
}
suspend fun getViewCode(id: Int): ViewCodeGetByIdResp
@Serializable
sealed interface GetSupportLanguageByProblemIdResp {
@Serializable
data class SuccessfulGetSupportLanguage(val languages: List<Language>) : GetSupportLanguageByProblemIdResp
}
suspend fun getSupportLanguageId(
authenticationToken: AuthenticationToken?, problemId: Int
): GetSupportLanguageByProblemIdResp
@Serializable
data object SubmissionNotFound : SubmissionGetByIdResp, ViewCodeGetByIdResp, PlaygroundOutput
@Serializable
data object ProblemNotFound : SubmissionGetByIdResp, ViewCodeGetByIdResp, GetSupportLanguageByProblemIdResp,
ProblemSubmissionResp, GetLastNProblemSubmissionResp, IContestService.AddProblemResp
@Serializable
data object UserNotFound : SubmissionGetByIdResp, ViewCodeGetByIdResp
@Serializable
sealed interface CreateSubmissionReq {
val rawCode: String
val languageId: Int
val codeType: Code.CodeType
@Serializable
data class PlaygroundCreateSubmissionReq(
val stdin: String,
override val rawCode: String,
override val languageId: Int,
override val codeType: Code.CodeType
) : CreateSubmissionReq
}
@Serializable
sealed interface CreateSubmissionResp {
@Serializable
data class SuccessfulCreateSubmissionResp(val submissionId: Int, val codeId: Int) : CreateSubmissionResp
}
suspend fun create(
authenticationToken: AuthenticationToken?, createSubmissionReq: CreateSubmissionReq
): CreateSubmissionResp
@Serializable
sealed interface GetJudgeResultByCodeIdResp
@Serializable
sealed interface ProblemOutput : GetJudgeResultByCodeIdResp {
@Serializable
data class SuccessProblemOutput(
val problem: ProblemJudgeResult
) : PlaygroundOutput
}
@Serializable
sealed interface PlaygroundOutput : GetJudgeResultByCodeIdResp {
@Serializable
data class SuccessPlaygroundOutput(
val outputDto: OutputDto
) : PlaygroundOutput
@Serializable
sealed interface OutputDto {
val language: SupportLanguages
@Serializable
data class SuccessOutput(
val stdin: String,
val stdout: String,
override val language: SupportLanguages,
) : OutputDto
@Serializable
sealed interface FailureReason {
@Serializable
data object CompileResultNotFound : FailureReason
@Serializable
data class CompileError(val compileErrMessage: String) : FailureReason
@Serializable
data object RunResultIsNull : FailureReason
@Serializable
data object TargetResultNotFound : FailureReason
}
@Serializable
data class FailureOutput(
val reason: FailureReason,
override val language: SupportLanguages
) : OutputDto
}
}
suspend fun getOutputByCodeId(
authenticationToken: AuthenticationToken?, codeId: Int
): GetJudgeResultByCodeIdResp
@Serializable
sealed interface GetLastNPlaygroundSubmissionResp {
@Serializable
data class PlaygroundSubmissionDto(
val language: Language,
val user: AuthenticationUserDto,
val submissionId: Int,
val status: SubmissionStatus,
val submitTime: LocalDateTime,
val codeId: Int
)
@Serializable
data class SuccessGetLastNPlaygroundSubmission(
val subs: List<PlaygroundSubmissionDto>
) : GetLastNPlaygroundSubmissionResp
}
suspend fun getLastNPlaygroundSubmission(
authenticationToken: AuthenticationToken?, last: Int = 5
): GetLastNPlaygroundSubmissionResp
@Serializable
data class ProblemSubmissionReq(
val code: String,
val problemId: Int,
val languageId: Int,
val visibilityType: SubmissionVisibilityType,
val contestId: ContestId? = null
)
@Serializable
data class ProblemSubmissionRespNotPersist(
val problemTestCases: ProblemTestCases,
val submissionTestCases: SubmissionTestCases,
)
@Serializable
sealed interface ProblemSubmissionResp {
@Serializable
data class ProblemSubmissionRespImpl(
val codeId: Int,
val problemTestCases: ProblemTestCases,
val submissionTestCases: SubmissionTestCases,
) : ProblemSubmissionResp
}
suspend fun submit(
value: AuthenticationToken?,
submissionSubmit: ProblemSubmissionReq
): ProblemSubmissionResp
@Serializable
sealed interface GetLastNProblemSubmissionResp {
@Serializable
data class GetLastNProblemSubmissionRespImpl(
val submissions: List<ProblemSubmissionListDto>
) : GetLastNProblemSubmissionResp
@Serializable
data class ProblemSubmissionListDto(
val language: Language,
val submitTime: LocalDateTime,
val codeId: Int,
val passerResult: PasserResult,
)
}
suspend fun getLastNProblemSubmission(
value: AuthenticationToken?,
problemId: Int,
lastN: Int
): GetLastNProblemSubmissionResp
@Serializable
sealed interface GetParticipantContestResp {
@Serializable
data class GetParticipantContestOk(val contests: List<Contest>) :
GetParticipantContestResp
}
suspend fun getParticipantContest(value: AuthenticationToken?): GetParticipantContestResp
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ISubmissionService.kt | 1652573409 |
package cn.llonvne.kvision.service
import cn.llonvne.entity.group.Group
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.group.GroupType
import cn.llonvne.entity.group.GroupVisibility
import cn.llonvne.entity.role.TeamIdRole
import cn.llonvne.kvision.service.Validatable.Companion.on
import cn.llonvne.kvision.service.Validatable.Companion.validate
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@KVService
interface IGroupService {
@Serializable
data class CreateGroupReq(
val groupName: String,
val groupShortName: String,
val teamVisibility: GroupVisibility,
val groupType: GroupType,
val description: String
) : Validatable {
override fun validate() = validate {
on(groupName, "队伍名称必须在 6..100 之间") {
length in 6..100
}
on(groupShortName, "短名称必须在 3..20之间") {
length in 3..20
}
}
}
@Serializable
sealed interface CreateGroupResp {
@Serializable
data class CreateGroupOk(val group: Group) : CreateGroupResp
}
suspend fun createTeam(
authenticationToken: AuthenticationToken, createGroupReq: CreateGroupReq
): CreateGroupResp
@Serializable
sealed interface LoadGroupResp {
sealed interface LoadGroupSuccessResp : LoadGroupResp {
val groupId: GroupId
val groupName: String
val groupShortName: String
val visibility: GroupVisibility
@SerialName("groupType")
val type: GroupType
val ownerName: String
val description: String
val members: List<GroupMemberDto>
val createAt: LocalDateTime
}
@Serializable
data class GuestLoadGroup(
override val groupId: GroupId,
override val groupName: String,
override val groupShortName: String,
override val visibility: GroupVisibility,
@SerialName("groupType")
override val type: GroupType,
override val ownerName: String,
override val description: String,
override val members: List<GroupMemberDtoImpl>,
override val createAt: LocalDateTime,
) : LoadGroupSuccessResp
@Serializable
data class ManagerLoadGroup(
override val groupId: GroupId,
override val groupName: String,
override val groupShortName: String,
override val visibility: GroupVisibility,
@SerialName("groupType") override val type: GroupType,
override val ownerName: String,
override val description: String,
override val members: List<GroupMemberDtoImpl>,
override val createAt: LocalDateTime
) : LoadGroupSuccessResp
@Serializable
data class MemberLoadGroup(
override val groupId: GroupId,
override val groupName: String,
override val groupShortName: String,
override val visibility: GroupVisibility,
@SerialName("groupType") override val type: GroupType,
override val ownerName: String,
override val description: String,
override val members: List<GroupMemberDtoImpl>,
override val createAt: LocalDateTime
) : LoadGroupSuccessResp
@Serializable
data class OwnerLoadGroup(
override val groupId: GroupId,
override val groupName: String,
override val groupShortName: String,
override val visibility: GroupVisibility,
@SerialName("groupType") override val type: GroupType,
override val ownerName: String,
override val description: String,
override val members: List<GroupMemberDtoImpl>,
override val createAt: LocalDateTime
) : LoadGroupSuccessResp
@Serializable
sealed interface GroupMemberDto {
val username: String
val role: TeamIdRole
val userId: Int
}
@Serializable
data class GroupMemberDtoImpl(
override val username: String, override val role: TeamIdRole,
override val userId: Int
) : GroupMemberDto
}
suspend fun load(authenticationToken: AuthenticationToken?, groupId: GroupId): LoadGroupResp
@Serializable
sealed interface JoinGroupResp {
@Serializable
data class Joined(val groupId: GroupId) : JoinGroupResp
@Serializable
data class Reject(val groupId: GroupId) : JoinGroupResp
@Serializable
data class NoManagersFound(val groupId: GroupId) : JoinGroupResp
}
suspend fun join(groupId: GroupId, authenticationToken: AuthenticationToken): JoinGroupResp
@Serializable
sealed interface QuitGroupResp
@Serializable
data object QuitOk : QuitGroupResp
suspend fun quit(groupId: GroupId, value: AuthenticationToken?): QuitGroupResp
@Serializable
sealed interface KickGroupResp {
@Serializable
data class KickMemberNotFound(val memberId: Int) : KickGroupResp
@Serializable
data class KickMemberGroupIdRoleFound(val memberId: Int, val groupId: GroupId) : KickGroupResp
@Serializable
data object Kicked : KickGroupResp
}
suspend fun kick(token: AuthenticationToken?, groupId: GroupId, kickMemberId: Int): KickGroupResp
@Serializable
data class BeUpOrDowngradedUserNotfound(val userId: Int) : UpgradeGroupManagerResp, DowngradeToMemberResp
@Serializable
data class UserAlreadyHasThisRole(val userId: Int) : UpgradeGroupManagerResp, DowngradeToMemberResp
@Serializable
data class UpOrDowngradeToIdNotMatchToGroupId(val userId: Int) : UpgradeGroupManagerResp
@Serializable
sealed interface UpgradeGroupManagerResp {
@Serializable
data object UpgradeManagerOk : UpgradeGroupManagerResp
}
suspend fun upgradeGroupManager(
token: AuthenticationToken?,
groupId: GroupId,
updatee: Int
): UpgradeGroupManagerResp
@Serializable
sealed interface DowngradeToMemberResp {
@Serializable
data class DowngradeToMemberOk(val userId: Int) : DowngradeToMemberResp
}
suspend fun downgradeToMember(
authenticationToken: AuthenticationToken?,
groupId: GroupId,
userId: Int
): DowngradeToMemberResp
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IGroupService.kt | 808162137 |
package cn.llonvne.kvision.service
import kotlinx.serialization.Serializable
@Serializable
data object ContestOwnerNotFound : IContestService.LoadContestResp {
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ContestOwnerNotFound.kt | 1286898692 |
package cn.llonvne.kvision.service
import cn.llonvne.entity.ModifyUserForm
import cn.llonvne.entity.role.IUserRole
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@KVService
interface IMineService {
@Serializable
sealed interface DashboardResp {
@Serializable
data class OnlineJudgeStatistics(
val totalUserCount: Int,
val totalSubmissionToday: Int,
val totalContestLastTwoWeek: Int
)
@Serializable
data class BackendInfo(
val name: String,
val host: String,
val port: String,
val cpuCoresCount: Int,
val cpuUsage: Double,
val totalMemory: Int,
val usedMemory: Int,
val isOnline: Boolean
)
@Serializable
data class JudgeServerInfo(
val name: String,
val host: String,
val port: String,
val cpuCoresCount: Int,
val cpuUsage: Double,
val memoryUsage: Int,
val isOnline: Boolean
)
@Serializable
data class DashboardRespImpl(
val statistics: OnlineJudgeStatistics,
val backendInfo: BackendInfo,
val judgeServerInfo: JudgeServerInfo
) : DashboardResp
}
suspend fun dashboard(authenticationToken: AuthenticationToken?): DashboardResp
@Serializable
sealed interface UsersResp {
@Serializable
data class UsersRespImpl(
val users: List<UserManageListUserDto>
) : UsersResp
@Serializable
data class UserManageListUserDto(
val userId: Int,
val username: String,
val createAt: LocalDateTime,
val userRole: IUserRole
)
}
suspend fun users(): UsersResp
suspend fun deleteUser(value: AuthenticationToken?, id: Int): Boolean
suspend fun modifyUser(value: AuthenticationToken?, result: ModifyUserForm): Boolean
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IMineService.kt | 1158501000 |
package cn.llonvne.kvision.service
import kotlinx.serialization.Serializable
@Serializable
data object AddProblemPermissionDenied : IContestService.AddProblemResp {
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/AddProblemPermissionDenied.kt | 3595710429 |
package cn.llonvne.kvision.service
import cn.llonvne.dtos.ProblemListDto
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.ProblemListShowType
import cn.llonvne.entity.problem.ProblemTag
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.problem.context.ProblemContext
import cn.llonvne.entity.problem.context.ProblemType
import cn.llonvne.entity.problem.context.ProblemVisibility
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.serialization.Serializable
@KVService
interface IProblemService {
@Serializable
data class CreateProblemReq(
val problemName: String,
val problemDescription: String,
val problemContext: ProblemContext,
val authorId: Int,
val timeLimit: Long,
val memoryLimit: Long,
val visibility: ProblemVisibility,
val type: ProblemType,
val supportLanguages: List<Language>,
)
@Serializable
sealed interface CreateProblemResp {
@Serializable
data class Ok(val problemId: Int) : CreateProblemResp
@Serializable
data class AuthorIdNotExist(val authorId: Int) : CreateProblemResp
}
suspend fun create(authenticationToken: AuthenticationToken?, createProblemReq: CreateProblemReq): CreateProblemResp
suspend fun list(authenticationToken: AuthenticationToken?, showType: ProblemListShowType): List<ProblemListDto>
@Serializable
sealed interface ProblemGetByIdResult {
@Serializable
data class GetProblemByIdOk(
val problem: Problem,
val supportLanguages: List<Language>,
val tage: List<ProblemTag>
) : ProblemGetByIdResult
@Serializable
data object ProblemNotFound : ProblemGetByIdResult
}
suspend fun getById(id: Int): ProblemGetByIdResult
suspend fun search(token: AuthenticationToken?, text: String): List<ProblemListDto>
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IProblemService.kt | 110917158 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ISubmissionService.PlaygroundOutput
import kotlinx.serialization.Serializable
@Serializable
data object JudgeResultParseError : PlaygroundOutput, ISubmissionService.ViewCodeGetByIdResp,
ISubmissionService.GetJudgeResultByCodeIdResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/JudgeResultParseError.kt | 1852324725 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ICodeService.*
import cn.llonvne.kvision.service.ISubmissionService.*
import kotlinx.serialization.Serializable
@Serializable
data object CodeNotFound : GetCodeResp, GetCommitsOnCodeResp,
SetCodeVisibilityResp, SetCodeCommentTypeResp, ViewCodeGetByIdResp,
SubmissionGetByIdResp, PlaygroundOutput | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/CodeNotFound.kt | 3747904120 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ICodeService.*
import cn.llonvne.kvision.service.IGroupService.CreateGroupResp
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.IProblemService.CreateProblemResp
import cn.llonvne.kvision.service.ISubmissionService.*
import kotlinx.serialization.Serializable
@Serializable
data object PermissionDenied : CreateProblemResp,
SaveCodeResp, CommitOnCodeResp, SetCodeVisibilityResp,
GetCodeResp, SetCodeCommentTypeResp,
SetCodeCommentVisibilityTypeResp, CreateSubmissionResp,
PlaygroundOutput, GetLastNPlaygroundSubmissionResp,
CreateGroupResp, LoadGroupResp, IGroupService.JoinGroupResp, IGroupService.QuitGroupResp,
IGroupService.KickGroupResp, ProblemSubmissionResp, GetLastNProblemSubmissionResp, IAuthenticationService.MineResp,
IContestService.AddProblemResp, IContestService.CreateContestResp, IContestService.LoadContestResp,
IContestService.ContextSubmissionResp, GetParticipantContestResp, IMineService.DashboardResp
@Serializable
data class PermissionDeniedWithMessage(val message: String) : IGroupService.KickGroupResp,
IGroupService.UpgradeGroupManagerResp, IGroupService.DowngradeToMemberResp, ProblemSubmissionResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/PermissionDenied.kt | 916160866 |
package cn.llonvne.kvision.service
import kotlinx.serialization.Serializable
/**
* 标识数据需要被校验
*/
interface Validatable {
fun validate(): ValidateResult
companion object {
@Serializable
sealed interface ValidateResult {
fun toBoolean(): Boolean {
return when (this) {
Ok -> true
is Failed -> false
}
}
}
@Serializable
data object Ok : ValidateResult
@Serializable
data class Failed(val message: String) : ValidateResult
fun interface Validator {
fun validate(): ValidateResult
}
interface ValidatorDsl {
fun add(validator: Validator)
}
inline fun <reified T> ValidatorDsl.on(
value: T,
failMessage: String,
crossinline predicate: T.() -> Boolean
) {
add {
return@add if (predicate.invoke(value)) {
Ok
} else {
Failed(failMessage)
}
}
}
private data class ValidatorDslImpl
(private val validators: MutableList<Validator> = mutableListOf()) :
ValidatorDsl {
override fun add(validator: Validator) {
validators.add(validator)
}
fun result(): ValidateResult {
validators.forEach {
when (val result = it.validate()) {
Ok -> {}
is Failed -> {
return result
}
}
}
return Ok
}
}
/**
* 校验数据 DSL 入口
*/
fun validate(action: ValidatorDsl.() -> Unit): ValidateResult {
val validatorDsl = ValidatorDslImpl()
validatorDsl.action()
return validatorDsl.result()
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/Validatable.kt | 973966642 |
package cn.llonvne.kvision.service
import kotlinx.serialization.Serializable
@Serializable
data object ProblemIdInvalid : IContestService.AddProblemResp, IContestService.CreateContestResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ProblemIdInvalid.kt | 252156925 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ICodeService.SaveCodeResp
import cn.llonvne.kvision.service.ISubmissionService.*
import kotlinx.serialization.Serializable
@Serializable
data object LanguageNotFound : SubmissionGetByIdResp, ViewCodeGetByIdResp,
SaveCodeResp, CreateSubmissionResp,
GetLastNPlaygroundSubmissionResp, PlaygroundOutput, ProblemSubmissionResp, GetLastNProblemSubmissionResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/LanguageNotFound.kt | 1252827148 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ICodeService.SetCodeCommentVisibilityTypeResp
import kotlinx.serialization.Serializable
@Serializable
data object CommentNotFound : SetCodeCommentVisibilityTypeResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/CommentNotFound.kt | 3450525113 |
package cn.llonvne.kvision.service
import cn.llonvne.dtos.CodeDto
import cn.llonvne.dtos.CreateCommentDto
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.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.serialization.Serializable
@KVService
interface ICodeService {
@Serializable
data class SaveCodeReq(
val code: String,
val languageId: Int?,
val visibilityType: CodeVisibilityType = CodeVisibilityType.Public,
)
@Serializable
sealed interface SaveCodeResp {
@Serializable
data class SuccessfulSaveCode(val code: Code) : SaveCodeResp
}
suspend fun saveCode(token: AuthenticationToken?, saveCodeReq: SaveCodeReq): SaveCodeResp
@Serializable
sealed interface GetCodeResp {
@Serializable
data class SuccessfulGetCode(val codeDto: CodeDto) : GetCodeResp
fun onSuccess(block: (SuccessfulGetCode) -> Unit): GetCodeResp {
if (this is SuccessfulGetCode) {
block(this)
}
return this
}
fun onFailure(block: (GetCodeResp) -> Unit): GetCodeResp {
if (this !is SuccessfulGetCode) {
block(this)
}
return this
}
}
suspend fun getCode(value: AuthenticationToken?, shareId: Int): GetCodeResp
@Serializable
data class CommitOnCodeReq(
val token: AuthenticationToken?,
val content: String,
val codeId: Int,
val type: ShareCodeCommentType
)
@Serializable
sealed interface CommitOnCodeResp {
@Serializable
data class SuccessfulCommit(val shareCodeCommitDto: CreateCommentDto) : CommitOnCodeResp
}
suspend fun commit(commitOnCodeReq: CommitOnCodeReq): CommitOnCodeResp
@Serializable
sealed interface GetCommitsOnCodeResp {
@Serializable
data class SuccessfulGetCommits(val commits: List<CreateCommentDto>) : GetCommitsOnCodeResp
}
suspend fun getComments(authenticationToken: AuthenticationToken?, sharCodeId: Int): GetCommitsOnCodeResp
suspend fun deleteComments(commentIds: List<Int>): List<Int>
@Serializable
sealed interface SetCodeVisibilityResp {
@Serializable
data object SuccessToPublicOrPrivate : SetCodeVisibilityResp
@Serializable
data class SuccessToRestrict(val link: String) : SetCodeVisibilityResp
}
suspend fun setCodeVisibility(
token: AuthenticationToken?,
shareId: Int,
result: CodeVisibilityType
): SetCodeVisibilityResp
suspend fun getCodeByHash(value: AuthenticationToken?, hash: String): GetCodeResp
@Serializable
sealed interface SetCodeCommentTypeResp {
@Serializable
data object SuccessSetCommentType : SetCodeCommentTypeResp
}
suspend fun setCodeCommentType(
token: AuthenticationToken?,
shareId: Int,
type: CodeCommentType
): SetCodeCommentTypeResp
@Serializable
sealed interface SetCodeCommentVisibilityTypeResp {
@Serializable
data object SuccessSetCodeCommentVisibilityType : SetCodeCommentVisibilityTypeResp
}
suspend fun setCodeCommentVisibilityType(
token: AuthenticationToken?,
shareId: Int,
commentId: Int,
type: ShareCodeCommentType
): SetCodeCommentVisibilityTypeResp
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ICodeService.kt | 3151185543 |
package cn.llonvne.kvision.service
import cn.llonvne.entity.group.GroupId
import cn.llonvne.kvision.service.IGroupService.*
import kotlinx.serialization.Serializable
@Serializable
data class GroupShortNameUnavailable(val shortName: String) : CreateGroupResp
@Serializable
data class GroupIdNotFound(val groupId: GroupId) : LoadGroupResp, JoinGroupResp, QuitGroupResp, KickGroupResp,
UpgradeGroupManagerResp, DowngradeToMemberResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/GroupResps.kt | 1936087647 |
package cn.llonvne.kvision.service
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestContext
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.problem.Submission
import cn.llonvne.security.AuthenticationToken
import io.kvision.annotations.KVService
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
@KVService
interface IContestService {
@Serializable
sealed interface AddProblemResp {
@Serializable
data class AddOkResp(val problemId: Int, val problemName: String) : AddProblemResp
}
suspend fun addProblem(value: AuthenticationToken?, problemId: String): AddProblemResp
@Serializable
data class CreateContestReq(
val title: String,
val description: String = "",
@Contextual val startAt: LocalDateTime,
@Contextual val endAt: LocalDateTime,
val contestScoreType: Contest.ContestScoreType,
val rankType: Contest.ContestRankType,
val problems: List<ContestContext.ContestProblem>
)
@Serializable
sealed interface CreateContestResp {
@Serializable
data class CreateOk(val contest: Contest) : CreateContestResp
}
suspend fun create(authenticationToken: AuthenticationToken?, createContestReq: CreateContestReq): CreateContestResp
@Serializable
sealed interface LoadContestResp {
@Serializable
data class LoadOk(val contest: Contest, val ownerName: String) : LoadContestResp
}
suspend fun load(value: AuthenticationToken?, contestId: ContestId): LoadContestResp
@Serializable
sealed interface ContextSubmissionResp {
@Serializable
data class ContextSubmissionOk(val submissions: List<Submission>) : ContextSubmissionResp
}
suspend fun contextSubmission(value: AuthenticationToken?, contestId: ContestId): ContextSubmissionResp
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/IContestService.kt | 1705144162 |
package cn.llonvne.kvision.service.exception
import cn.llonvne.JvmMainException
import io.kvision.annotations.KVServiceException
import io.kvision.remote.AbstractServiceException
@KVServiceException
class AuthorAuthenticationUserIdNotExist : AbstractServiceException() {
override val message = "作者的注册用户ID不存在"
}
/**
* 题目服务异常
*/
open class ProblemServiceException(msg: String) : JvmMainException(msg)
/**
* 题目ID在创建后仍不存在
*/
class ProblemIdDoNotExistAfterCreation : ProblemServiceException("题目ID在创建后仍不存在")
@KVServiceException
class AuthorNotExist : AbstractServiceException()
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/exception/AuthorRepositoryException.kt | 2021086017 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.ICodeService.CommitOnCodeResp
import cn.llonvne.kvision.service.ISubmissionService.CreateSubmissionResp
import cn.llonvne.kvision.service.ISubmissionService.GetLastNPlaygroundSubmissionResp
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
@Serializable
data class InternalError(val reason: String) : CommitOnCodeResp, CreateSubmissionResp,
GetLastNPlaygroundSubmissionResp, IGroupService.CreateGroupResp, ISubmissionService.ProblemSubmissionResp,
IContestService.AddProblemResp, IContestService.CreateContestResp
@Serializable
data class JudgeError(@Contextual val reason: String) : CreateSubmissionResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/InternalError.kt | 3665236466 |
package cn.llonvne.kvision.service
import kotlinx.serialization.Serializable
@Serializable
object ContestNotFound : IContestService.LoadContestResp, IContestService.ContextSubmissionResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ContestNotFound.kt | 3261896481 |
package cn.llonvne.kvision.service
import cn.llonvne.kvision.service.IGroupService.CreateGroupResp
/**
* 用户端异常
* 用于描述用户造成的异常
* @property message 异常信息可以发送给用户
*/
data class ClientError(val message: String = "") : CreateGroupResp | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/kvision/service/ClientError.kt | 1470406974 |
package cn.llonvne
/**
* 所有自定义异常的父类
*
* 所有业务错误不应该从这里继承
*/
open class OnlineJudgeException(msg: String) : Exception(msg) {
}
/**
* 所有 CommonMain 自定义异常的父类
*/
open class CommonMainException(msg: String) : OnlineJudgeException(msg)
/**
* 所有 JsMain 自定义异常的父类
*/
open class JsMainException(msg: String) : OnlineJudgeException(msg)
/**
* 所有 JvmMain 自定义异常的父类
*/
open class JvmMainException(msg: String) : OnlineJudgeException(msg)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/Exceptions.kt | 2622254850 |
package cn.llonvne
import kotlinx.datetime.LocalDateTime
fun LocalDateTime.ll() =
"${year}年${monthNumber}月${dayOfMonth}日${hour}时${minute}分${second}秒" | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/TimeExts.kt | 1113348807 |
package cn.llonvne
import io.kvision.annotations.KVService
@KVService
interface IPingService {
suspend fun ping(message: String): String
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/IPingService.kt | 3466268730 |
package cn.llonvne
import cn.llonvne.entity.AuthenticationUser
import io.kvision.annotations.KVService
@KVService
interface IUserService {
suspend fun byId(id: Int): AuthenticationUser
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/IUserService.kt | 1605520015 |
package cn.llonvne.security
import kotlinx.serialization.Serializable
@Serializable
sealed interface AuthenticationToken {
val token: String
val id: Int
}
@Serializable
data class RedisToken(override val id: Int, override val token: String) : AuthenticationToken {
override fun toString(): String {
return "<Redis-Token-$id>"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/security/AuthenticationToken.kt | 2607368875 |
package cn.llonvne.entity.role
import kotlinx.serialization.Serializable
@Serializable
sealed interface Banned : Role {
companion object {
val BannedImpl: Banned = BannedImplClass()
}
@Serializable
class BannedImplClass : Banned {
override fun check(provide: Role): Boolean {
return provide is Banned
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/Banned.kt | 2448075924 |
@file:UseContextualSerialization
package cn.llonvne.entity.role
import cn.llonvne.entity.group.GroupType
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseContextualSerialization
import kotlin.reflect.KClass
/**
* 通用队伍权限身份接口,该接口用于表示**通用权限**
*/
@Serializable
sealed interface TeamRole : Role {
companion object {
fun default(): List<TeamRole> = listOf(CreateGroup.CreateTeamImpl())
fun TeamRole.simpleName(cls: KClass<*>): String = withSimpleName(cls) { "" }
fun withSimpleName(cls: KClass<*>, build: () -> String) = "<${cls.simpleName}-${build()}>"
}
}
@Serializable
sealed interface CreateGroup : TeamRole {
val teamTypes: List<GroupType>
@Serializable
data class CreateTeamImpl(
override val teamTypes: List<GroupType> = listOf(GroupType.Classic)
) : CreateGroup {
override fun check(provide: Role): Boolean {
return if (provide is CreateGroup) {
return provide.teamTypes.containsAll(teamTypes)
} else {
false
}
}
override fun toString(): String {
return TeamRole.withSimpleName(CreateGroup::class) {
teamTypes.joinToString(",") { it.name }
}
}
}
companion object {
fun require(type: GroupType): CreateGroup {
return CreateTeamImpl(listOf(type))
}
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/TeamRole.kt | 1503930373 |
package cn.llonvne.entity.role
import kotlinx.serialization.Serializable
/***
* 指示一个用户是否能访问后台
*/
sealed interface Backend : Role {
@Serializable
data object BackendImpl : Backend {
override fun check(provide: Role): Boolean {
return provide is Backend
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/Backend.kt | 960698196 |
package cn.llonvne.entity.role
import kotlinx.serialization.Serializable
/**
* [UserRole 的数据传输对象]
*/
@Serializable
data class IUserRole(
val roles: List<Role>
)
inline fun <reified R : Role> List<Role>.check(required: R): Boolean {
return map { provide ->
required.check(provide)
}.contains(true)
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/IUserRole.kt | 3299780078 |
package cn.llonvne.entity.role
import cn.llonvne.entity.group.GroupType
import kotlinx.serialization.Serializable
/**
* 超级队伍管理员,拥有对一切队伍的管理权限
*/
@Serializable
sealed interface TeamSuperManager : TeamIdRole, CreateGroup {
@Serializable
data class TeamSuperManagerImpl(
override val teamId: Int = 0,
override val teamTypes: List<GroupType> = GroupType.entries
) :
TeamSuperManager {
override fun check(provide: Role): Boolean {
return provide is TeamSuperManager
}
}
companion object {
fun get(): TeamSuperManager = TeamSuperManagerImpl()
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/TeamSuperManager.kt | 2033130299 |
package cn.llonvne.entity.role
import kotlinx.serialization.Serializable
/**
* 权限认证接口
*/
@Serializable
sealed interface Role {
/**
* 检查 [provide] 是否可以通过认证
*/
fun check(provide: Role): Boolean
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/Role.kt | 2161709746 |
package cn.llonvne.entity.role
import kotlinx.serialization.Serializable
/**
* 对于有状态的权限,可以通过该接口获得对于任何状态都符合的权限
*/
@Serializable
sealed interface SuperRole {
fun superRole(): Role
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/SuperRole.kt | 1501396445 |
package cn.llonvne.entity.role
import cn.llonvne.entity.role.TeamIdRole.Companion.simpleName
import kotlinx.serialization.Serializable
import kotlin.reflect.KClass
/**
* 特定队伍权限身份接口,表示该权限对于唯一一个 [teamId]
*/
@Serializable
sealed interface TeamIdRole : Role {
/**
* [teamId] 标识符号
*/
val teamId: Int
companion object : SuperRole {
fun TeamIdRole.simpleName(cls: KClass<*>): String {
return "<${cls.simpleName}-id-$teamId>"
}
override fun superRole(): Role {
return TeamSuperManager.get()
}
fun getManagerRoles(groupId: Int): List<TeamIdRole> {
return listOf(
GroupManager.GroupMangerImpl(groupId),
GroupOwner.GroupOwnerImpl(groupId)
)
}
}
}
inline fun <reified T : TeamIdRole> T.checkInternal(provide: Role): Boolean {
if (provide is TeamSuperManager) {
return true
}
if (provide is T) {
return provide.teamId == teamId
}
return false
}
@Serializable
sealed interface TeamMember : TeamIdRole {
@Serializable
data class TeamMemberImpl(override val teamId: Int) : TeamMember {
override fun check(provide: Role): Boolean = checkInternal<TeamMember>(provide)
override fun toString(): String {
return simpleName(TeamMember::class)
}
}
}
@Serializable
sealed interface DeleteTeam : TeamIdRole {
@Serializable
data class DeleteTeamImpl(override val teamId: Int) : DeleteTeam {
override fun check(provide: Role): Boolean = checkInternal<DeleteTeam>(provide)
override fun toString(): String {
return simpleName(DeleteTeam::class)
}
}
}
@Serializable
sealed interface InviteMember : TeamIdRole {
@Serializable
data class InviteMemberImpl(override val teamId: Int) : InviteMember {
override fun check(provide: Role): Boolean = checkInternal<InviteMember>(provide)
override fun toString(): String {
return simpleName(InviteMember::class)
}
}
}
@Serializable
sealed interface KickMember : TeamIdRole {
@Serializable
data class KickMemberImpl(override val teamId: Int) : KickMember {
override fun check(provide: Role): Boolean = checkInternal<KickMember>(provide)
override fun toString(): String {
return simpleName(KickMember::class)
}
}
}
@Serializable
sealed interface GroupManager : DeleteTeam, InviteMember, KickMember {
@Serializable
data class GroupMangerImpl(override val teamId: Int) : GroupManager {
override fun check(provide: Role): Boolean = checkInternal<GroupManager>(provide)
override fun toString(): String {
return simpleName(GroupManager::class)
}
}
}
@Serializable
sealed interface GroupOwner : GroupManager {
@Serializable
data class GroupOwnerImpl(override val teamId: Int) : GroupOwner {
override fun check(provide: Role): Boolean = checkInternal<GroupOwner>(provide)
override fun toString(): String {
return simpleName(GroupOwner::class)
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/role/TeamIdRole.kt | 3839472643 |
package cn.llonvne.entity.types
import kotlinx.serialization.Serializable
@Serializable
enum class ProblemStatus {
Accepted,
WrongAnswer,
NotLogin,
NotBegin
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/types/ProblemStatus.kt | 161762612 |
package cn.llonvne.entity.types.badge
import kotlinx.serialization.Serializable
@Serializable
enum class BadgeColor {
Green,
Red,
Blue,
Grey,
Golden,
White,
Dark
}
val BadgeColor.cssClass: String
get() = when (this) {
BadgeColor.Green -> "bg-success"
BadgeColor.Red -> "bg-danger"
BadgeColor.Blue -> "bg-primary"
BadgeColor.Grey -> "text-bg-secondary"
BadgeColor.Golden -> "text-bg-warning"
BadgeColor.White -> "text-bg-light"
BadgeColor.Dark -> "dark"
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/types/badge/BadgeColor.kt | 2092526952 |
package cn.llonvne.entity.types.badge
/**
* 为 [cn.llonvne.compoent.badgeGroup]
*/
interface BadgeColorGetter {
val color: BadgeColor
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/types/badge/BadgeColorGetter.kt | 2363027775 |
package cn.llonvne.entity
interface DescriptionGetter {
val decr: String
val reprName: String
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/DescriptionGetter.kt | 3092880395 |
package cn.llonvne.entity.group
import kotlinx.serialization.Serializable
@Serializable
enum class GroupType {
Classic,
College,
Team;
val chinese
get() = when (this) {
Classic -> "经典的小组,拥有经典的组织层次(管理员-成员结构),该选项面对所有用户开放"
College -> "学校,拥有类学校的组织层次(管理员-教师-助教-学生-...),该选项需要验证您的身份"
Team -> "学校附属的小组结构,不拥有管理员(管理权由对应的学校拥有)"
}
val shortChinese
get() = when (this) {
Classic -> "经典小组"
College -> "学校"
Team -> "小队"
}
companion object {
val options: List<Pair<String, String>> = entries.map {
it.ordinal.toString() to it.chinese
}
val defaultOption get() = Classic.ordinal.toString() to Classic.chinese
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/group/GroupType.kt | 371422065 |
package cn.llonvne.entity.group
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class Group(
val groupId: Int? = null,
val groupName: String,
val groupShortName: String,
val groupHash: String,
val description: String,
val visibility: GroupVisibility,
val type: GroupType,
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/group/Group.kt | 1482643598 |
package cn.llonvne.entity.group
import kotlinx.serialization.Serializable
@Serializable
sealed interface GroupId {
val path: String
@Serializable
data class IntGroupId(val id: Int) : GroupId {
override fun toString(): String {
return "<id-$id>"
}
override val path: String
get() = id.toString()
}
@Serializable
data class HashGroupId(val id: String) : GroupId {
override fun toString(): String {
return "<hash-$id>"
}
override val path: String
get() = id
}
@Serializable
data class ShortGroupName(val shortName: String) : GroupId {
override fun toString(): String {
return "short-$shortName"
}
override val path: String
get() = shortName
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/group/GroupId.kt | 1704272266 |
package cn.llonvne.entity.group;
import kotlinx.serialization.Serializable
@Serializable
enum class GroupVisibility {
Public, Private, Restrict;
val chinese: String
get() = when (this) {
Public -> "公开的小组,对任何人都可见,任何都可以自由加入"
Private -> "非空开的小组,对任何人都不可见,任何人都无法加入"
Restrict -> "公开的小组,加入者需要通过Hash或者由管理员审批"
}
val shortChinese get() = when(this){
Public -> "公开"
Private -> "私有"
Restrict -> "受限制的"
}
companion object {
val options: List<Pair<String, String>> = entries.map {
it.ordinal.toString() to it.chinese
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/group/GroupVisibility.kt | 3480928192 |
package cn.llonvne.entity.group
import cn.llonvne.kvision.service.IGroupService
fun interface GroupLoader {
suspend fun load(): IGroupService.LoadGroupResp
companion object
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/group/GroupLoader.kt | 3500388431 |
package cn.llonvne.entity.problem
import kotlinx.serialization.Serializable
@Serializable
data class Language(
val languageId: Int,
val languageName: String,
val languageVersion: String
) {
override fun toString(): String {
return "$languageName:$languageVersion"
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/Language.kt | 2873571745 |
package cn.llonvne.entity.problem
enum class SubmissionVisibilityType {
PUBLIC, PRIVATE, Contest;
val chinese
get() = when (this) {
PUBLIC -> "公开"
PRIVATE -> "私有"
Contest -> "比赛"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/SubmissionVisibilityType.kt | 1826209658 |
package cn.llonvne.entity.problem.context
import cn.llonvne.entity.problem.context.ProblemTestCases.ProblemTestCase
import cn.llonvne.gojudge.api.task.Output
import kotlinx.serialization.Serializable
@Serializable
data class SubmissionTestCases(val testCases: List<SubmissionTestCase>) {
val showOnJudgeResultDisplay
get() = testCases.filter {
it.visibility in setOf(
TestCaseType.ViewAndJudge
)
}
@Serializable
data class SubmissionTestCase(
override val id: String,
override val name: String,
override val input: String,
override val expect: String,
override val visibility: TestCaseType,
val originOutput: Output,
val outputStr: String?
) : TestCase {
companion object {
fun from(
problemTestCase: ProblemTestCase,
output: Output
): SubmissionTestCase {
return SubmissionTestCase(
id = problemTestCase.id,
name = problemTestCase.name,
input = problemTestCase.input,
expect = problemTestCase.expect,
visibility = problemTestCase.visibility,
originOutput = output,
outputStr = when (output) {
is Output.Success -> output.runResult.files?.get("stdout").toString()
else -> null
}
)
}
}
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/SubmissionTestCases.kt | 1797118170 |
package cn.llonvne.entity.problem.context
import cn.llonvne.entity.problem.context.passer.PasserResult
import cn.llonvne.entity.problem.context.passer.ProblemPasser
import kotlinx.serialization.Serializable
@Serializable
data class ProblemTestCases(
val testCases: List<ProblemTestCase>,
val passer: ProblemPasser<PasserResult>
) {
@Serializable
data class ProblemTestCase(
override val id: String,
override val name: String,
override val input: String,
override val expect: String,
override val visibility: TestCaseType,
) : TestCase
fun canShow() = testCases.filter {
it.visibility in setOf(
TestCaseType.OnlyForView,
TestCaseType.ViewAndJudge
)
}
fun canJudge() = testCases.filter {
it.visibility in setOf(
TestCaseType.ViewAndJudge,
TestCaseType.OnlyForJudge
)
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/ProblemTestCases.kt | 1865542179 |
package cn.llonvne.entity.problem.context
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class Problem(
// 题目 ID
val problemId: Int? = null,
// 作者 ID
val authorId: Int,
val ownerId: Int,
// 题目名字
val problemName: String,
// 题目描述
val problemDescription: String,
// 时间限制
val timeLimit: Long,
// 内存限制
val memoryLimit: Long,
val visibility: ProblemVisibility,
val type: ProblemType,
/**
* [ProblemContext] 序列化后的类型
*/
val contextJson: String,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) {
suspend fun <R> onIdNotNull(
onNull: R,
action: suspend (id: Int, problem: Problem) -> R,
): R {
if (problemId != null) {
return action(problemId, this)
}
return onNull
}
val context = Json.decodeFromString<ProblemContext>(contextJson)
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/Problem.kt | 1210824533 |
package cn.llonvne.entity.problem.context.passer
import cn.llonvne.entity.types.badge.BadgeColor
import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline
@Serializable
sealed interface PasserResult {
val readable: String
val pass: Boolean
@Serializable
class BooleanResult(
val result: Boolean
) : PasserResult {
val suggestColor: BadgeColor
get() = when (result) {
true -> BadgeColor.Green
false -> BadgeColor.Red
}
override val readable
get() = when (result) {
true -> "Accepted"
false -> "Wrong Answer"
}
override val pass: Boolean
get() = result
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/passer/PasserResult.kt | 111150668 |
package cn.llonvne.entity.problem.context.passer
import cn.llonvne.entity.problem.context.SubmissionTestCases
import cn.llonvne.entity.problem.context.passer.PasserResult.BooleanResult
import kotlinx.serialization.Serializable
/**
* 定义题目任何算通过
*/
@Serializable
sealed interface ProblemPasser<out R : PasserResult> {
val description: String
/**
* 通过测试结果集合判断题目是否通过测试,并获得测试结果
*/
fun pass(submissionTestCases: SubmissionTestCases): R
/**
* 通过所有测试
*/
@Serializable
data class PassAllCases(override val description: String = "必须要通过所有测试") : ProblemPasser<BooleanResult> {
override fun pass(submissionTestCases: SubmissionTestCases): BooleanResult {
return submissionTestCases.testCases.map { testcase ->
testcase.outputStr?.trimIndent() == testcase.expect
}.all { it }.let { BooleanResult(it) }
}
}
/**
* 通过一定程度
*/
@Serializable
data class OfPassRate(val rate: Double) : ProblemPasser<BooleanResult> {
override fun pass(submissionTestCases: SubmissionTestCases): BooleanResult {
TODO()
}
override val description: String
get() = "通过 $rate 比例测试即可算题目通过"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/passer/ProblemPasser.kt | 1853728258 |
package cn.llonvne.entity.problem.context
import kotlinx.serialization.Serializable
@Serializable
enum class ProblemType {
Individual,
Group
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/ProblemType.kt | 1695476503 |
package cn.llonvne.entity.problem.context
import kotlinx.serialization.Serializable
/**
* 题目内容
*/
@Serializable
data class ProblemContext(
val overall: String,
val inputDescription: String,
val outputDescription: String,
val hint: String,
val testCases: ProblemTestCases
)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/ProblemContext.kt | 3655639824 |
package cn.llonvne.entity.problem.context;
import kotlinx.serialization.Serializable
@Serializable
enum class ProblemVisibility {
Public,
Private,
Restrict;
val chinese
get() = when (this) {
Public -> "公开的题目,所有人都可以查看,所有人都可以提交"
Private -> "私有的题目,任何人都无法查看"
Restrict -> "受限制的题目,只能通过特定的Hash链接访问,并提交"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/ProblemVisibility.kt | 3035570565 |
package cn.llonvne.entity.problem.context
import kotlinx.serialization.Serializable
@Serializable
sealed interface TestCase {
val id: String
val name: String
val input: String
val expect: String
val visibility: TestCaseType
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/TestCase.kt | 111576774 |
package cn.llonvne.entity.problem.context;
import kotlinx.serialization.Serializable
@Serializable
enum class TestCaseType {
OnlyForView,
OnlyForJudge,
ViewAndJudge,
Deprecated,
Building;
val chinese
get() = when (this) {
OnlyForView -> "仅展示"
OnlyForJudge -> "仅判题"
ViewAndJudge -> "展示/判题"
Deprecated -> "废弃"
Building -> "建设中"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/context/TestCaseType.kt | 4144572028 |
package cn.llonvne.entity.problem
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.entity.types.badge.BadgeColorGetter
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class ProblemTag(
val problemTagId: Int,
val problemId: Int,
val tag: String,
override val color: BadgeColor,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) : BadgeColorGetter
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/ProblemTag.kt | 881565077 |
package cn.llonvne.entity.problem
import kotlinx.serialization.Serializable
@Serializable
enum class ProblemListShowType {
All,
Accepted,
Attempted,
Favorite
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/ProblemListShowType.kt | 744586154 |
package cn.llonvne.entity.problem
import cn.llonvne.entity.problem.context.ProblemTestCases
import cn.llonvne.entity.problem.context.SubmissionTestCases
import cn.llonvne.entity.problem.context.passer.PasserResult
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
private val json = Json
@Serializable
sealed interface JudgeResult {
fun json() = json.encodeToString<JudgeResult>(this)
}
@Serializable
data class PlaygroundJudgeResult(
val submissionTestCases: SubmissionTestCases
) : JudgeResult {
val output = submissionTestCases.testCases.first().originOutput
}
@Serializable
data class ProblemJudgeResult(
val problemTestCases: ProblemTestCases,
val submissionTestCases: SubmissionTestCases,
val passerResult: PasserResult
) : JudgeResult | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/JudgeResult.kt | 1931766637 |
package cn.llonvne.entity.problem
enum class SubmissionStatus {
Received,
Finished;
val readable: String
get() = when (this) {
Received -> "收到评测请求"
Finished -> "评测完毕"
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/SubmissionStatus.kt | 2544033403 |
package cn.llonvne.entity.problem
import cn.llonvne.entity.DescriptionGetter
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
/**
* [Code] 的评论
*/
@Serializable
data class ShareCodeComment(
val commentId: Int? = null,
val committerAuthenticationUserId: Int,
val shareCodeId: Int,
val content: String,
val type: ShareCodeCommentType = ShareCodeCommentType.Public,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) {
companion object {
@Serializable
enum class ShareCodeCommentType : DescriptionGetter {
Deleted,
Public,
Private;
override val decr: String
get() = when (this) {
Deleted -> "被删除"
Public -> "公开的评论"
Private -> "私有的"
}
override val reprName: String
get() = when (this) {
Deleted -> "被删除"
Public -> "公开"
Private -> "私密"
}
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/ShareCodeComment.kt | 1508029201 |
package cn.llonvne.entity.problem
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class Submission(
val submissionId: Int? = null,
val problemId: Int?,
val codeId: Int,
val contestId: Int? = null,
// 用户 ID
val authenticationUserId: Int,
// 可见性
val visibility: SubmissionVisibilityType = SubmissionVisibilityType.PUBLIC,
val status: SubmissionStatus = SubmissionStatus.Received,
// 以 Json 形式存在内部
val judgeResult: String,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) {
companion object {
private val json = Json
}
val result: JudgeResult get() = json.decodeFromString(judgeResult)
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/Submission.kt | 2460570550 |
package cn.llonvne.entity.problem.share
import cn.llonvne.entity.DescriptionGetter
import kotlinx.serialization.Serializable
@Serializable
enum class CodeVisibilityType : DescriptionGetter {
Public, Private, Restrict;
override val decr: String
get() = when (this) {
Public -> "对所有人可见"
Private -> "仅对自己可见"
Restrict -> "对特定的链接可见(通过 ID 访问将显示为不可见)"
}
override val reprName: String
get() = when (this) {
Public -> "公开"
Private -> "私有"
Restrict -> "受限"
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/share/CodeVisibilityType.kt | 2891314490 |
package cn.llonvne.entity.problem.share
import cn.llonvne.entity.DescriptionGetter
import cn.llonvne.entity.problem.share.CodeCommentType.*
import cn.llonvne.security.AuthenticationToken
import kotlinx.serialization.Serializable
import kotlin.enums.EnumEntries
@Serializable
enum class CodeCommentType : DescriptionGetter {
Open,
Closed,
ClosedByAdmin,
Freezing,
Protected,
ContestCode
;
override val decr: String
get() = decr()
override val reprName: String
get() = name
}
private fun CodeCommentType.decr() = when (this) {
Open -> "任何人均可查看,均可发表评论"
Closed -> "评论区被关闭"
ClosedByAdmin -> "评论区被管理员关闭"
Protected -> "评论区被保护(需经过审核才能公开展示)"
Freezing -> "评论区被冻结,无法添加/删除/修改评论"
ContestCode -> "比赛代码不支持评论"
}
fun EnumEntries<CodeCommentType>.limited(token: AuthenticationToken): List<CodeCommentType> {
return this.filter { it != ContestCode }
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/share/CodeCommentType.kt | 1434461521 |
package cn.llonvne.entity.problem.share
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class Code(
val codeId: Int? = null,
val authenticationUserId: Int,
val code: String,
val languageId: Int?,
val codeType: CodeType,
val visibilityType: CodeVisibilityType = CodeVisibilityType.Public,
val commentType: CodeCommentType = CodeCommentType.Open,
val hashLink: String? = null,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) {
@Serializable
enum class CodeType {
Share, Playground, Problem
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/problem/share/Code.kt | 3109414243 |
package cn.llonvne.entity
import kotlinx.serialization.Serializable
@Serializable
data class ModifyUserForm(
val userId: String,
val username: String,
val isBanned: Boolean
) | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/ModifyUserForm.kt | 3828705372 |
package cn.llonvne.entity
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
/**
* 注册用户实体
* @see [cn.llonvne.database.entity.def.AuthenticationUserDef]
*/
@Serializable
data class AuthenticationUser(
val id: Int = 0,
val username: String,
val encryptedPassword: String,
val version: Int? = null,
val role: String,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) {
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/AuthenticationUser.kt | 3646400129 |
package cn.llonvne.entity
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
/**
* 作者信息
*/
@Serializable
data class Author(
val authorId: Int? = null,
val authorName: String,
val introduction: String,
// 如果是注册用户,那么则绑定 AuthenticationUser 的ID
val authenticationUserId: Int? = null,
//--- 数据库信息区 ---//
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null
) | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/Author.kt | 2023790395 |
package cn.llonvne.entity.contest
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
@Serializable
data class ContestContext(
val problems: List<ContestProblem>
) {
@Serializable
data class ContestProblem(
val problemId: Int,
val weight: Int,
val alias: String
)
fun json() = contestContextJson.encodeToString(this)
companion object {
fun empty() = ContestContext(problems = listOf())
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/contest/ContestContext.kt | 2314357355 |
package cn.llonvne.entity.contest
import kotlinx.serialization.Serializable
@Serializable
sealed interface ContestId
@Serializable
class IntId(val id: Int) : ContestId
@Serializable
class HashId(val hash: String) : ContestId | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/contest/ContestId.kt | 4035074810 |
package cn.llonvne.entity.contest
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
val contestContextJson = Json { encodeDefaults = true }
@Serializable
data class Contest(
val contestId: Int = -1,
val ownerId: Int,
val title: String,
val description: String = "",
val contestScoreType: ContestScoreType,
val startAt: LocalDateTime,
val endAt: LocalDateTime,
val rankType: ContestRankType,
val groupId: Int? = null,
val version: Int? = null,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null,
val contextStr: String = ContestContext(listOf()).json(),
val hashLink: String
) {
val context: ContestContext = Json.decodeFromString(contextStr)
/**
* 定义比赛如何执行记分
*/
@Serializable
enum class ContestScoreType {
ACM, IOI, IO
}
@Serializable
enum class ContestStatus {
NotBegin, Running, Ended
}
@Serializable
enum class ContestRankType {
OpenForEveryOne,
OpenForParticipant,
OpenForManger,
OpenForOwner,
Closed;
val chinese
get() = when (this) {
OpenForEveryOne -> "对所有人开放"
OpenForParticipant -> "仅对参与者开放"
OpenForManger -> "仅对比赛管理员开放"
OpenForOwner -> "仅对所有者开放"
Closed -> "不开放"
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/entity/contest/Contest.kt | 1372455342 |
package cn.llonvne.constants
import _Name
object Authentication {
object User {
val Name = _Name
val Password = _Password
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/constants/Authentication.kt | 3470946364 |
package cn.llonvne.constants
import kotlinx.serialization.Serializable
object _Password {
private const val MIN_LENGTH = 6
private const val MAX_LENGTH = 40
private const val VALIDATOR_MESSAGE = "密码长度必须在${MIN_LENGTH}-${MAX_LENGTH}"
fun check(password: String?): PasswordCheckResult {
if (password == null) {
return PasswordCheckResult.PasswordIsNull
}
if (password.length !in MIN_LENGTH..MAX_LENGTH) {
return PasswordCheckResult.PasswordIsTooLongOrTooShort
}
return PasswordCheckResult.Ok
}
fun reason(password: String?): String {
return "$VALIDATOR_MESSAGE:${check(password)}"
}
@Serializable
sealed interface PasswordCheckResult {
fun isOk() = this is Ok
@Serializable
data object Ok : PasswordCheckResult
@Serializable
data object PasswordIsTooLongOrTooShort : PasswordCheckResult {
override fun toString(): String {
return "密码太长或者太短"
}
}
@Serializable
data object PasswordIsNull : PasswordCheckResult {
override fun toString(): String {
return "密码不能为空"
}
}
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/constants/_Password.kt | 2995640167 |
import kotlinx.serialization.Serializable
object _Name {
private const val NAME_MIN_LENGTH = 6
private const val NAME_MAX_LENGTH = 40
private const val VALIDATOR_MESSAGE =
"用户名长度必须在${NAME_MIN_LENGTH}-${NAME_MAX_LENGTH}"
fun reason(username: String?): String {
return "$VALIDATOR_MESSAGE:${check(username)}"
}
fun check(username: String?): UsernameCheckResult {
if (username == null) {
return UsernameCheckResult.UsernameIsNull
}
if (username.length !in NAME_MIN_LENGTH..NAME_MAX_LENGTH) {
return UsernameCheckResult.UsernameTooLongOrTooShort(username)
}
return UsernameCheckResult.Ok
}
@Serializable
sealed interface UsernameCheckResult {
fun isOk() = this is Ok
@Serializable
data object Ok : UsernameCheckResult
@Serializable
data object UsernameIsNull : UsernameCheckResult {
override fun toString(): String {
return "用户名为空"
}
}
@Serializable
data class UsernameTooLongOrTooShort(val username: String) : UsernameCheckResult {
override fun toString(): String {
return if (username.length < NAME_MIN_LENGTH) {
"用户名过短"
} else {
"用户名过长"
}
}
}
}
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/constants/_Name.kt | 1761093682 |
package cn.llonvne.constants
interface Site {
val uri: String
val name: String
}
object Frontend {
object Index : Site {
override val uri = "/"
override val name: String = "主页"
}
object Problems : Site {
override val uri = "/problems"
override val name: String = "问题"
object Create : Site {
override val uri: String = "${Problems.uri}/create"
override val name: String = "创建问题"
}
}
object Login : Site {
override val uri = "/login"
override val name: String = "登入"
}
object Register : Site {
override val uri = "/register"
override val name: String = "注册"
}
object Mine : Site {
override val uri: String = "/me"
override val name: String = "我的"
}
object Submission : Site {
override val uri: String = "/submissions"
override val name: String = "提交"
}
object PlayGround : Site {
override val uri: String = "/playground"
override val name: String = "训练场"
}
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/constants/Frontend.kt | 1844664792 |
package cn.llonvne.message
import kotlinx.serialization.Serializable
@Serializable
sealed interface Message {
@Serializable
val level: MessageLevel
/**
* 指示该信息将由 Toast 发出
* @see [cn.llonvne.message.Messager.toastByLevel]
*/
@Serializable
data class ToastMessage(override val level: MessageLevel, val message: String) :
Message
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/message/Message.kt | 1491707370 |
package cn.llonvne.message
import kotlinx.serialization.Serializable
@Serializable
enum class MessageLevel {
Info,
Warning,
Danger,
Success
}
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/message/MessageLevel.kt | 1073429625 |
package cn.llonvne.dtos
import kotlinx.serialization.Serializable
@Serializable
data class SubmissionSubmit(
val languageId: String?,
val code: String?,
val visibilityTypeStr: String? = null
) | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/SubmissionSubmit.kt | 1164772097 |
package cn.llonvne.dtos
import cn.llonvne.entity.Author
import cn.llonvne.entity.problem.ProblemTag
import cn.llonvne.entity.problem.context.Problem
import cn.llonvne.entity.types.ProblemStatus
import kotlinx.serialization.Serializable
@Serializable
data class ProblemListDto(
val problem: Problem,
val problemId: Int,
val author: Author,
val status: ProblemStatus,
val tags: List<ProblemTag>
)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/ProblemListDto.kt | 3803342756 |
package cn.llonvne.dtos
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType.*
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class CreateCommentDto(
val commentId: Int,
val committerUsername: String,
val shareCodeId: Int,
val content: String,
val createdAt: LocalDateTime,
val visibilityType: ShareCodeCommentType
)
/**
* 获取评论的可见性中文描述
*/
fun CreateCommentDto.getVisibilityDecr(): String = when (visibilityType) {
Deleted -> "已被删除"
Public -> "对所有人可见"
Private -> "仅对你与代码所有者可见"
} | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/CreateCommentDto.kt | 2690311775 |
package cn.llonvne.dtos
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeVisibilityType
import kotlinx.serialization.Serializable
@Serializable
data class CodeDto(
val codeId: Int,
val rawCode: String,
val language: Language?,
val shareUserId: Int,
val shareUsername: String,
val visibilityType: CodeVisibilityType,
val commentType: CodeCommentType,
val hashLink: String?,
val codeType: Code.CodeType
) | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/CodeDto.kt | 1167090859 |
package cn.llonvne.dtos
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.SubmissionStatus
import cn.llonvne.entity.problem.context.passer.PasserResult
import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.Serializable
@Serializable
data class SubmissionListDto(
val language: Language,
val user: AuthenticationUserDto,
val problemId: Int,
val problemName: String,
val submissionId: Int,
val status: SubmissionStatus,
val codeLength: Long,
val submitTime: LocalDateTime,
val passerResult: PasserResult,
val codeId: Int
)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/SubmissionListDto.kt | 1021359630 |
package cn.llonvne.dtos
import cn.llonvne.entity.problem.JudgeResult
import cn.llonvne.entity.problem.Language
import cn.llonvne.entity.problem.SubmissionStatus
import kotlinx.serialization.Serializable
@Serializable
data class ViewCodeDto(
val rawCode: String,
val language: Language,
val problemName: String,
val problemId: Int,
val status: SubmissionStatus,
val submissionId: Int,
val judgeResult: JudgeResult
)
| OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/ViewCodeDto.kt | 4279520368 |
package cn.llonvne.dtos
import kotlinx.serialization.Serializable
@Serializable
data class AuthenticationUserDto(
val username: String
) | OnlineJudge/online-judge-web/src/commonMain/kotlin/cn/llonvne/dtos/AuthenticationUserDto.kt | 3686611324 |
package cn.llonvne.exts
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.toKotlinLocalDateTime
fun LocalDateTime.Companion.now() = java.time.LocalDateTime.now().toKotlinLocalDateTime() | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/exts/Extensions.kt | 1856563343 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.code
import cn.llonvne.database.entity.def.shareCodeComment
import cn.llonvne.entity.problem.ShareCodeComment
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType.Deleted
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeVisibilityType
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.metamodel.define
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
@Repository
class CodeRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase
) {
private val codeMeta = Meta.code
private val commentMeta = Meta.shareCodeComment.define {
where {
// 默认不查询被删除的评论
it.type notEq Deleted
}
}
suspend fun save(code: Code) = db.runQuery {
QueryDsl.insert(codeMeta).single(code).returning()
}
suspend fun get(shareId: Int): Code? {
return db.runQuery { QueryDsl.from(codeMeta).where { codeMeta.codeId eq shareId }.singleOrNull() }
}
suspend fun getCodeByHash(hash: String): Code? {
return db.runQuery { QueryDsl.from(codeMeta).where { codeMeta.hashLink eq hash }.singleOrNull() }
}
suspend fun getCodeOwnerId(shareCodeId: Int): Int? {
return db.runQuery {
QueryDsl.from(codeMeta).where {
codeMeta.codeId eq shareCodeId
}
.select(codeMeta.authenticationUserId)
.singleOrNull()
}
}
suspend fun isIdExist(shareCodeId: Int): Boolean = db.runQuery {
QueryDsl.from(codeMeta).where {
codeMeta.codeId eq shareCodeId
}.select(count())
} == 1.toLong()
suspend fun setCodeVisibility(shareId: Int, visibilityType: CodeVisibilityType): Long {
return db.runQuery {
QueryDsl.update(codeMeta).set {
codeMeta.visibilityType eq visibilityType
}.where {
codeMeta.codeId eq shareId
}
}
}
suspend fun setHashLink(shareId: Int, hashLink: String?): Long {
return db.runQuery {
QueryDsl.update(codeMeta).set {
codeMeta.hashLink eq hashLink
}.where {
codeMeta.codeId eq shareId
}
}
}
suspend fun deleteComment(ids: List<Int>): List<ShareCodeComment> {
return db.runQuery {
QueryDsl.update(commentMeta).set {
commentMeta.type eq Deleted
}.where {
commentMeta.commentId inList ids
}.returning()
}
}
suspend fun comment(comment: ShareCodeComment): ShareCodeComment {
return db.runQuery {
QueryDsl.insert(commentMeta).single(
comment
).returning()
}
}
suspend fun getComments(shareCodeId: Int, limit: Int = 500): List<ShareCodeComment> {
return db.runQuery {
QueryDsl.from(commentMeta).where {
commentMeta.shareCodeId eq shareCodeId
}.limit(500)
}
}
suspend fun setCodeCommentType(shareId: Int, type: CodeCommentType): Long {
return db.runQuery {
QueryDsl.update(codeMeta).set {
codeMeta.commentType eq type
}.where {
codeMeta.codeId eq shareId
}
}
}
suspend fun isCommentIdExist(commentId: Int) = db.runQuery {
QueryDsl.from(commentMeta)
.where {
commentMeta.commentId eq commentId
}
.select(count()).map {
it == 1L
}
}
suspend fun setShareCodeCommentVisibilityType(
commentId: Int,
type: ShareCodeCommentType
) {
db.runQuery {
QueryDsl.update(commentMeta)
.set {
commentMeta.type eq type
}
.where {
commentMeta.commentId eq commentId
}
}
}
suspend fun getCodeLanguageId(codeId: Int): Int? {
return db.runQuery {
QueryDsl.from(codeMeta)
.where {
codeMeta.codeId eq codeId
}
.select(codeMeta.languageId)
.singleOrNull()
}
}
suspend fun getCodeLength(codeId: Int): Int? {
return db.runQuery {
QueryDsl.from(codeMeta)
.where {
codeMeta.codeId eq codeId
}
.select(codeMeta.code)
.singleOrNull().map {
it?.length
}
}
}
suspend fun getCodeVisibilityType(codeId: Int): CodeVisibilityType? = db.runQuery {
QueryDsl.from(codeMeta).where {
codeMeta.codeId eq codeId
}.select(codeMeta.visibilityType).singleOrNull()
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/CodeRepository.kt | 330362751 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.code
import cn.llonvne.database.entity.def.problem.submission
import cn.llonvne.entity.problem.Submission
import cn.llonvne.entity.problem.share.Code
import cn.llonvne.entity.types.ProblemStatus
import cn.llonvne.security.AuthenticationToken
import kotlinx.coroutines.flow.Flow
import kotlinx.datetime.LocalDateTime
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Repository
@Repository
class SubmissionRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase
) {
private val submissionMeta = Meta.submission
private val codeMeta = Meta.code
suspend fun list(limit: Int = 500) = db.runQuery {
QueryDsl.from(submissionMeta)
.limit(limit)
}
suspend fun getById(id: Int) = db.runQuery {
QueryDsl.from(submissionMeta)
.where {
submissionMeta.submissionId eq id
}.singleOrNull()
}
suspend fun save(submission: Submission): Submission {
return db.runQuery {
QueryDsl.insert(submissionMeta).single(submission).returning()
}
}
suspend fun getByCodeId(codeId: Int): Submission? {
return db.runQuery {
QueryDsl.from(submissionMeta)
.where {
submissionMeta.codeId eq codeId
}.singleOrNull()
}
}
suspend fun getByAuthenticationUserID(
userID: Int, codeType: Code.CodeType?, limit: Int = 500
): List<Submission> {
return db.runQuery {
QueryDsl.from(submissionMeta).innerJoin(codeMeta) {
submissionMeta.codeId eq codeMeta.codeId
}.where {
submissionMeta.authenticationUserId eq userID
and {
if (codeType != null) {
codeMeta.codeType eq codeType
}
}
}.limit(limit)
}
}
fun getUserProblemStatus(token: AuthenticationToken?, problemId: Int): ProblemStatus {
// TODO
return ProblemStatus.NotBegin
}
suspend fun getByContestId(contestId: Int, limit: Int = 1000): List<Submission> {
return db.runQuery {
QueryDsl.from(submissionMeta).where {
submissionMeta.contestId eq contestId
}.limit(1000)
}
}
suspend fun getByTimeRange(start: LocalDateTime, end: LocalDateTime): List<Submission> {
return db.runQuery {
QueryDsl.from(submissionMeta).where {
submissionMeta.createdAt greaterEq start
and {
submissionMeta.createdAt lessEq end
}
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/SubmissionRepository.kt | 192633593 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.ProblemSupportLanguage
import cn.llonvne.database.entity.def.problem.language
import cn.llonvne.database.entity.problemSupportLanguage
import cn.llonvne.entity.problem.Language
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.Query
import org.komapper.core.dsl.query.map
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Repository
@Repository
class LanguageRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
) {
private val languageMeta = Meta.language
private val problemSupportLanguages = Meta.problemSupportLanguage
suspend fun getByIdOrNull(id: Int?): Language? {
if (id == null) {
return null
}
return db.runQuery {
getByIdOrNullQuery(id)
}
}
fun getByIdOrNullQuery(id: Int): Query<Language?> {
return QueryDsl.from(languageMeta).where {
languageMeta.languageId eq id
}.singleOrNull()
}
suspend fun isIdExist(id: Int) = db.runQuery {
QueryDsl.from(languageMeta).where {
languageMeta.languageId eq id
}.select(count()).map {
if (it == null) {
return@map false
} else {
return@map it != 0L
}
}
}
suspend fun setSupportLanguages(problemId: Int, languages: List<Int>) {
db.runQuery {
QueryDsl.insert(problemSupportLanguages).multiple(
languages.map {
ProblemSupportLanguage(
problemId = problemId,
languageId = it
)
}
)
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/LanguageRepository.kt | 1511523957 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.authenticationUser
import cn.llonvne.security.UserRole
import org.komapper.core.dsl.Meta
import org.komapper.core.dsl.QueryDsl
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Repository
@Repository
class RoleRepository(@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase) {
private val userMeta = Meta.authenticationUser
suspend fun getRoleStrByUserId(id: Int): String? {
return db.runQuery {
QueryDsl.from(userMeta)
.where { userMeta.id eq id }
.select(userMeta.role)
.singleOrNull()
}
}
suspend fun setRoleStrByUserId(id: Int, role: UserRole): Long {
val str = role.asJson
return db.runQuery {
QueryDsl.update(userMeta)
.set {
userMeta.role eq str
}.where {
userMeta.id eq id
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/RoleRepository.kt | 155794136 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.authenticationUser
import cn.llonvne.database.entity.def.createAtNow
import cn.llonvne.entity.AuthenticationUser
import cn.llonvne.entity.role.Banned
import cn.llonvne.kvision.service.IAuthenticationService
import cn.llonvne.kvision.service.IAuthenticationService.LoginResult.*
import cn.llonvne.security.BPasswordEncoder.Companion.invoke
import cn.llonvne.security.RedisAuthenticationService
import cn.llonvne.security.check
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.Query
import org.komapper.core.dsl.query.map
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
@Service
class AuthenticationUserRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
private val passwordEncoder: PasswordEncoder,
private val redisAuthenticationService: RedisAuthenticationService
) {
private val userMeta = Meta.authenticationUser
suspend fun new(name: String, password: String) = passwordEncoder {
db.runQuery {
QueryDsl.insert(userMeta).single(AuthenticationUser.createAtNow(name, password)).returning()
}
}
suspend fun login(username: String, rawPassword: String): IAuthenticationService.LoginResult = passwordEncoder {
val user = db.runQuery {
QueryDsl.from(userMeta).where {
userMeta.username eq username
}.singleOrNull()
}
return@passwordEncoder if (user == null) {
UserDoNotExist
} else if (matches(rawPassword, user.encryptedPassword)) {
if (user.check(Banned.BannedImpl)) {
BannedUser
} else {
SuccessfulLogin(redisAuthenticationService.login(user), user.username)
}
} else {
IncorrectUsernameOrPassword
}
}
internal suspend fun usernameAvailable(username: String): Boolean {
val count = db.runQuery {
QueryDsl.from(userMeta).where {
userMeta.username eq username
}.selectNotNull(org.komapper.core.dsl.operator.count())
}
return count == 0.toLong()
}
internal suspend fun isIdExist(authenticationUserId: Int): Boolean {
return db.runQuery {
QueryDsl.from(userMeta).where {
userMeta.id eq authenticationUserId
}.map {
it.isNotEmpty()
}
}
}
internal suspend fun getByIdOrNull(authenticationUserId: Int) = db.runQuery {
QueryDsl.from(userMeta).where {
userMeta.id eq authenticationUserId
}.singleOrNull()
}
internal suspend fun matchRoleStr(str: String): List<AuthenticationUser> {
return db.runQuery {
QueryDsl.from(userMeta).where {
userMeta.role contains str
}
}
}
internal suspend fun count(): Int {
return db.runQuery {
QueryDsl.from(userMeta).select(org.komapper.core.dsl.operator.count())
}?.toInt() ?: 0
}
internal suspend fun all(): List<AuthenticationUser> {
return db.runQuery {
QueryDsl.from(userMeta)
}
}
suspend fun deleteById(id: Int): Boolean {
return db.runQuery {
QueryDsl.delete(userMeta).where {
userMeta.id eq id
}.map {
it == 1.toLong()
}
}
}
} | OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/AuthenticationUserRepository.kt | 1411827351 |
package cn.llonvne.database.repository
import cn.llonvne.database.entity.def.group
import cn.llonvne.entity.group.Group
import cn.llonvne.kvision.service.GroupHashService
import cn.llonvne.kvision.service.IGroupService.CreateGroupReq
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.map
import org.komapper.core.dsl.query.singleOrNull
import org.komapper.r2dbc.R2dbcDatabase
import org.springframework.stereotype.Repository
import java.util.*
@Repository
class GroupRepository(
@Suppress("SpringJavaInjectionPointsAutowiringInspection") private val db: R2dbcDatabase,
private val groupHashService: GroupHashService
) {
private val groupMeta = Meta.group
suspend fun create(createGroupReq: CreateGroupReq): Group {
return db.runQuery {
QueryDsl.insert(groupMeta).single(
Group(
groupName = createGroupReq.groupName,
groupShortName = createGroupReq.groupShortName,
groupHash = groupHashService.hash(),
visibility = createGroupReq.teamVisibility,
type = createGroupReq.groupType,
description = createGroupReq.description
)
).returning()
}
}
suspend fun shortNameAvailable(name: String): Boolean {
return db.runQuery {
QueryDsl.from(groupMeta).where {
groupMeta.groupShortName eq name
}.select(count())
.map { it == 0.toLong() }
}
}
suspend fun isIdExist(id: Int): Boolean {
return db.runQuery {
QueryDsl.from(groupMeta).where {
groupMeta.groupId eq id
}.select(count())
.map { it == 1.toLong() }
}
}
suspend fun fromHashToId(hash: String): Int? {
return db.runQuery {
QueryDsl.from(groupMeta).where {
groupMeta.groupHash eq hash
}.select(groupMeta.groupId).singleOrNull()
}
}
suspend fun fromShortname(shortname: String): Int? {
return db.runQuery {
QueryDsl.from(groupMeta).where {
lower(groupMeta.groupShortName) eq shortname.lowercase(Locale.getDefault())
}.select(groupMeta.groupId).singleOrNull()
}
}
suspend fun fromId(id: Int): Group? = db.runQuery {
QueryDsl.from(groupMeta).where {
groupMeta.groupId eq id
}.singleOrNull()
}
}
| OnlineJudge/online-judge-web/src/jvmMain/kotlin/cn/llonvne/database/repository/GroupRepository.kt | 1411551302 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.