content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package cn.llonvne.site.problem
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badgeGroup
import cn.llonvne.compoent.observable.observableListOf
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.compoent.problemStatus
import cn.llonvne.dtos.ProblemListDto
import cn.llonvne.entity.problem.ProblemListShowType
import cn.llonvne.message.Messager
import cn.llonvne.model.ProblemModel
import cn.llonvne.model.RoutingModule
import cn.llonvne.model.Storage
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onClickLaunch
import io.kvision.core.onInput
import io.kvision.form.formPanel
import io.kvision.form.text.Text
import io.kvision.html.*
import io.kvision.routing.Routing
import io.kvision.state.bind
import io.kvision.tabulator.ColumnDefinition
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
import io.kvision.toolbar.buttonGroup
import io.kvision.utils.px
import kotlinx.serialization.Serializable
import kotlinx.serialization.serializer
@Serializable
data class ProblemSearch(
val input: String? = null
)
internal fun Container.problems(routing: Routing) {
alert(AlertType.Light) {
h1 {
+"题目集合"
}
p {
+"选择或者搜索您喜欢的题目来练练手吧!"
}
}
observableOf(ProblemListConfigure()) {
setUpdater { ProblemListConfigure() }
syncNotNull(div { }) { config ->
div(className = "row") {
div(className = "col-8") {
alert(AlertType.Light) {
problemsList(routing, config)
}
}
div(className = "col") {
alert(AlertType.Light) {
buttonGroup {
button("所有") {
onClick {
setObv(ProblemListConfigure {
showType = ProblemListShowType.All
})
}
}
button("已通过", style = ButtonStyle.SUCCESS) {
onClick {
setObv(ProblemListConfigure {
showType = ProblemListShowType.Accepted
})
}
}
button("已尝试", style = ButtonStyle.WARNING) {
onClick {
setObv(ProblemListConfigure {
showType = ProblemListShowType.Attempted
})
}
}
button("星标", style = ButtonStyle.INFO) {
onClick {
setObv(ProblemListConfigure {
showType = ProblemListShowType.Favorite
})
}
}
}
}
}
}
}
}
}
private class ProblemListConfigure {
var showType: ProblemListShowType = ProblemListShowType.All
}
private fun ProblemListConfigure(configure: ProblemListConfigure.() -> Unit): ProblemListConfigure {
val config = ProblemListConfigure()
config.configure()
return config
}
private fun Container.problemsList(
routing: Routing,
configure: ProblemListConfigure = ProblemListConfigure()
) {
val loader: suspend () -> List<ProblemListDto> = {
ProblemModel.listProblem(configure.showType)
}
val alert = div { }
add(alert)
observableListOf {
setUpdater { ProblemModel.listProblem() }
formPanel<ProblemSearch> {
"row gy-2 gx-3 align-items-center p-1".split(" ").forEach {
addCssClass(it)
}
var searchText by Storage.remember("", "problemSearchText")
add(ProblemSearch::input, Text(value = searchText) {
placeholder = "查找"
addCssClass("col-auto")
removeCssClass("kv-mb-3")
onInput {
searchText = this.value ?: ""
}
}, required = true, requiredMessage = "查找内容不可为空")
button("搜索", style = ButtonStyle.OUTLINESECONDARY) {
addCssClass("col-auto")
onClick {
val data = [email protected]()
if (data.input == null) {
updateList {
ProblemModel.listProblem().also {
Messager.toastInfo("为你查找到 ${it.size}条记录")
}
}
} else {
Messager.toastInfo("正在查找 ${data.input}")
disabled = true
updateList {
ProblemModel.search(data.input).also {
disabled = false
Messager.toastInfo("为你查找到 ${it.size}条记录")
}
}
}
}
}
button("创建您的题目", style = ButtonStyle.OUTLINESECONDARY) {
addCssClass("col-auto")
onClickLaunch {
RoutingModule.routing.navigate("/problems/create")
}
}
}
div(className = "py-2").bind(this) {
tabulator(
it, options = TabulatorOptions(
layout = Layout.FITCOLUMNS, columns = listOf(
ColumnDefinition("题目ID", "problem.problemId"),
ColumnDefinition("题目名称", "problem.problemName", cellClick = { _, cell ->
val id = cell.getData.invoke().asDynamic().problem.problemId as Int?
routing.navigate("/problems/${id}")
}),
ColumnDefinition("状态", "status", formatterComponentFunction = { _, _, e: ProblemListDto ->
span {
problemStatus(e.status)
}
}),
ColumnDefinition("题目标签", formatterComponentFunction = { _, _, e: ProblemListDto ->
span {
badgeGroup(e.tags) { tag ->
+tag.tag
}
}
}),
ColumnDefinition("作者", formatterComponentFunction = { _, _, e: ProblemListDto ->
span {
+e.author.authorName
}
}),
ColumnDefinition("更新时间", formatterComponentFunction = { _, _, e: ProblemListDto ->
span {
val updateAt = e.problem.updatedAt
if (updateAt != null) {
+"${updateAt.year}年${updateAt.monthNumber}月${updateAt.dayOfMonth}日"
} else {
+"未找到更新时间"
}
}
})
)
), serializer = serializer()
) {
height = 400.px
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/Problem.kt | 1912316112 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.submission.SubmitProblemResolver
import cn.llonvne.site.problem.detail.CodeEditorShower.Companion.CodeEditorConfigurer
class ProblemDetailConfigurer {
var notShowProblem: Boolean = false
var notShowProblemMessage: String = ""
var disableHistory: Boolean = false
var submitProblemResolver: SubmitProblemResolver = SubmitProblemResolver()
var codeEditorConfigurer: CodeEditorConfigurer =
CodeEditorConfigurer()
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/ProblemDetailConfigurer.kt | 2837300527 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import io.kvision.core.Container
import io.kvision.html.h4
import io.kvision.html.p
fun interface ProblemContextShower {
fun show(root: Container)
companion object {
fun from(resp: GetProblemByIdOk): ProblemContextShower {
return AbstractProblemContextShower(resp)
}
}
}
private open class AbstractProblemContextShower(private val resp: GetProblemByIdOk) : ProblemContextShower {
protected val context = resp.problem.context
override fun show(root: Container) {
root.alert(AlertType.Light) {
h4 {
+"任务说明"
}
p(rich = true) {
+context.overall
}
h4 {
+"输入说明"
}
p {
+context.inputDescription
}
h4 {
+"输出说明"
}
p {
+context.outputDescription
}
h4 {
+"提示"
}
p {
+context.hint
}
h4 {
+"判题标准"
}
p {
+context.testCases.passer.description
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/ProblemContextShower.kt | 1921052908 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.submission.SubmitProblemResolver
import cn.llonvne.dtos.SubmissionSubmit
import cn.llonvne.entity.problem.SubmissionVisibilityType
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import cn.llonvne.site.problem.detail.CodeEditorShower.Companion.CodeEditorConfigurer
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.form.formPanel
import io.kvision.form.select.TomSelect
import io.kvision.form.text.TextArea
import io.kvision.html.button
import io.kvision.html.h4
import io.kvision.html.p
import io.kvision.i18n.tr
interface CodeEditorShower {
fun show(root: Container)
companion object {
fun from(
problemId: Int,
getProblemByIdOk: GetProblemByIdOk,
codeEditorConfigurer: CodeEditorConfigurer
): CodeEditorShower {
return AbstractCodeEditorShower(problemId, getProblemByIdOk, codeEditorConfigurer)
}
class CodeEditorConfigurer {
/**
* 设置为 null 允许用户进行选择,否则将使用这里设定的可见性设置
*/
var forceVisibility: SubmissionVisibilityType? = null
var submitProblemResolver = SubmitProblemResolver()
var showSubmitPanel: Boolean = true
var notShowSubmitPanelMessage: String = ""
}
fun CodeEditorConfigurer(action: CodeEditorConfigurer.() -> Unit): CodeEditorConfigurer {
val codeEditorConfigurer = CodeEditorConfigurer()
codeEditorConfigurer.action()
return codeEditorConfigurer
}
}
}
private class AbstractCodeEditorShower(
private val problemId: Int,
getProblemByIdOk: GetProblemByIdOk,
private val codeEditorConfigurer: CodeEditorConfigurer
) : CodeEditorShower {
val problem = getProblemByIdOk
override fun show(root: Container) {
if (codeEditorConfigurer.showSubmitPanel) {
doShow(root)
} else {
root.alert(AlertType.Secondary) {
h4 {
+"提交面板已经被关闭"
}
p {
+codeEditorConfigurer.notShowSubmitPanelMessage
}
}
}
}
private fun doShow(root: Container) {
root.alert(AlertType.Secondary) {
h4 {
+"你的代码"
}
val panel = formPanel<SubmissionSubmit> {
add(SubmissionSubmit::languageId, TomSelect(options = problem.supportLanguages.map {
it.languageId.toString() to it.toString()
}) {
label = "提交语言"
})
add(SubmissionSubmit::code, TextArea {
label = "解决方案"
rows = 10
})
if (
codeEditorConfigurer.forceVisibility == null
) {
add(SubmissionSubmit::visibilityTypeStr, TomSelect(options = SubmissionVisibilityType.entries.map {
it.ordinal.toString() to it.chinese
}, label = "提交可见性"))
}
}
button("提交") {
onClickLaunch {
codeEditorConfigurer.submitProblemResolver.resolve(problemId, panel.getData().let {
if (codeEditorConfigurer.forceVisibility != null) {
it.copy(visibilityTypeStr = codeEditorConfigurer.forceVisibility?.ordinal.toString())
} else {
it
}
})
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/CodeEditorShower.kt | 1001648732 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badges
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import cn.llonvne.ll
import io.kvision.core.Container
import io.kvision.html.h1
import io.kvision.html.p
fun interface DetailHeaderShower {
fun show(root: Container)
companion object {
fun from(resp: GetProblemByIdOk): DetailHeaderShower {
return AbstractDetailHeaderShower(resp)
}
}
}
private class AbstractDetailHeaderShower(result: GetProblemByIdOk) :
DetailHeaderShower {
protected val problem = result.problem
override fun show(root: Container) {
root.alert(AlertType.Light) {
h1 {
+problem.problemName
}
p {
+problem.problemDescription
}
badges {
add {
+"内存限制:${problem.memoryLimit}"
}
add {
+"时间限制:${problem.timeLimit}"
}
add {
+"可见性:${problem.visibility.chinese}"
}
add {
+"类型:${problem.type.name}"
}
add {
+"最后更新于:${problem.updatedAt?.ll()}"
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/DetailHeaderShower.kt | 4099249794 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.BadgesDsl
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badges
import cn.llonvne.entity.problem.context.ProblemTestCases.ProblemTestCase
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import io.kvision.core.Container
import io.kvision.html.*
fun interface TestCasesShower {
fun load(root: Container)
companion object {
fun from(
resp: GetProblemByIdOk,
withoutTitle: Boolean = false,
filter: (ProblemTestCase) -> Boolean = { true },
badges: BadgesDsl.(ProblemTestCase) -> Unit = {}
): TestCasesShower {
return AbstractTestCasesShower(resp.problem.context.testCases.testCases, withoutTitle, filter, badges)
}
fun from(
testCase: List<ProblemTestCase>,
withoutTitle: Boolean = false,
filter: (ProblemTestCase) -> Boolean = { true },
badges: BadgesDsl.(ProblemTestCase) -> Unit = {}
): TestCasesShower {
return AbstractTestCasesShower(testCase, withoutTitle, filter, badges)
}
}
}
private open class AbstractTestCasesShower(
private val testCase: List<ProblemTestCase>,
private val withoutTitle: Boolean,
private val filter: (ProblemTestCase) -> Boolean = { true },
private val doBadges: BadgesDsl.(ProblemTestCase) -> Unit = {}
) : TestCasesShower {
protected val testcases = testCase.filter { filter(it) }
private fun Container.doShow() {
testcases.forEach { testcase ->
alert(AlertType.Primary) {
h6 {
+testcase.name
}
label { +"输入" }
customTag("pre") {
code {
+testcase.input
}
}
label { +"输出" }
customTag("pre") {
code {
+testcase.expect
}
}
badges {
add {
+testcase.visibility.chinese
}
doBadges(testcase)
}
}
}
}
private fun Container.showTitleOn(withoutTitle: Boolean, action: Container.() -> Unit) {
if (withoutTitle) {
action()
} else {
alert(AlertType.Light) {
h4 {
+"输入/输出样例"
}
action()
}
}
}
override fun load(root: Container) {
root.div {
showTitleOn(withoutTitle) {
if (testcases.isEmpty()) {
p {
+"无输入/输出样例"
}
} else {
doShow()
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/TestCasesShower.kt | 2362787087 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.loading
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.problem.context.passer.PasserResult
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.kvision.service.ISubmissionService.GetLastNProblemSubmissionResp.GetLastNProblemSubmissionRespImpl
import cn.llonvne.kvision.service.LanguageNotFound
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.ll
import cn.llonvne.message.Messager
import cn.llonvne.model.SubmissionModel
import cn.llonvne.site.BooleanPasserResultDisplay
import cn.llonvne.site.JudgeResultDisplayErrorHandler
import io.kvision.core.Container
import io.kvision.html.Span
import io.kvision.html.h4
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
interface ProblemSubmissionShower {
fun show(div: Container)
companion object {
fun from(resp: GetProblemByIdOk): ProblemSubmissionShower {
return BaseProblemSubmissionShower(resp)
}
}
}
private class BaseProblemSubmissionShower(
private val resp: GetProblemByIdOk
) : ProblemSubmissionShower {
private val errorHandler = JudgeResultDisplayErrorHandler.getHandler()
override fun show(div: Container) {
if (resp.problem.problemId == null) {
return Messager.toastInfo("ProblemId 为空")
}
observableOf<ISubmissionService.GetLastNProblemSubmissionResp>(null) {
setUpdater {
SubmissionModel.getLastNProblemSubmission(resp.problem.problemId)
}
div.sync { resp ->
if (resp == null) {
loading()
} else {
onShow(this, resp)
}
}
}
}
private fun onShow(
root: Container,
resp: ISubmissionService.GetLastNProblemSubmissionResp
) {
when (resp) {
is GetLastNProblemSubmissionRespImpl -> onSuccess(root, resp)
LanguageNotFound -> errorHandler.handleLanguageNotFound(root, -1)
PermissionDenied -> Messager.toastInfo("你还为登入哦,无法查看历史记录")
ISubmissionService.ProblemNotFound -> Messager.toastInfo("该题目不存在,或者已被删除")
}
}
private fun onSuccess(
root: Container,
resp: GetLastNProblemSubmissionRespImpl
) {
console.log(resp.submissions)
root.alert(AlertType.Light) {
h4 {
+"提交记录"
}
tabulator(
resp.submissions, options = TabulatorOptions(
layout = Layout.FITCOLUMNS,
columns = listOf(
defineColumn("提交时间") {
Span {
+it.submitTime.ll()
}
},
defineColumn("提交语言") {
Span {
+(it.language.languageName + ":" + it.language.languageVersion)
}
},
defineColumn("结果") {
when (it.passerResult) {
is PasserResult.BooleanResult -> {
Span {
BooleanPasserResultDisplay(it.passerResult, codeId = it.codeId, small = true)
.load(this)
}
}
}
}
)
)
)
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/ProblemSubmissionShower.kt | 3785430532 |
package cn.llonvne.site.problem.detail
import cn.llonvne.compoent.*
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.problem.context.TestCaseType
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.GetProblemByIdOk
import cn.llonvne.kvision.service.IProblemService.ProblemGetByIdResult.ProblemNotFound
import cn.llonvne.model.ProblemModel
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.h4
import io.kvision.html.p
fun detail(root: Container, problemId: Int, configurer: ProblemDetailConfigurer.() -> Unit = {}) {
val configure = ProblemDetailConfigurer()
configure.configurer()
if (configure.notShowProblem) {
root.alert(AlertType.Secondary) {
h4 {
+"题目显示已经被关闭"
}
p {
+configure.notShowProblemMessage
}
}
return
}
observableOf<ProblemGetByIdResult>(null) {
setUpdater {
ProblemModel.getById(problemId)
}
sync(root.div { }) { resp ->
if (resp == null) {
loading()
} else {
ProblemDetailShower.from(problemId, resp, configure).show(this)
}
}
}
}
private fun interface ProblemDetailShower {
fun show(root: Container)
companion object {
private fun problemNotFoundDetailShower(problemId: Int) = ProblemDetailShower { root ->
root.notFound(object : NotFoundAble {
override val header: String
get() = "题目未找到"
override val notice: String
get() = "请确认题目ID正确,如果确认题目ID正确,请联系我们 ^_^"
override val errorCode: String = "ProblemNotFound-$problemId"
})
}
fun from(problemId: Int, resp: ProblemGetByIdResult, configure: ProblemDetailConfigurer): ProblemDetailShower {
return when (resp) {
is GetProblemByIdOk -> AbstractProblemDetailShower(problemId, resp, configure)
ProblemNotFound -> problemNotFoundDetailShower(problemId = problemId)
}
}
}
}
private open class AbstractProblemDetailShower(
private val problemId: Int,
resp: GetProblemByIdOk,
private val configure: ProblemDetailConfigurer
) :
ProblemDetailShower {
private val headerShower = DetailHeaderShower.from(resp)
private val contextShower = ProblemContextShower.from(resp)
private val codeEditorShower = CodeEditorShower.from(
problemId, resp,
configure.codeEditorConfigurer
)
private val testCasesShower = TestCasesShower.from(resp, filter = {
it.visibility in setOf(TestCaseType.ViewAndJudge, TestCaseType.OnlyForView)
})
private val submissionsShower = ProblemSubmissionShower.from(resp)
override fun show(root: Container) {
root.div {
headerShower.show(div { })
div(className = "row") {
div(className = "col") {
contextShower.show(div { })
testCasesShower.load(div { })
}
div(className = "col") {
codeEditorShower.show(div { })
if (!configure.disableHistory) {
submissionsShower.show(div { })
}
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/problem/detail/ProblemDetail.kt | 3273671351 |
package cn.llonvne.site
import cn.llonvne.AppScope
import cn.llonvne.compoent.addPassword
import cn.llonvne.compoent.addUsername
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import io.kvision.form.formPanel
import io.kvision.html.button
import io.kvision.modal.Dialog
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
@Serializable
internal data class LoginPanel(
val username: String,
val password: String
)
internal fun loginPanel() {
val dialog = Dialog(
"登入",
) {
val loginPanel = formPanel<LoginPanel> {
addUsername(LoginPanel::username)
addPassword(LoginPanel::password)
}
button("登入") {
onClick {
setResult(loginPanel)
}
}
}
AppScope.launch {
val data = dialog.getResult()
if (data == null) {
Messager.toastError("登入失败")
return@launch
}
if (data.validate()) {
val value = data.getData()
kotlin.runCatching {
val result = AuthenticationModel.login(value.username, value.password)
Messager.send(result.message)
}.onFailure {
Messager.toastError("请检查你的网络设置")
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/Login.kt | 3126135305 |
package cn.llonvne.site
import cn.llonvne.compoent.NotFoundAble
import cn.llonvne.compoent.notFound
import io.kvision.core.Container
interface ErrorHandler<ID> {
fun handleLanguageNotFound(root: Container, id: ID) {
root.notFound(object : NotFoundAble {
override val header: String
get() = "评测语言未找到"
override val notice: String
get() = "请尝试再次提交,如果还是错误,请联系我们"
override val errorCode: String
get() = "ErrorCode-LanguageNotFound-$id"
})
}
fun handleCodeNotFound(root: Container, id: ID) {
root.notFound(object : NotFoundAble {
override val header: String
get() = "评测结果未找到"
override val notice: String
get() = "请尝试再次提交,如果还是错误,请联系我们"
override val errorCode: String
get() = "ErrorCode-PlaygroundOutputNotFound-CodeId-${id}"
})
}
fun handleJudgeResultParseError(root: Container, id: ID) {
root.notFound(object : NotFoundAble {
override val header: String
get() = "无法解析评测结果"
override val notice: String
get() = "请尝试再次提交,如果还是错误,请联系我们"
override val errorCode: String
get() = "JudgeResultParseError-CodeId-${id}"
})
}
fun handleSubmissionNotFound(root: Container, id: ID) {
root.notFound(object : NotFoundAble {
override val header: String
get() = "找到不到提交记录"
override val notice: String
get() = "请确认提交号正确"
override val errorCode: String
get() = "SubmissionNotFound-CodeId-${id}"
})
}
}
class JudgeResultDisplayErrorHandler private constructor() : ErrorHandler<Int> {
companion object {
private val errorHandler = JudgeResultDisplayErrorHandler()
fun getHandler(): ErrorHandler<Int> = errorHandler
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/ErrorHandler.kt | 979841012 |
package cn.llonvne.site
import cn.llonvne.AppScope
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.kvision.service.ISubmissionService.GetLastNPlaygroundSubmissionResp.SuccessGetLastNPlaygroundSubmission
import cn.llonvne.kvision.service.InternalError
import cn.llonvne.kvision.service.LanguageNotFound
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.ll
import cn.llonvne.message.Messager
import cn.llonvne.model.RoutingModule
import cn.llonvne.model.SubmissionModel
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.form.formPanel
import io.kvision.form.select.TomSelect
import io.kvision.form.text.TextArea
import io.kvision.html.*
import io.kvision.utils.px
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
@Serializable
data class PlaygroundSubmission(
val language: String, val code: String, val stdin: String? = ""
)
fun Container.playground() {
alert(AlertType.Light) {
h1 { +"代码训练场" }
p {
+"*训练场提交的代码会永久在服务器保存,且不可删除。请注意保护个人隐私,不要上传任何有关个人隐私的内容"
}
}
div(className = "row") {
div(className = "col") {
alert(AlertType.Secondary) {
val form = formPanel<PlaygroundSubmission> {
add(PlaygroundSubmission::language, TomSelect(
options = SupportLanguages.entries.map {
it.languageId.toString() to "${it.languageName} ${it.languageVersion}"
}, label = "语言"
) {
maxWidth = 300.px
})
add(PlaygroundSubmission::stdin, TextArea(label = "标准输入"))
add(PlaygroundSubmission::code, TextArea(label = "代码") {
rows = 11
})
}
button("提交") {
onClick {
AppScope.launch {
val data = form.getData()
val resp = SubmissionModel.submit(
PlaygroundSubmission(data.language, data.code, data.stdin)
)
Messager.toastInfo(resp.toString())
}
}
}
}
}
div(className = "col") {
h4 { +"最近一次运行结果" }
val lastRun = div { }
h4 { +"历史记录" }
alert(AlertType.Dark) {
AppScope.launch {
when (val resp = SubmissionModel.getLastNPlaygroundSubmission()) {
is InternalError -> {
Messager.toastError("内部错误:${resp.reason}")
}
LanguageNotFound -> {
Messager.toastError(resp.toString())
}
PermissionDenied -> {
Messager.toastError("你还为登入,无法获得历史记录")
}
is SuccessGetLastNPlaygroundSubmission -> {
Messager.toastInfo(resp.subs.toString())
val sortByTime = resp.subs.sortedByDescending {
it.submitTime
}
val first = sortByTime.firstOrNull()
if (first != null) {
lastRun.apply {
JudgeResultDisplay.playground(first.codeId, lastRun)
onClick {
RoutingModule.routing.navigate("/share/${first.codeId}")
}
}
}
sortByTime.forEach { dto ->
alert(AlertType.Light) {
link("训练场提交-语言:${dto.language}-时间:${dto.submitTime.ll()}") {
onClick {
RoutingModule.routing.navigate("/share/${dto.codeId}")
}
}
}
}
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/Playground.kt | 3308859452 |
package cn.llonvne.site
import cn.llonvne.compoent.NotFoundAble
import cn.llonvne.compoent.circleCheck
import cn.llonvne.compoent.loading
import cn.llonvne.compoent.notFound
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.dtos.ViewCodeDto
import cn.llonvne.entity.problem.SubmissionStatus
import cn.llonvne.kvision.service.CodeNotFound
import cn.llonvne.kvision.service.ISubmissionService.*
import cn.llonvne.kvision.service.ISubmissionService.ViewCodeGetByIdResp.SuccessfulGetById
import cn.llonvne.kvision.service.JudgeResultParseError
import cn.llonvne.kvision.service.LanguageNotFound
import cn.llonvne.model.SubmissionModel
import io.kvision.core.Container
import io.kvision.html.code
import io.kvision.html.div
import io.kvision.routing.Routing
import io.kvision.state.bind
fun Container.submissionDetail(routing: Routing, submissionId: Int) {
val alert = div {}
add(alert)
observableOf<ViewCodeGetByIdResp?>(null) {
setUpdater {
SubmissionModel.codeGetById(submissionId)
}
div().bind(this) { submission ->
if (submission == null) {
loading()
} else {
when (submission) {
LanguageNotFound -> {
codeNotfound(submission, submissionId)
}
ProblemNotFound -> {
codeNotfound(submission, submissionId)
}
SubmissionNotFound -> {
codeNotfound(submission, submissionId)
}
UserNotFound -> {
codeNotfound(submission, submissionId)
}
is SuccessfulGetById -> {
showStatus(submission.viewCodeDto)
}
CodeNotFound -> {
codeNotfound(submission, submissionId)
}
JudgeResultParseError -> {
codeNotfound(submission, submissionId)
}
}
}
}
}
}
fun Container.showStatus(submission: ViewCodeDto) {
when (submission.status) {
SubmissionStatus.Received -> circleCheck()
SubmissionStatus.Finished -> circleCheck()
}
code(submission.rawCode)
}
fun Container.codeNotfound(type: ViewCodeGetByIdResp, id: Int) {
notFound(object : NotFoundAble {
override val header: String
get() = "代码走丢啦"
override val notice: String
get() = "请检查你的提交ID是否正确,如果确认ID正确,但无法打开代码,请联系我们 ^_^"
override val errorCode: String
get() = "ErrorCode:${type}-${id}"
})
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/SubmissionDetail.kt | 2462006430 |
package cn.llonvne.site
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.message.Messager
import io.kvision.core.Container
import io.kvision.form.select.tomSelect
import io.kvision.form.text.text
import io.kvision.html.*
import io.kvision.routing.Routing
fun Container.index(routing: Routing) {
alert(AlertType.Light) {
h1 {
+"Online Judge"
}
}
div(className = "row") {
div(className = "col") {
alert(AlertType.Secondary) {
h4 {
+"作为个人用户"
}
p {
+"点击左上角注册账号,立刻开始使用"
}
h6 {
+"功能介绍"
}
ul {
li {
+"题库:查找有兴趣的题目"
}
li {
+"提交:查看你的所有题目的提交"
}
li {
+"训练场:在线测试您的代码"
}
}
}
alert(type = AlertType.Warning) {
h4 {
+"查看我们的免费课程"
}
}
}
div(className = "col") {
alert(AlertType.Info) {
h4 {
+"作为团队/学校用户"
}
h6 {
+"输入您的通行凭证(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)"
}
val text = text(InputType.TEXT)
div {
button("转到", style = ButtonStyle.OUTLINESECONDARY) {
onClick {
if (text.value?.length == 36) {
routing.navigate("/team/${text.value}")
} else {
Messager.toastInfo("不是合法的凭证")
}
}
}
}
br { }
h6 {
+"查找您的组织"
}
label {
+"请注意如果团队/学校选择了不公开其组织名称,那么您只能通过通行凭证加入"
}
tomSelect {
}
h6 {
+"新建团队/学校"
}
label {
+"建立您自己的团队/学校"
}
br { }
button("新建", style = ButtonStyle.OUTLINESECONDARY) {
onClick {
routing.navigate("/team/create")
}
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/Index.kt | 2076136483 |
package cn.llonvne.site.team
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.group.GroupType
import cn.llonvne.entity.group.GroupVisibility
import cn.llonvne.kvision.service.*
import cn.llonvne.kvision.service.IGroupService.CreateGroupResp.CreateGroupOk
import cn.llonvne.message.Messager
import cn.llonvne.model.TeamModel
import io.kvision.core.Container
import io.kvision.core.onChangeLaunch
import io.kvision.core.onClickLaunch
import io.kvision.form.formPanel
import io.kvision.form.select.TomSelect
import io.kvision.form.text.Text
import io.kvision.html.button
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.p
import io.kvision.routing.Routing
import kotlinx.serialization.Serializable
@Serializable
private data class CreateTeam(
val teamName: String, val shortName: String, val visibilityStr: String, val typeStr: String, val description: String
)
fun teamCreate(root: Container, routing: Routing) {
root.div {
div(className = "row") {
alert(AlertType.Info) {
h1 {
+"创建队伍"
}
p {
+"创建小组/组织,来团结合作解决问题"
}
}
div(className = "col-6") {
alert(AlertType.Light) {
val form = formPanel<CreateTeam> {
add(CreateTeam::teamName, Text {
label = "你的组织的名字"
}, required = true)
observableOf("") {
add(
CreateTeam::shortName, sync(Text()) {
label =
"短名称,仅支持数字英文,最长不超过20个字符(你可以通过 /t/${it ?: "<短名称>"} 访问您的组织)"
onChangeLaunch {
setObv(this.value ?: "<短名称>")
}
}, required = true
)
}
add(
CreateTeam::visibilityStr, TomSelect(
options = GroupVisibility.options, label = "小组可见性"
), required = true
)
add(
CreateTeam::typeStr, TomSelect(
options = GroupType.options, label = "小组类型(对于个人用户,请选择经典小组)"
), required = true
)
add(CreateTeam::description, Text {
label = "描述"
placeholder = "用一句话简单描述一下吧"
}, required = true)
button("提交") {
onClickLaunch {
form.clearValidation()
if (!form.validate()) {
return@onClickLaunch
}
val createTeam = form.getData()
val resp = TeamModel.create(
IGroupService.CreateGroupReq(
groupName = createTeam.teamName,
groupShortName = createTeam.shortName,
teamVisibility = GroupVisibility.entries[createTeam.visibilityStr.toInt()],
groupType = GroupType.entries[createTeam.typeStr.toInt()],
description = createTeam.description
)
)
when (resp) {
is ClientError -> Messager.toastInfo(resp.message)
is CreateGroupOk -> Messager.toastInfo("成功创建小组,小组ID为${resp.group.groupId}")
PermissionDenied -> Messager.toastInfo("你没有创建改小组的权限,或者你还未登入")
is InternalError -> Messager.toastInfo(resp.reason)
is GroupShortNameUnavailable -> Messager.toastInfo("小组短名称${resp.shortName}已被占用")
}
}
}
}
}
}
div(className = "col-6") {
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/TeamCreate.kt | 3961370643 |
package cn.llonvne.site.team.show
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.group.GroupId
import cn.llonvne.entity.group.GroupLoader
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.model.TeamModel.of
import cn.llonvne.site.team.show.member.GroupMemberShower
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.routing.Routing
fun showGroup(root: Container, groupId: GroupId, routing: Routing) {
val groupLoader = GroupLoader.of(groupId)
GroupShower(groupLoader).show(root, routing)
}
private class GroupShower(private val groupLoader: GroupLoader) {
private val obv = observableOf<LoadGroupResp>(null) {
setUpdater {
groupLoader.load()
}
}
fun show(root: Container, routing: Routing) {
obv.sync(root) { resp ->
if (resp == null) {
return@sync
}
div {
GroupHeaderShower.from(resp).load(this)
}
div(className = "row") {
div(className = "col") {
GroupMemberShower.from(resp).show(this)
}
div(className = "col") {
GroupNoticeShower.from(resp).load(this)
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/TeamShow.kt | 7521608 |
package cn.llonvne.site.team.show.member
import cn.llonvne.compoent.badge
import cn.llonvne.compoent.team.KickMemberResolver
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.*
import io.kvision.core.onClickLaunch
import io.kvision.html.Span
fun interface KickOp {
fun load(target: Span, user: GroupMemberDto, kickMemberResolver: KickMemberResolver)
companion object {
private val emptyKickOp = KickOp { _, _, _ -> }
fun from(resp: LoadGroupSuccessResp): KickOp {
val impl = KickOpImpl()
return when (resp) {
is GuestLoadGroup -> emptyKickOp
is MemberLoadGroup -> emptyKickOp
is OwnerLoadGroup -> {
KickOp { target: Span, user: GroupMemberDto, kickMemberResolver: KickMemberResolver ->
onNotSelf(user) {
impl.load(target, user, kickMemberResolver)
}
}
}
is ManagerLoadGroup -> {
KickOp { target, user, kickMemberResolver ->
onNotSelf(user) {
onNotOwner(user) {
onNotManager(user) {
impl.load(target, user, kickMemberResolver)
}
}
}
}
}
}
}
}
}
private class KickOpImpl : KickOp {
override fun load(target: Span, user: GroupMemberDto, kickMemberResolver: KickMemberResolver) {
target.badge(BadgeColor.Red) {
onClickLaunch {
kickMemberResolver.resolve(user.userId)
}
+"踢出"
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/member/KickOp.kt | 3111234038 |
package cn.llonvne.site.team.show.member
import cn.llonvne.entity.role.GroupManager
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.GroupMemberDto
import cn.llonvne.model.AuthenticationModel
fun onNotSelf(user: GroupMemberDto, block: () -> Unit) {
if (user.userId != AuthenticationModel.userToken.value?.id) {
block()
}
}
fun onNotManager(user: GroupMemberDto, block: () -> Unit) {
if (user.role !is GroupManager) {
block()
}
}
fun onManager(user: GroupMemberDto, block: () -> Unit) {
if (user.role is GroupManager) {
block()
}
}
fun onNotOwner(user: GroupMemberDto, block: () -> Unit) {
if (user.role !is GroupOwner) {
block()
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/member/UserRestricters.kt | 2661698757 |
package cn.llonvne.site.team.show.member
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badge
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.team.*
import cn.llonvne.entity.role.DeleteTeam
import cn.llonvne.entity.role.GroupManager.GroupMangerImpl
import cn.llonvne.entity.role.GroupOwner
import cn.llonvne.entity.role.InviteMember.InviteMemberImpl
import cn.llonvne.entity.role.KickMember.KickMemberImpl
import cn.llonvne.entity.role.TeamMember.TeamMemberImpl
import cn.llonvne.entity.role.TeamSuperManager.TeamSuperManagerImpl
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.*
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.RoutingModule
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.html.*
import io.kvision.tabulator.ColumnDefinition
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
interface GroupMemberShower {
fun show(target: Container)
companion object {
fun from(resp: LoadGroupResp): GroupMemberShower {
val memberShower = when (resp) {
is GroupIdNotFound -> emptyMemberShower
is GuestLoadGroup -> GuestMemberShower(resp)
PermissionDenied -> emptyMemberShower
is ManagerLoadGroup -> ManagerMemberShower(resp)
is MemberLoadGroup -> MemberMemberShower(resp)
is OwnerLoadGroup -> OwnerMemberShower(resp)
}
return memberShower
}
private val emptyMemberShower = object : GroupMemberShower {
override fun show(target: Container) {}
}
}
}
/**
* 读取小组成功后[LoadGroupSuccessResp]用于显示的基类
*/
private abstract class AbstractMemberShower(private val resp: LoadGroupSuccessResp) : GroupMemberShower {
override fun show(target: Container) {
target.alert(AlertType.Light) {
div {
loadButtons()
}
h4 {
+"成员列表"
}
tabulator(
resp.members,
options = TabulatorOptions(
layout = Layout.FITDATASTRETCH, columns = defaultColumns() + addColumnDefinition()
)
)
slot()
}
}
private fun Div.defaultColumns(): List<ColumnDefinition<GroupMemberDto>> =
listOf(
ColumnDefinition("用户名", formatterComponentFunction = { _, _, e ->
displayUsername(e)
}),
ColumnDefinition("身份", formatterComponentFunction = { _, _, e ->
displayRole(e)
})
)
protected open fun Div.displayRole(e: GroupMemberDto) = span {
when (e.role) {
is DeleteTeam.DeleteTeamImpl -> {}
is GroupMangerImpl -> badge(BadgeColor.Red) { +"管理员" }
is GroupOwner.GroupOwnerImpl -> badge(BadgeColor.Red) { +"所有者" }
is InviteMemberImpl -> {}
is KickMemberImpl -> {}
is TeamMemberImpl -> {
badge(BadgeColor.Grey) { +"成员" }
}
is TeamSuperManagerImpl -> badge(BadgeColor.Dark) {
+"队伍超级管理员"
}
}
}
protected open fun Div.displayUsername(e: GroupMemberDto) = span {
+e.username
}
protected open fun Div.addColumnDefinition(): List<ColumnDefinition<GroupMemberDto>> = listOf()
open fun Container.loadButtons() {}
protected open fun Div.slot() {}
}
private class GuestMemberShower(private val resp: GuestLoadGroup) : AbstractMemberShower(resp) {
override fun Container.loadButtons() {
button("现在加入") {
onClick {
val token =
AuthenticationModel.userToken.value ?: return@onClick Messager.toastInfo("登入后才可以加入小组")
JoinGroupResolver(RoutingModule.routing)
.resolve(resp.groupId, resp.groupName, token)
}
}
}
}
private class ManagerMemberShower(private val resp: ManagerLoadGroup) : AbstractMemberShower(resp) {
private val kickMemberResolver = KickMemberResolver(groupId = resp.groupId)
override fun Div.addColumnDefinition(): List<ColumnDefinition<GroupMemberDto>> = listOf(
defineColumn("操作") { user ->
span {
KickOp.from(resp).load(this, user, kickMemberResolver)
}
}
)
}
private fun Span.upgradeToGroupMangerOp(
user: GroupMemberDto,
upgradeToGroupManagerResolver: UpgradeToGroupManagerResolver
) = onNotSelf(user) {
onNotManager(user) {
badge(BadgeColor.Red) {
onClickLaunch {
upgradeToGroupManagerResolver.resolve(user)
}
+"升级为管理员"
}
}
}
private fun Span.downgradeToGroupMemberOp(
user: GroupMemberDto,
downgradeToGroupMemberResolver: DowngradeToGroupMemberResolver
) = onNotSelf(user) {
onManager(user) {
badge(BadgeColor.Red) {
onClickLaunch {
downgradeToGroupMemberResolver.resolve(user)
}
+"降级为成员"
}
}
}
private class OwnerMemberShower(private val resp: OwnerLoadGroup) : AbstractMemberShower(resp) {
override fun Div.addColumnDefinition(): List<ColumnDefinition<GroupMemberDto>> = listOf(
defineColumn("操作") { user ->
span {
KickOp.from(resp).load(this, user, KickMemberResolver(groupId = resp.groupId))
upgradeToGroupMangerOp(user, UpgradeToGroupManagerResolver(groupId = resp.groupId))
downgradeToGroupMemberOp(user, DowngradeToGroupMemberResolver(resp.groupId))
}
}
)
}
private class MemberMemberShower(private val resp: MemberLoadGroup) : AbstractMemberShower(resp) {
override fun Container.loadButtons() {
GroupMemberQuitResolver(resp.groupId).load(this)
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/member/GroupMemberShower.kt | 2922045378 |
package cn.llonvne.site.team.show
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.*
import cn.llonvne.kvision.service.PermissionDenied
import io.kvision.core.Container
import io.kvision.html.h4
fun interface GroupNoticeShower {
fun load(root: Container)
companion object {
fun from(resp: LoadGroupResp): GroupNoticeShower {
return when (resp) {
is GroupIdNotFound -> emptyNoticeShower
is GuestLoadGroup -> GuestGroupNoticeShower(resp)
PermissionDenied -> emptyNoticeShower
is ManagerLoadGroup -> ManagerGroupNoticeShower(resp)
is MemberLoadGroup -> MemberGroupNoticeShower(resp)
is OwnerLoadGroup -> OwnerGroupNoticeShower(resp)
}
}
private val emptyNoticeShower = GroupNoticeShower { }
}
}
private abstract class AbstractGroupNoticeShower(private val resp: LoadGroupSuccessResp) :
GroupNoticeShower {
override fun load(root: Container) {
root.alert(AlertType.Light) {
h4 {
+"公告"
}
}
}
}
private class GuestGroupNoticeShower(private val resp: GuestLoadGroup) : AbstractGroupNoticeShower(resp)
private class ManagerGroupNoticeShower(private val resp: ManagerLoadGroup) : AbstractGroupNoticeShower(resp)
private class MemberGroupNoticeShower(private val resp: MemberLoadGroup) : AbstractGroupNoticeShower(resp)
private class OwnerGroupNoticeShower(private val resp: OwnerLoadGroup) : AbstractGroupNoticeShower(resp) | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/GroupNoticeShower.kt | 1246826961 |
package cn.llonvne.site.team.show
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badge
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.kvision.service.GroupIdNotFound
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp
import cn.llonvne.kvision.service.IGroupService.LoadGroupResp.*
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.ll
import cn.llonvne.message.Messager
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.html.h4
import io.kvision.html.p
sealed interface GroupHeaderShower {
fun load(root: Container)
companion object {
fun from(resp: LoadGroupResp): GroupHeaderShower {
return when (resp) {
is GroupIdNotFound -> GroupIdNotFoundShower
is GuestLoadGroup -> GuestGroupHeaderShower(resp)
PermissionDenied -> GroupIdNotFoundShower
is ManagerLoadGroup -> ManagerGroupHeaderShower(resp)
is MemberLoadGroup -> MemberGroupHeaderShower(resp)
is OwnerLoadGroup -> OwnerLoadGroupShower(resp)
}
}
}
}
private data object GroupIdNotFoundShower : GroupHeaderShower {
override fun load(root: Container) {
root.alert(AlertType.Danger) {
h4 {
+"对应小组未找到"
}
p {
+"可能是该小组不存在或者对方设置了查看权限"
}
}
}
}
private abstract class AbstractGroupHeaderShower(private val resp: LoadGroupResp.LoadGroupSuccessResp) :
GroupHeaderShower {
override fun load(root: Container) {
root.alert(AlertType.Light) {
h4 {
+resp.groupName
}
p {
+resp.description
}
badge(BadgeColor.Golden) {
+"所有者:${resp.ownerName}"
}
badge(BadgeColor.Grey) {
+"短名称:${resp.groupShortName}"
}
badge(BadgeColor.Red) {
+resp.visibility.shortChinese
onClick {
Messager.toastInfo(resp.visibility.chinese)
}
}
badge(BadgeColor.Blue) {
+resp.type.shortChinese
onClick {
Messager.toastInfo(resp.type.chinese)
}
}
badge(BadgeColor.White) {
+"创建于:${resp.createAt.ll()}"
}
slot()
}
}
open fun Container.slot() {}
}
private open class GuestGroupHeaderShower(private val resp: GuestLoadGroup) : AbstractGroupHeaderShower(resp)
private open class ManagerGroupHeaderShower(val resp: ManagerLoadGroup) : AbstractGroupHeaderShower(resp)
private class OwnerLoadGroupShower(resp: OwnerLoadGroup) : AbstractGroupHeaderShower(resp)
private class MemberGroupHeaderShower(val resp: MemberLoadGroup) : AbstractGroupHeaderShower(resp)
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/show/GroupHeaderShower.kt | 1539835856 |
package cn.llonvne.site.team
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.p
interface TeamIndex {
fun show(root: Container)
companion object {
fun from(): TeamIndex {
return TeamIndexBase()
}
}
}
class TeamIndexBase : TeamIndex {
override fun show(root: Container) {
root.div {
alert(AlertType.Light) {
h1 {
+"队伍"
}
p {
+"众人拾柴火焰高"
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/team/Team.kt | 3424188714 |
package cn.llonvne.site
import cn.llonvne.AppScope
import cn.llonvne.compoent.*
import cn.llonvne.constants.Frontend
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import io.kvision.core.Container
import io.kvision.form.formPanel
import io.kvision.html.button
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.h4
import io.kvision.routing.Routing
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
@Serializable
internal data class RegisterForm(
val username: String,
val password: String
)
internal fun Container.registerPanel(routing: Routing) {
val alert = div { }
add(alert)
h1 {
+"Register"
}
navigateButton(routing, Frontend.Index)
val registerPanel = formPanel<RegisterForm> {
addUsername(RegisterForm::username)
addPassword(RegisterForm::password)
}
button("注册") {
onClick {
AppScope.launch {
if (registerPanel.validate()) {
val value = registerPanel.getData()
runCatching {
AuthenticationModel.register(value.username, value.password)
}.onFailure {
alert.alert(AlertType.Danger) {
h4 { +"请检查你的网络设置" }
}
}.onSuccess { result ->
Messager.send(result.message)
if (result.isOk()) {
routing.navigate("/")
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/Register.kt | 3469118586 |
package cn.llonvne.site.mine
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.kvision.service.IMineService
import cn.llonvne.kvision.service.IMineService.DashboardResp.DashboardRespImpl
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.MineModel
import io.kvision.core.Container
import io.kvision.html.Div
import io.kvision.html.div
import io.kvision.html.h4
data class DashBoard(override val name: String = "仪表盘") : AdminMineChoice {
override fun show(root: Container) {
observableOf<IMineService.DashboardResp>(null) {
setUpdater { MineModel.dashboard() }
syncNotNull(root.div { }) { resp ->
when (resp) {
is DashboardRespImpl -> onSuccess(resp)
PermissionDenied -> Messager.toastInfo("你未登入,或者不具有后台权限")
}
}
}
}
private fun Div.onSuccess(resp: DashboardRespImpl) {
alert(AlertType.Light) {
h4 {
+"统计数据"
}
div(className = "row") {
div(className = "col") {
alert(AlertType.Info) {
h4 {
+"用户总数: ${resp.statistics.totalUserCount}"
}
}
}
div(className = "col") {
alert(AlertType.Success) {
h4 {
+"今日总提交: ${resp.statistics.totalSubmissionToday}"
}
}
}
div(className = "col") {
alert(AlertType.Secondary) {
h4 {
+"近两周比赛: ${resp.statistics.totalContestLastTwoWeek}"
}
}
}
}
}
alert(AlertType.Light) {
h4 {
+"后端系统"
}
div(className = "row") {
div(className = "col") {
alert(AlertType.Success) {
+"名称: ${resp.backendInfo.name}"
}
}
div(className = "col") {
alert(AlertType.Info) {
+"地址: ${resp.backendInfo.host}"
}
}
div(className = "col") {
alert(AlertType.Secondary) {
+"端口: ${resp.backendInfo.port}"
}
}
div(className = "col") {
alert(AlertType.Danger) {
+"CPU 使用率: ${resp.backendInfo.cpuUsage}"
}
}
div(className = "col") {
alert(AlertType.Warning) {
+"CPU 核心数: ${resp.backendInfo.cpuCoresCount}"
}
}
div(className = "col") {
alert(AlertType.Primary) {
+"使用中的内存: ${resp.backendInfo.usedMemory / 1048576} MB"
}
}
div(className = "col") {
alert(AlertType.Dark) {
+"总内存: ${resp.backendInfo.totalMemory / 1048576} MB"
}
}
}
}
alert(AlertType.Light) {
h4 {
+"评测机"
}
div(className = "row") {
div(className = "col") {
alert(AlertType.Success) {
+"名称: ${resp.judgeServerInfo.name}"
}
}
div(className = "col") {
alert(AlertType.Info) {
+"地址: ${resp.judgeServerInfo.host}"
}
}
div(className = "col") {
alert(AlertType.Secondary) {
+"端口: ${resp.judgeServerInfo.port}"
}
}
div(className = "col") {
alert(AlertType.Danger) {
+"CPU 使用率: ${resp.judgeServerInfo.cpuUsage}"
}
}
div(className = "col") {
alert(AlertType.Warning) {
+"CPU 核心数: ${resp.judgeServerInfo.cpuCoresCount}"
}
}
div(className = "col") {
alert(AlertType.Primary) {
+"使用中的内存: ${resp.judgeServerInfo.memoryUsage / 1048576} MB"
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/mine/DashBoard.kt | 3113032051 |
package cn.llonvne.site.mine
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.p
sealed interface AdminMineChoice {
val name: String
fun show(root: Container)
companion object {
private val choices by lazy {
listOf(
DashBoard(),
UserManage(),
SystemSettings(),
ProblemManage(),
ContestManage()
)
}
internal fun getAdminMineChoices() = choices
internal fun defaultChoice() = choices.first()
}
}
data class SystemSettings(override val name: String = "系统设置") : AdminMineChoice {
override fun show(root: Container) {
root.div {
p {
+name
}
}
}
}
data class ProblemManage(override val name: String = "题目管理") : AdminMineChoice {
override fun show(root: Container) {
root.div {
p {
+name
}
}
}
}
data class ContestManage(override val name: String = "比赛管理") : AdminMineChoice {
override fun show(root: Container) {
root.div {
p {
+name
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/mine/AdminMineChoice.kt | 3590094091 |
package cn.llonvne.site.mine
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.loading
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.kvision.service.IAuthenticationService.MineResp
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.model.AuthenticationModel
import io.kvision.core.Container
import io.kvision.html.*
import io.kvision.toolbar.buttonGroup
fun Container.mine() {
observableOf<MineResp>(null) {
setUpdater {
AuthenticationModel.mine()
}
sync {
if (it == null) {
loading()
} else {
Mine.from(it).load(div { })
}
}
}
}
private interface Mine {
fun load(root: Container)
companion object {
private val notLogin = object : Mine {
override fun load(root: Container) {
root.alert(AlertType.Danger) {
h4 {
+"您还未登入"
}
p {
+"请先登入账户后刷新页面"
}
}
}
}
fun from(mineResp: MineResp): Mine {
return when (mineResp) {
is MineResp.AdministratorMineResp -> AdministratorMine()
is MineResp.NormalUserMineResp -> NormalUserMine(mineResp)
PermissionDenied -> notLogin
}
}
}
}
class AdministratorMine : Mine {
override fun load(root: Container) {
root.div {
observableOf<AdminMineChoice>(null) {
setUpdater { AdminMineChoice.defaultChoice() }
alert(AlertType.Light) {
h1 {
+"Online Judge 管理面板"
}
buttonGroup {
AdminMineChoice.getAdminMineChoices().forEach { choice ->
button(choice.name) {
onClick {
setObv(choice)
}
}
}
}
}
syncNotNull(div { }) { choice ->
choice.show(this)
}
}
}
}
}
private class NormalUserMine(private val mineResp: MineResp.NormalUserMineResp) : Mine {
override fun load(root: Container) {
root.div {
alert(AlertType.Light) {
h4 {
+"Load as Normal User"
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/mine/Mine.kt | 77275344 |
package cn.llonvne.site.mine
import cn.llonvne.AppScope
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badges
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.ModifyUserForm
import cn.llonvne.entity.role.Backend
import cn.llonvne.entity.role.Banned
import cn.llonvne.entity.role.check
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.kvision.service.IMineService
import cn.llonvne.ll
import cn.llonvne.message.Messager
import cn.llonvne.model.MineModel
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onClickLaunch
import io.kvision.form.check.CheckBox
import io.kvision.form.formPanel
import io.kvision.form.text.Text
import io.kvision.html.*
import io.kvision.modal.Alert
import io.kvision.modal.Confirm
import io.kvision.modal.Dialog
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
data class UserManage(override val name: String = "用户管理") : AdminMineChoice {
override fun show(root: Container) {
root.div {
alert(AlertType.Light) {
h4 {
+"用户管理"
}
observableOf<IMineService.UsersResp>(null) {
setUpdater {
MineModel.users()
}
syncNotNull(div { }) { resp ->
when (resp) {
is IMineService.UsersResp.UsersRespImpl -> onSuccess(this, resp)
}
}
}
}
}
}
private fun onSuccess(div: Div, resp: IMineService.UsersResp.UsersRespImpl) {
div.alert(AlertType.Light) {
tabulator(
resp.users, options =
TabulatorOptions(
layout = Layout.FITDATASTRETCH,
columns = listOf(
defineColumn("用户") {
Span {
+it.username
}
},
defineColumn("创建时间") {
Span {
+it.createAt.ll()
}
},
defineColumn("状态") {
Span {
if (it.userRole.roles.check(Banned.BannedImpl)) {
+"被封禁"
} else {
+"正常"
}
}
},
defineColumn("是否为超级管理") {
Span {
if (it.userRole.roles.check(Backend.BackendImpl)) {
+"是"
} else {
+"否"
}
}
},
defineColumn("操作") { user ->
Span {
badges {
add(color = BadgeColor.Red) {
+"删除"
onClick {
Confirm.show(
"确认删除用户",
"你确定要删除用户 ${user.username}",
animation = false,
align = Align.LEFT,
yesTitle = "确认",
noTitle = "取消",
cancelVisible = false,
noCallback = {
Alert.show("删除用户通知", "你取消了删除用户的操作")
}) {
AppScope.launch {
if (MineModel.deleteUser(user.userId)) {
Alert.show("删除用户通知", "删除用户成功")
} else {
Alert.show("删除用户通知", "删除用户失败")
}
}
}
}
}
add {
+"修改"
onClickLaunch {
val dialog = Dialog<ModifyUserForm> {
val form = formPanel<ModifyUserForm> {
add(ModifyUserForm::userId, Text {
label = "用户ID"
value = user.userId.toString()
disabled = true
})
add(ModifyUserForm::username, Text {
label = "用户名"
value = user.username
})
add(ModifyUserForm::isBanned, CheckBox(label = "是否封禁") {
value = user.userRole.roles.check(Banned.BannedImpl)
})
}
button("确认") {
onClickLaunch {
setResult(form.getData())
}
}
button("取消") {
onClickLaunch {
setResult(null)
}
}
}
// TODO 重构!
if (MineModel.modifyUser(dialog.getResult())) {
Messager.toastInfo("设置成功")
} else {
Messager.toastInfo("设置失败")
}
}
}
}
}
},
)
)
)
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/mine/UserManage.kt | 522574444 |
package cn.llonvne.site
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badges
import cn.llonvne.entity.problem.context.passer.PasserResult
import cn.llonvne.model.RoutingModule
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.core.onClickLaunch
import io.kvision.html.h4
interface PasserResultDisplay {
fun load(root: Container)
companion object {
fun from(passerResult: PasserResult): PasserResultDisplay {
return when (passerResult) {
is PasserResult.BooleanResult -> BooleanPasserResultDisplay(passerResult)
}
}
}
}
class BooleanPasserResultDisplay(
private val booleanResult: PasserResult.BooleanResult,
private val codeId: Int? = null,
private val small: Boolean = false
) :
PasserResultDisplay {
private fun onSmall(root: Container) {
root.badges {
add(booleanResult.suggestColor) {
+booleanResult.readable
onClickLaunch {
RoutingModule.routing.navigate("/share/$codeId")
}
}
}
}
override fun load(root: Container) {
if (small) {
onSmall(root)
return
} else {
if (booleanResult.result) {
root.alert(AlertType.Success) {
+"Accepted"
}
} else {
root.alert(AlertType.Danger) {
h4 {
+"Wrong Answer"
}
}
}
if (codeId != null) {
root.badges {
add {
+"详情"
onClick {
RoutingModule.routing.navigate("/share/$codeId")
}
}
}
}
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/PasserResultDisplay.kt | 3782830743 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.model.RoutingModule
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.form.formPanel
import io.kvision.form.text.Text
import io.kvision.html.button
import io.kvision.html.h4
import io.kvision.html.p
import kotlinx.serialization.Serializable
@Serializable
private data class ContestIdForm(val id: String)
interface ContestNavigator {
fun show(container: Container)
companion object {
fun get(): ContestNavigator {
return object : ContestNavigator {
override fun show(container: Container) {
container.alert(AlertType.Secondary) {
h4 {
+"输入比赛 ID 或者 Hash 快速转到比赛"
}
p {
+"对于特定比赛可能只能通过 Hash 访问"
}
formPanel<ContestIdForm> {
add(ContestIdForm::id, Text(label = "比赛ID/Hash"), required = true)
button("转到") {
onClickLaunch {
RoutingModule.routing.navigate("/contest/${getData().id}")
}
}
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/ContestNavigator.kt | 908791094 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.notFound
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.kvision.service.ISubmissionService
import cn.llonvne.kvision.service.ISubmissionService.GetParticipantContestResp.GetParticipantContestOk
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.RoutingModule
import cn.llonvne.model.SubmissionModel
import cn.llonvne.site.contest.detail.ContestStatusResolver
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.html.Span
import io.kvision.html.div
import io.kvision.html.h4
import io.kvision.html.p
import io.kvision.state.bind
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
fun participantContestList(root: Container) {
root.div().bind(AuthenticationModel.userToken) {
if (it == null) {
alert(AlertType.Info) {
h4 {
+"你还未登入,无法获取已经参加的比赛"
}
}
} else {
alert(AlertType.Info) {
h4 {
+"您参加的比赛"
}
p {
+"你必须在比赛中作出一次有效提交才能计入参加比赛"
}
observableOf<ISubmissionService.GetParticipantContestResp>(null) {
setUpdater { SubmissionModel.getParticipantContest() }
sync(div { }) { resp ->
when (resp) {
is GetParticipantContestOk -> onOk(div { }, resp)
PermissionDenied -> notFound("你还为登入", "登入后才可以查看参加的比赛哦", "NotLogin")
null -> {}
}
}
}
}
}
}
}
private fun onOk(root: Container, resp: GetParticipantContestOk) {
root.tabulator(
resp.contests, options = TabulatorOptions(
layout = Layout.FITCOLUMNS,
columns = listOf(
defineColumn("比赛名") {
Span {
+it.title
val id = it.contestId
onClickLaunch {
RoutingModule.routing.navigate("/contest/$id")
}
}
},
defineColumn("状态") {
val contestStatusResolver = ContestStatusResolver(it.startAt, it.endAt)
Span {
+contestStatusResolver.status().name
}
},
defineColumn("AC 数量") {
Span {
}
},
defineColumn("题目总数") {
Span {
+it.context.problems.size.toString()
}
}
)
)
)
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/ParticipantContestList.kt | 4056789514 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.model.RoutingModule
import io.kvision.core.Container
import io.kvision.html.ButtonStyle
import io.kvision.html.button
import io.kvision.html.h4
import io.kvision.html.p
fun createContestEntry(root: Container) {
root.alert(AlertType.Success) {
h4 {
+"没有想参加的比赛?,自己来组织吧!"
}
p {
+"点击下方链接即可创建比赛"
}
button("创建比赛", style = ButtonStyle.OUTLINESECONDARY) {
onClick {
RoutingModule.routing.navigate("/contest/create")
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/CreateContestEntry.kt | 2887980406 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.*
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.contest.HashId
import cn.llonvne.entity.contest.IntId
import cn.llonvne.kvision.service.ContestNotFound
import cn.llonvne.kvision.service.ContestOwnerNotFound
import cn.llonvne.kvision.service.IContestService
import cn.llonvne.kvision.service.IContestService.LoadContestResp.LoadOk
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.model.ContestModel
import cn.llonvne.site.contest.Display.*
import cn.llonvne.site.contest.detail.ContestDetailHeader
import cn.llonvne.site.contest.detail.ContestProblemDisplay
import cn.llonvne.site.contest.detail.ContestStatusResolver
import cn.llonvne.site.contest.detail.ProblemChooser
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.html.button
import io.kvision.html.div
import cn.llonvne.site.contest.Display as ContestDisplay
sealed interface ContestDetail {
fun show(root: Container)
companion object {
private data object ContestNotFound : ContestDetail {
override fun show(root: Container) {
root.notFound(object : NotFoundAble {
override val header: String
get() = "比赛未找到"
override val notice: String
get() = "请确认比赛ID正确,如果确认比赛ID正确,请联系我们 ^_^"
override val errorCode: String = "ContestNotFound"
})
}
}
fun from(id: String): ContestDetail {
val intId = id.toIntOrNull()
val contestId: ContestId = if (intId != null) {
IntId(intId)
} else if (id.length == 36) {
HashId(id)
} else {
return ContestNotFound
}
return BaseContestDetail(contestId)
}
}
}
sealed interface Display {
data class ProblemIndex(val id: Int) : ContestDisplay
data object Status : ContestDisplay
data object None : ContestDisplay
}
private class BaseContestDetail(private val contestId: ContestId) : ContestDetail {
override fun show(root: Container) {
observableOf<IContestService.LoadContestResp>(null) {
setUpdater {
ContestModel.load(contestId)
}
sync(root.div { }) { resp ->
if (resp == null) {
loading()
} else {
when (resp) {
ContestNotFound -> notFound(
"比赛未找到",
"请检查比赛ID是否正确,如果确认比赛ID正确,请联系我们.",
"ContestNotFound-$contestId"
)
is LoadOk -> {
onOk(this, resp)
}
PermissionDenied -> notFound("你还为登入", "请登入后查看该页面", "NotLogin")
ContestOwnerNotFound -> notFound(
"所有者账号处于异常状态,该比赛已经不可查看",
"如有问题请联系管理",
"OwnerIdNotFound"
)
}
}
}
}
}
fun onOk(container: Container, loadOk: LoadOk) {
val contestDetailHeader = ContestDetailHeader.form(loadOk = loadOk)
val problemChooser = ProblemChooser.from(loadOk)
val statusResolver = ContestStatusResolver(loadOk.contest.startAt, loadOk.contest.endAt)
val problemDisplay = ContestProblemDisplay.from(contestId, statusResolver)
container.div {
contestDetailHeader.show(div { })
observableOf<ContestDisplay>(None) {
setUpdater { ProblemIndex(loadOk.contest.context.problems.first().problemId) }
sync(div { }) { index ->
div(className = "row") {
div(className = "col-3") {
problemChooser.show(div { }, this@observableOf)
alert(AlertType.Light) {
button("状态") {
onClickLaunch {
setObv(Status)
}
}
}
}
div(className = "col") {
if (index != null) {
when (index) {
None -> loading()
is ProblemIndex -> problemDisplay.show(div { }, index)
Status -> TODO()
}
}
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/ContestDetail.kt | 452061412 |
package cn.llonvne.site.contest.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.observable.ObservableDsl
import cn.llonvne.kvision.service.IContestService.LoadContestResp.LoadOk
import cn.llonvne.site.contest.Display
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.html.button
import io.kvision.html.div
interface ProblemChooser {
fun show(container: Container, observableDsl: ObservableDsl<Display>)
companion object {
fun from(loadOk: LoadOk): ProblemChooser = BaseProblemChooser(loadOk)
}
}
private class BaseProblemChooser(private val loadOk: LoadOk) : ProblemChooser {
override fun show(container: Container, observableDsl: ObservableDsl<Display>) {
container.div {
alert(AlertType.Light) {
loadOk.contest.context.problems.forEachIndexed { index, problem ->
button('A'.plus(index).toString()) {
onClickLaunch {
observableDsl.setObv(Display.ProblemIndex(problem.problemId))
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/detail/ProblemChooser.kt | 588881683 |
package cn.llonvne.site.contest.detail
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badges
import cn.llonvne.kvision.service.IContestService
import cn.llonvne.ll
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.h4
interface ContestDetailHeader {
fun show(container: Container)
companion object {
fun form(loadOk: IContestService.LoadContestResp.LoadOk): ContestDetailHeader =
BaseContestDetailHeader(loadOk)
}
}
private class BaseContestDetailHeader(private val loadOk: IContestService.LoadContestResp.LoadOk) :
ContestDetailHeader {
private val contestStatusResolver = ContestStatusResolver(loadOk.contest.startAt, loadOk.contest.endAt)
override fun show(container: Container) {
container.div {
alert(contestStatusResolver.statusColor()) {
h1 {
+loadOk.contest.title
}
h4(rich = true) {
+loadOk.contest.description
}
badges {
add {
+contestStatusResolver.status().name
}
add {
+"所有者:${loadOk.ownerName}"
}
add {
+loadOk.contest.contestScoreType.name
}
add {
+loadOk.contest.rankType.chinese
}
add {
+"开始于${loadOk.contest.startAt.ll()}"
}
add {
+"结束于${loadOk.contest.endAt.ll()}"
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/detail/ContestDetailHeader.kt | 804502930 |
package cn.llonvne.site.contest.detail
import cn.llonvne.compoent.submission.SubmitProblemResolver
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestId
import cn.llonvne.entity.problem.SubmissionVisibilityType
import cn.llonvne.site.contest.Display
import cn.llonvne.site.problem.detail.CodeEditorShower
import cn.llonvne.site.problem.detail.detail
import io.kvision.core.Container
import io.kvision.html.div
interface ContestProblemDisplay {
companion object {
fun from(
contestId: ContestId,
statusResolver: ContestStatusResolver
): ContestProblemDisplay = BaseContestProblemDisplay(contestId, statusResolver)
}
fun show(container: Container, index: Display.ProblemIndex)
}
private class BaseContestProblemDisplay(
private val contestId: ContestId,
private val statusResolver: ContestStatusResolver
) : ContestProblemDisplay {
override fun show(container: Container, index: Display.ProblemIndex) {
container.div {
detail(div { }, index.id) {
notShowProblem =
statusResolver.status() == Contest.ContestStatus.NotBegin
notShowProblemMessage = "比赛还未开始"
disableHistory = true
submitProblemResolver = SubmitProblemResolver(contestId = contestId)
codeEditorConfigurer = CodeEditorShower.CodeEditorConfigurer {
forceVisibility = SubmissionVisibilityType.Contest
submitProblemResolver = SubmitProblemResolver(contestId)
showSubmitPanel = statusResolver.status() == Contest.ContestStatus.Running
notShowSubmitPanelMessage = "比赛尚未开始或者已经结束"
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/detail/ContestProblemDisplay.kt | 2210546337 |
package cn.llonvne.site.contest.detail
interface ContestStatus {
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/detail/ContestStatus.kt | 773610069 |
package cn.llonvne.site.contest.detail
import cn.llonvne.compoent.AlertType
import cn.llonvne.entity.contest.Contest
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toInstant
import kotlin.js.Date
class ContestStatusResolver(private val startAt: LocalDateTime,private val endAt: LocalDateTime) {
fun status(): Contest.ContestStatus {
val instant = Instant.fromEpochMilliseconds(Date.now().toLong())
return if (instant < startAt.toInstant(TimeZone.currentSystemDefault())) {
Contest.ContestStatus.NotBegin
} else if (instant < endAt.toInstant(TimeZone.currentSystemDefault())) {
Contest.ContestStatus.Running
} else {
Contest.ContestStatus.Ended
}
}
fun statusColor(): AlertType {
return when (status()) {
Contest.ContestStatus.NotBegin -> AlertType.Info
Contest.ContestStatus.Running -> AlertType.Success
Contest.ContestStatus.Ended -> AlertType.Danger
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/detail/ContestStatusResolver.kt | 665984445 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.contest.Contest
import cn.llonvne.entity.contest.ContestContext
import cn.llonvne.kvision.service.*
import cn.llonvne.kvision.service.IContestService.AddProblemResp.AddOkResp
import cn.llonvne.kvision.service.ISubmissionService.ProblemNotFound
import cn.llonvne.message.Messager
import cn.llonvne.model.ContestModel
import cn.llonvne.model.RoutingModule
import io.kvision.core.Container
import io.kvision.core.onClickLaunch
import io.kvision.form.formPanel
import io.kvision.form.select.TomSelect
import io.kvision.form.text.RichText
import io.kvision.form.text.Text
import io.kvision.form.time.DateTime
import io.kvision.html.*
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import kotlin.js.Date
@Serializable
data class CreateContestForm(
val title: String,
val description: String = "",
@Contextual val startAt: Date,
@Contextual val endAt: Date,
val contestScoreTypeStr: String,
val rankTypeStr: String
)
@Serializable
private data class AddContestProblemForm(
val problemId: String
)
fun Container.createContest() {
alert(AlertType.Success) {
h1 {
+"创建你自己的比赛"
}
p {
+"在限定的时间内与别人一决高下吧"
}
}
observableOf(listOf<ContestContext.ContestProblem>()) {
div(className = "row") {
div(className = "col") {
alert(AlertType.Light) {
val form = formPanel<CreateContestForm> {
add(CreateContestForm::title, Text(label = "比赛标题"), required = true)
add(CreateContestForm::description, RichText(label = "描述"), required = true)
add(CreateContestForm::startAt, DateTime(label = "开始时间"), validator = { dateTime ->
val utc = dateTime.value?.getTime()
if (utc == null) {
false
} else {
utc > Date.now()
}
}, validatorMessage = { dateTime ->
"比赛开始时间必须晚于现在"
})
add(CreateContestForm::endAt, DateTime(label = "结束时间"), validator = { dateTime ->
val utc = dateTime.value?.getTime()
if (utc == null) {
false
} else {
utc > Date.now() && utc > form.getData().startAt.getTime()
}
}, validatorMessage = { dateTime -> "比赛开始时间必须晚于现在且晚于开始时间" })
add(
CreateContestForm::contestScoreTypeStr,
TomSelect(label = "记分方式", options = Contest.ContestScoreType.entries.map {
it.name to it.name
})
)
add(
CreateContestForm::rankTypeStr,
TomSelect(label = "排行显示", options = Contest.ContestRankType.entries.map {
it.name to it.name
})
)
button("提交", style = ButtonStyle.OUTLINESECONDARY) {
onClickLaunch {
if (!form.validate()) {
return@onClickLaunch
}
val data = form.getData()
val problems = getState()
if (problems.isNullOrEmpty()) {
return@onClickLaunch Messager.toastInfo("必须要有一道题目")
}
when (val resp = ContestModel.create(data, problems)) {
is IContestService.CreateContestResp.CreateOk -> {
Messager.toastInfo("创建比赛成功")
RoutingModule.routing.navigate("/contest/${resp.contest.contestId}")
}
is InternalError -> Messager.toastInfo(resp.reason)
PermissionDenied -> Messager.toastInfo("请先登入后在创建题目")
ProblemIdInvalid -> Messager.toastInfo("输入题目的ID无效")
}
}
}
getChildren().forEach {
it.addCssClass("small")
}
}
}
}
div(className = "col") {
alert(AlertType.Light) {
h4 {
+"选择题目"
}
val addProblemForm = formPanel<AddContestProblemForm> {
add(AddContestProblemForm::problemId, Text(label = "题目ID"), required = true)
}
setUpdater { listOf() }
sync(div { }) { problems ->
if (problems == null) {
+"<题目集为空>"
}
tabulator(
problems, options = TabulatorOptions(
columns = listOf(
defineColumn("题目ID") {
Span {
+it.problemId.toString()
}
},
defineColumn("题目名字") {
Span {
+it.alias
}
},
defineColumn("题目权重") {
Span {
+it.weight.toString()
}
}
), layout = Layout.FITCOLUMNS
)
)
}
button("添加", style = ButtonStyle.OUTLINESECONDARY) {
onClickLaunch {
when (val resp = ContestModel.addProblem(addProblemForm.getData().problemId)) {
is AddOkResp -> {
if (getState()?.none { it.problemId == resp.problemId } != false) {
setObv(
listOf(
ContestContext.ContestProblem(
problemId = resp.problemId,
weight = 1,
alias = resp.problemName
)
) + (getState() ?: listOf())
)
} else {
Messager.toastInfo("请勿添加重复的题目哦")
}
}
AddProblemPermissionDenied -> Messager.toastInfo("该题目设置了权限,您无法添加该题目到您的题集中")
is InternalError -> Messager.toastInfo(resp.reason)
PermissionDenied -> Messager.toastInfo("你需要先登入才能创建比赛")
ProblemIdInvalid -> Messager.toastInfo("您输入了无效的题目ID")
ProblemNotFound -> Messager.toastInfo("你输入的题目ID未被找到")
}
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/CreateContest.kt | 4149176108 |
package cn.llonvne.site.contest
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.html.h1
import io.kvision.html.h4
import io.kvision.html.p
fun Container.contest() {
alert(AlertType.Light) {
h1 {
+"比赛"
}
p {
+"加入或者创建比赛,在限定的时间与别人一决高下吧"
}
}
div(className = "row") {
div(className = "col") {
participantContestList(div { })
createContestEntry(div { })
}
div(className = "col") {
ContestNavigator.get().show(div { })
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/contest/Contest.kt | 3612745855 |
package cn.llonvne.site
import cn.llonvne.compoent.defineColumn
import cn.llonvne.compoent.observable.observableListOf
import cn.llonvne.dtos.SubmissionListDto
import cn.llonvne.model.SubmissionModel
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.html.Span
import io.kvision.html.div
import io.kvision.html.link
import io.kvision.html.span
import io.kvision.routing.Routing
import io.kvision.state.bind
import io.kvision.tabulator.ColumnDefinition
import io.kvision.tabulator.Layout
import io.kvision.tabulator.TabulatorOptions
import io.kvision.tabulator.tabulator
import io.kvision.utils.px
import kotlinx.serialization.serializer
fun Container.submission(routing: Routing) {
observableListOf {
setUpdater {
SubmissionModel.list().sortedByDescending {
it.submitTime
}
}
div(className = "p-1") { }.bind(this) { listDtos ->
tabulator<SubmissionListDto>(
listDtos,
options = TabulatorOptions(
layout = Layout.FITDATASTRETCH,
columns = listOf(
ColumnDefinition("提交ID", formatterComponentFunction = { _, _, e: SubmissionListDto ->
span {
+(e.submissionId.toString())
}
}),
ColumnDefinition("题目名字", formatterComponentFunction = { _, _, e ->
span {
+e.problemName
onClick {
routing.navigate("/problems/${e.problemId}")
}
}
}),
ColumnDefinition("状态", formatterComponentFunction = { _, _, e ->
span {
+e.status.readable
}
}),
defineColumn("评测结果") {
Span {
+it.passerResult.readable
}
},
ColumnDefinition("语言", formatterComponentFunction = { _, _, e ->
span {
+e.language.toString()
}
}),
ColumnDefinition("代码长度", formatterComponentFunction = { _, _, e ->
span {
+e.codeLength.toString()
}
}),
ColumnDefinition("作者", formatterComponentFunction = { _, _, e ->
span {
+e.user.username
}
}),
ColumnDefinition("提交时间", formatterComponentFunction = { _, _, e ->
div {
+"${e.submitTime.year}年${e.submitTime.monthNumber}月${e.submitTime.dayOfMonth}日${e.submitTime.hour}时${e.submitTime.minute}分${e.submitTime.second}秒"
}
}),
ColumnDefinition("", formatterComponentFunction = { _, _, e ->
link("详情", className = "p-1") {
onClick {
routing.navigate("/share/${e.codeId}")
}
}
}),
),
),
serializer = serializer()
) {
height = 400.px
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/Submission.kt | 1513579741 |
package cn.llonvne.site.share
import cn.llonvne.AppScope
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badge
import cn.llonvne.dtos.CodeDto
import cn.llonvne.dtos.CreateCommentDto
import cn.llonvne.dtos.getVisibilityDecr
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.ll
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.CodeModel
import cn.llonvne.site.share.visisbility.CodeCommentVisibilityTypeChanger
import io.kvision.core.Container
import io.kvision.core.TextAlign
import io.kvision.core.onClick
import io.kvision.core.style
import io.kvision.html.Align
import io.kvision.html.div
import io.kvision.html.h5
import io.kvision.html.span
import io.kvision.modal.Alert
import io.kvision.modal.Confirm
import io.kvision.state.bind
import kotlinx.coroutines.launch
interface CommentDisplay {
fun load(root: Container)
companion object {
fun empty() = object : CommentDisplay {
override fun load(root: Container) {}
}
fun public(
code: CodeDto, shareCodeCommentComponent: ShareCodeCommentComponent<CreateCommentDto>
): CommentDisplay = PublicShareCodeCommentDisplay(code, shareCodeCommentComponent)
fun freezing(
code: CodeDto, shareCodeCommentComponent: ShareCodeCommentComponent<CreateCommentDto>
): CommentDisplay {
return FreezingShareCodeCommentDisplay(code, shareCodeCommentComponent)
}
}
}
private class FreezingShareCodeCommentDisplay(
code: CodeDto, shareCodeCommentComponent: ShareCodeCommentComponent<CreateCommentDto>
) : PublicShareCodeCommentDisplay(code, shareCodeCommentComponent) {
override fun getDeleteComponent(root: Container, comment: CreateCommentDto) {
}
override fun getVisibilityChangerComponent(root: Container, comment: CreateCommentDto) {
root.badge(BadgeColor.Blue) {
+comment.getVisibilityDecr()
}
}
override fun getDeleteAllComponent(root: Container, commentIds: List<Int>) {
}
}
private open class PublicShareCodeCommentDisplay(
val code: CodeDto, val shareCodeCommentComponent: ShareCodeCommentComponent<CreateCommentDto>
) : CommentDisplay {
open fun getDeleteComponent(root: Container, comment: CreateCommentDto) {
AppScope.launch {
if (comment.committerUsername == AuthenticationModel.info()?.username || AuthenticationModel.info()?.id == code.shareUserId) {
root.badge(BadgeColor.Red) {
+"删除"
onClick {
deletePanel(
listOf(comment.commentId),
)
}
}
}
}
}
open fun getVisibilityChangerComponent(root: Container, comment: CreateCommentDto) {
root.badge(BadgeColor.Blue) {
+comment.getVisibilityDecr()
onClick {
AppScope.launch {
if (AuthenticationModel.info()?.id == code.shareUserId) {
CodeCommentVisibilityTypeChanger(code).change(comment.commentId)
}
}
}
}
}
open fun getDeleteAllComponent(root: Container, commentIds: List<Int>) {
root.badge(BadgeColor.Red) {
+"删除全部"
onClick {
deletePanel(commentIds)
}
}
}
override fun load(root: Container) {
root.div().bind(
shareCodeCommentComponent.getComments()
) { comments ->
comments.groupBy { dto ->
dto.committerUsername
}.forEach { (username, comments) ->
alert(AlertType.Dark) {
val commentIds = comments.map { it.commentId }
h5 {
+"$username 评论:"
}
comments.forEach { comment ->
span {
alert(AlertType.Light) {
div {
+comment.content
}
div {
getDeleteComponent(this, comment)
getVisibilityChangerComponent(this, comment)
addCssStyle(style {
textAlign = TextAlign.RIGHT
})
}
}
}
}
val lastUpdate = comments.map { it.createdAt }.maxOf { it }
badge(BadgeColor.Green) {
+"最后更新于 ${lastUpdate.ll()}"
}
getDeleteAllComponent(this, commentIds)
}
}
}
}
fun deletePanel(
commentIds: List<Int>,
) {
Confirm.show("你正在尝试删除评论",
"此操作将删除您的所有评论,请确认您的选择",
animation = true,
align = Align.LEFT,
yesTitle = "删除",
noTitle = "取消",
cancelVisible = false,
noCallback = {
Alert.show("删除结果", "你取消了删除")
},
yesCallback = {
AppScope.launch {
val result = CodeModel.deleteCommentByIds(commentIds)
if (result.isNotEmpty()) {
Alert.show("删除结果", "删除成功")
} else {
Alert.show("删除结果", "删除失败")
}
shareCodeCommentComponent.refreshComments()
}
})
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/CommentDisplay.kt | 383082936 |
package cn.llonvne.site.share
import cn.llonvne.compoent.NotFoundAble
import cn.llonvne.compoent.notFound
import cn.llonvne.compoent.observable.observableOf
import cn.llonvne.entity.problem.share.Code.CodeType.*
import cn.llonvne.kvision.service.ICodeService.GetCodeResp
import cn.llonvne.site.JudgeResultDisplay
import io.kvision.core.Container
import io.kvision.html.Div
import io.kvision.html.div
import kotlinx.coroutines.Deferred
import kotlinx.serialization.Serializable
interface ShareID {
data class IntId(val id: Int) : ShareID
data class HashId(val hash: String) : ShareID
}
fun Container.share(
hash: String,
codeLoader: CodeLoader<String>,
) {
val load = codeLoader.load(hash)
shareInternal(load, ShareID.HashId(hash))
}
fun Container.share(
shareId: Int,
codeLoader: CodeLoader<Int>,
) {
val load = codeLoader.load(shareId)
shareInternal(load, ShareID.IntId(shareId))
}
private fun Container.shareInternal(load: Deferred<GetCodeResp>, id: ShareID) {
observableOf<GetCodeResp?>(null) {
setUpdater { load.await() }
sync { resp ->
resp?.onSuccess { (code) ->
val highlighter = ShareCodeHighlighter.loadHighlighter(code, id, div { })
div(className = "row") {
div(className = "col") {
add(Div {
highlighter.load(this, code)
})
add(Div {
when (code.codeType) {
Share -> {}
Playground -> JudgeResultDisplay.playground(code.codeId, this)
Problem -> JudgeResultDisplay.problem(code.codeId, this)
}
})
}
div(className = "col") {
val shareCodeComment = ShareCodeCommentComponent.from(code.commentType, code)
shareCodeComment.loadComments(this)
}
}
}?.onFailure {
notFound(object : NotFoundAble {
override val header: String
get() = "未找到对应的代码分享/提交/训练场数据"
override val notice: String
get() = "有可能是该ID/Hash不存在,也可有可能是对方设置了权限"
override val errorCode: String
get() = "ShareNotFound-${id}"
})
}
}
}
}
@Serializable
data class CommentForm(val content: String?, val type: String)
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/ShareCode.kt | 926398976 |
package cn.llonvne.site.share
import cn.llonvne.AppScope
import cn.llonvne.kvision.service.ICodeService.GetCodeResp
import cn.llonvne.model.CodeModel
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
interface CodeLoader<ID> {
fun load(id: ID): Deferred<GetCodeResp>
companion object {
fun id() = object : CodeLoader<Int> {
override fun load(id: Int): Deferred<GetCodeResp> {
return AppScope.async {
CodeModel.getCode(id)
}
}
}
fun hash() = object : CodeLoader<String> {
override fun load(id: String): Deferred<GetCodeResp> {
return AppScope.async {
CodeModel.getCode(id)
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/CodeLoader.kt | 2251024097 |
package cn.llonvne.site.share
import cn.llonvne.AppScope
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.dtos.CodeDto
import cn.llonvne.dtos.CreateCommentDto
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.CodeCommentType.*
import cn.llonvne.kvision.service.CodeNotFound
import cn.llonvne.kvision.service.ICodeService.GetCommitsOnCodeResp.SuccessfulGetCommits
import cn.llonvne.message.Messager
import cn.llonvne.model.CodeModel
import io.kvision.core.Container
import io.kvision.html.h4
import io.kvision.state.ObservableListWrapper
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
/**
* 该接口负责管理评论
*/
interface ShareCodeCommentComponent<Comment> {
val shareId: Int
val comments: ObservableListWrapper<Comment>
fun loadComments(root: Container)
fun refreshComments(): Deferred<Boolean>
fun getComments(): ObservableListWrapper<Comment>
companion object {
fun from(status: CodeCommentType, code: CodeDto): ShareCodeCommentComponent<*> {
return when (status) {
Open -> public(code.codeId, code)
Closed -> empty("评论区已被代码所有者关闭")
ClosedByAdmin -> empty("评论区已被管理员关闭")
Protected -> protected(code.codeId, code)
Freezing -> freezing(code.codeId, code)
ContestCode -> empty("比赛提交评论区将自动关闭")
}
}
private fun empty(title: String) = object : ShareCodeCommentComponent<Nothing> {
override val shareId: Int = 0
override val comments: ObservableListWrapper<Nothing> = ObservableListWrapper()
override fun loadComments(root: Container) {
root.alert(AlertType.Secondary) {
h4 {
+title
}
}
}
override fun getComments(): ObservableListWrapper<Nothing> {
return comments
}
override fun refreshComments(): Deferred<Boolean> {
return AppScope.async { true }
}
}
private fun public(shareId: Int, code: CodeDto): ShareCodeCommentComponent<CreateCommentDto> =
PublicShareCommentComponent(shareId, code)
private fun protected(shareId: Int, code: CodeDto): ShareCodeCommentComponent<*> {
return ProtectedShareCommentComponent(shareId, code)
}
private fun freezing(shareId: Int, code: CodeDto): ShareCodeCommentComponent<*> {
return FreezingShareCommentCompoent(shareId, code)
}
}
}
private class FreezingShareCommentCompoent(
shareId: Int,
private val code: CodeDto,
comments: ObservableListWrapper<CreateCommentDto> = ObservableListWrapper()
) : PublicShareCommentComponent(shareId, code, comments) {
override fun loadComments(root: Container) {
AppScope.launch {
if (refreshComments().await()) {
CommentSubmitter.closed()
CommentDisplay.freezing(code, this@FreezingShareCommentCompoent).load(root)
}
}
}
}
private class ProtectedShareCommentComponent(
shareId: Int,
private val code: CodeDto,
comments: ObservableListWrapper<CreateCommentDto> = ObservableListWrapper()
) : PublicShareCommentComponent(shareId, code, comments) {
override fun loadComments(root: Container) {
AppScope.launch {
if (refreshComments().await()) {
CommentSubmitter.protected(shareId, code, this@ProtectedShareCommentComponent).load(root)
CommentDisplay.public(code, this@ProtectedShareCommentComponent).load(root)
}
}
}
}
private open class PublicShareCommentComponent(
override val shareId: Int,
private val code: CodeDto,
override val comments: ObservableListWrapper<CreateCommentDto> = ObservableListWrapper()
) : ShareCodeCommentComponent<CreateCommentDto> {
override fun refreshComments(): Deferred<Boolean> {
return AppScope.async {
when (val commentsResp = CodeModel.getCommentByCodeId(shareId)) {
CodeNotFound -> {
Messager.toastError("尝试获取评论失败")
false
}
is SuccessfulGetCommits -> {
Messager.toastInfo(commentsResp.commits.toString())
comments.clear()
comments.addAll(commentsResp.commits)
true
}
}
}
}
private fun loadUI(root: Container, submitter: CommentSubmitter, display: CommentDisplay) {
submitter.load(root)
display.load(root)
}
override fun loadComments(root: Container) {
AppScope.launch {
refreshComments().await()
}
loadUI(
root,
CommentSubmitter.public(shareId, this@PublicShareCommentComponent),
CommentDisplay.public(code, this@PublicShareCommentComponent)
)
}
override fun getComments(): ObservableListWrapper<CreateCommentDto> {
return comments
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/ShareCodeCommentComponent.kt | 131288019 |
package cn.llonvne.site.share
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.compoent.badge
import cn.llonvne.compoent.codeHighlighter
import cn.llonvne.dtos.CodeDto
import cn.llonvne.entity.problem.share.Code.CodeType.*
import cn.llonvne.entity.types.badge.BadgeColor
import cn.llonvne.message.Messager
import cn.llonvne.model.RoutingModule
import cn.llonvne.site.share.visisbility.CodeVisibilityChanger
import cn.llonvne.site.share.visisbility.CommentVisibilityChanger
import io.kvision.core.Container
import io.kvision.core.onClick
import io.kvision.html.Div
import io.kvision.html.h3
import io.kvision.html.h4
import io.kvision.html.p
interface ShareCodeHighlighter {
val idPlaceHolder: ShareID
val title: Div
val shareName: String
fun load(root: Container, codeDto: CodeDto) {
root.onSuccess(codeDto)
}
fun Container.slotOnTitle() {}
private fun onNotFound() {
title.alert(AlertType.Info) {
h4 {
+"未找到 ${[email protected]} 的${shareName}"
}
p {
+"可能是对方设置了权限,也可能是不存在该${shareName}"
}
}
Messager.toastError("未找到对应${shareName},可能是ID错误,或者是对方设置了查看权限")
}
private fun Container.onSuccess(
codeDto: CodeDto,
) {
title.alert(AlertType.Light) {
h3 {
+"${codeDto.shareUsername} 的${shareName}"
}
slotOnTitle()
badge(BadgeColor.Green) {
+codeDto.visibilityType.reprName
onClick {
CodeVisibilityChanger(codeDto).change()
}
}
badge(BadgeColor.Blue) {
+"语言 ${codeDto.language.toString()}"
}
badge(BadgeColor.Red) {
+codeDto.commentType.decr
onClick {
CommentVisibilityChanger(codeDto).change()
}
}
if (codeDto.hashLink != null) {
badge(BadgeColor.Golden) {
+"分享链接"
onClick {
RoutingModule.routing.navigate("/share/${codeDto.hashLink}")
}
}
}
}
codeHighlighter(code = codeDto.rawCode)
}
companion object {
private fun highlighterJsImpl(shareId: ShareID, alert: Div): ShareCodeHighlighter =
HighlighterJs(shareId, alert)
private fun playgroundHighlighterJsImpl(share: ShareID, alert: Div): ShareCodeHighlighter =
PlaygroundHighlighterJs(share, alert)
fun loadHighlighter(codeDto: CodeDto, shareId: ShareID, alert: Div): ShareCodeHighlighter =
when (codeDto.codeType) {
Share -> highlighterJsImpl(shareId = shareId, alert = alert)
Playground -> playgroundHighlighterJsImpl(shareId, alert)
Problem -> ProblemHighlighterJs(shareId, alert)
}
}
}
private class HighlighterJs(
override val idPlaceHolder: ShareID, override val title: Div, override val shareName: String = "分享",
) : ShareCodeHighlighter
private class PlaygroundHighlighterJs(
override val idPlaceHolder: ShareID, override val title: Div, override val shareName: String = "训练场"
) : ShareCodeHighlighter {
override fun Container.slotOnTitle() {
p {
+"训练场提交数据默认为私有,如果要与他人分享,请点击下方 <私有> 更改可见性"
}
}
}
private class ProblemHighlighterJs(
override val idPlaceHolder: ShareID, override val title: Div, override val shareName: String = "题解",
) : ShareCodeHighlighter | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/ShareCodeHighlighter.kt | 3428539984 |
package cn.llonvne.site.share.visisbility
import cn.llonvne.AppScope
import cn.llonvne.dtos.CodeDto
import cn.llonvne.entity.DescriptionGetter
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import io.kvision.core.Container
import io.kvision.html.ButtonStyle
import io.kvision.html.button
import io.kvision.html.p
import io.kvision.modal.Dialog
import io.kvision.toolbar.buttonGroup
import kotlinx.coroutines.launch
interface VisibilityChanger {
val codeDto: CodeDto
fun isCodeOwner(): Boolean {
val token = AuthenticationModel.userToken.value
if (token == null) {
Messager.toastError("你需要先验证你的身份才能更改代码可见性")
return false
}
if (token.id != codeDto.shareUserId) {
Messager.toastError("只有代码所有者才能更改代码可见性")
return false
}
return true
}
fun <T : DescriptionGetter> change(
dialogTitle: String,
choice: List<T>,
onEach: Container.(T) -> Unit = {},
slot: Container.() -> Unit = {},
selectionCallback: suspend (T) -> Unit
) {
val dialog = Dialog(dialogTitle) {
choice.forEach {
p {
+"${it.reprName}:${it.decr}"
}
onEach(it)
}
slot()
buttonGroup {
choice.forEach { c ->
button(c.reprName, style = ButtonStyle.OUTLINESECONDARY) {
onClick {
setResult(c)
}
}
}
}
}
AppScope.launch {
val result = dialog.getResult()
if (result != null) {
selectionCallback(result)
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/visisbility/VisibilityChanger.kt | 3453341503 |
package cn.llonvne.site.share.visisbility
import cn.llonvne.dtos.CodeDto
import cn.llonvne.entity.problem.ShareCodeComment
import cn.llonvne.kvision.service.CommentNotFound
import cn.llonvne.kvision.service.ICodeService.SetCodeCommentVisibilityTypeResp.SuccessSetCodeCommentVisibilityType
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.CodeModel
class CodeCommentVisibilityTypeChanger(override val codeDto: CodeDto) : VisibilityChanger {
fun change(commentId: Int) {
if (!isCodeOwner()) {
return
}
change("更改该评论的可见性", ShareCodeComment.Companion.ShareCodeCommentType.entries) { type ->
when (val resp = CodeModel.setCodeCommentVisibilityType(
shareId = codeDto.codeId, commentId = commentId, type
)) {
CommentNotFound -> return@change Messager.toastInfo("未找到该评论")
PermissionDenied -> return@change Messager.toastInfo("权限不足")
SuccessSetCodeCommentVisibilityType -> return@change Messager.toastInfo(
"修改成功"
)
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/visisbility/CodeCommentVisibilityTypeChanger.kt | 1086715307 |
package cn.llonvne.site.share.visisbility
import cn.llonvne.dtos.CodeDto
import cn.llonvne.entity.problem.share.CodeVisibilityType
import cn.llonvne.kvision.service.CodeNotFound
import cn.llonvne.kvision.service.ICodeService.SetCodeVisibilityResp.SuccessToPublicOrPrivate
import cn.llonvne.kvision.service.ICodeService.SetCodeVisibilityResp.SuccessToRestrict
import cn.llonvne.kvision.service.PermissionDenied
import cn.llonvne.message.Messager
import cn.llonvne.model.CodeModel
import io.kvision.html.p
class CodeVisibilityChanger(override val codeDto: CodeDto) : VisibilityChanger {
fun change() {
if (!isCodeOwner()) {
return
}
change("更改代码可见性",
choice = CodeVisibilityType.entries,
slot = {
if (codeDto.visibilityType == CodeVisibilityType.Restrict) {
p {
+"请注意你现在处于 ${codeDto.visibilityType.reprName} 模式中,一旦你更换到 公开/私密模式,将立刻使得目前的哈希链接失效,且不可恢复,如果你尝试再次切换到受限模式,将会生成一个新的哈希链接,并且使得旧的失效"
}
}
}
) { result ->
when (val resp = CodeModel.setCodeVisibility(codeDto.codeId, result)) {
CodeNotFound -> Messager.toastInfo("该分享代码不存在,或已被删除")
PermissionDenied -> Messager.toastInfo("你未登入,或者不是改代码所有者无法更改可见性")
SuccessToPublicOrPrivate -> Messager.toastInfo("成功更改代码可见性")
is SuccessToRestrict -> Messager.toastInfo("成功更改为受限类型,链接为${resp.link}")
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/visisbility/CodeVisibilityChanger.kt | 3534440805 |
package cn.llonvne.site.share.visisbility
import cn.llonvne.dtos.CodeDto
import cn.llonvne.entity.problem.share.CodeCommentType
import cn.llonvne.entity.problem.share.limited
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.CodeModel
class CommentVisibilityChanger(override val codeDto: CodeDto) : VisibilityChanger {
fun change() {
if (!isCodeOwner()) {
return
}
if (codeDto.commentType == CodeCommentType.ContestCode) {
return Messager.toastInfo("比赛代码不支持修改评论区权限")
}
val types = CodeCommentType.entries.limited(AuthenticationModel.userToken.value ?: return)
change("更改评论可见性", types) {
Messager.toastInfo(
CodeModel.setCodeCommentType(
shareId = codeDto.codeId,
type = it
).toString()
)
}
}
}
| OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/visisbility/CommentVisibilityChanger.kt | 3133632810 |
package cn.llonvne.site.share
import cn.llonvne.AppScope
import cn.llonvne.compoent.AlertType
import cn.llonvne.compoent.alert
import cn.llonvne.dtos.CodeDto
import cn.llonvne.dtos.CreateCommentDto
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType.Private
import cn.llonvne.entity.problem.ShareCodeComment.Companion.ShareCodeCommentType.Public
import cn.llonvne.message.Messager
import cn.llonvne.model.AuthenticationModel
import cn.llonvne.model.CodeModel
import io.kvision.core.Container
import io.kvision.form.formPanel
import io.kvision.form.select.TomSelect
import io.kvision.form.text.TextArea
import io.kvision.html.button
import io.kvision.html.h4
import io.kvision.html.p
import io.kvision.utils.px
import kotlinx.coroutines.launch
interface CommentSubmitter {
fun load(root: Container)
companion object {
fun public(shareId: Int, shareCommentComponent: ShareCodeCommentComponent<CreateCommentDto>): CommentSubmitter =
PublicCommentSubmitter(shareId, shareCommentComponent)
fun protected(
shareId: Int, code: CodeDto, shareCommentComponent: ShareCodeCommentComponent<CreateCommentDto>
): CommentSubmitter = ProtectedCommentSubmitter(shareId, shareCommentComponent, code)
fun closed(): CommentSubmitter = object : CommentSubmitter {
override fun load(root: Container) {
root.alert(AlertType.Dark) {
+"评论区已经被冻结"
}
}
}
}
}
private class ProtectedCommentSubmitter(
shareId: Int, shareCommentComponent: ShareCodeCommentComponent<CreateCommentDto>,
private val code: CodeDto
) : PublicCommentSubmitter(shareId, shareCommentComponent) {
override fun getCommentVisibilityOptions(): List<Pair<String, String>> {
return super.getCommentVisibilityOptions().filter {
if (AuthenticationModel.userToken.value?.id == null) {
return@filter false
}
if (code.shareUserId != AuthenticationModel.userToken.value?.id) {
it.first != PUBLIC_CODE
} else {
return@filter true
}
}
}
override fun notice(container: Container) {
container.p {
+"代码所有者已将该评论区设为保护状态,所有评论必须经过代码所有者审批才可以转换为公开状态"
}
}
}
private open class PublicCommentSubmitter(
private val shareId: Int,
private val shareCommentComponent: ShareCodeCommentComponent<CreateCommentDto>,
) : CommentSubmitter {
companion object {
const val PRIVATE_CODE = "1"
const val PUBLIC_CODE = "2"
}
protected open fun getCommentVisibilityOptions(): List<Pair<String, String>> {
return listOf(
PUBLIC_CODE to "对所有人可见", PRIVATE_CODE to "仅对你与代码所有者可见"
)
}
protected open fun notice(container: Container) {
}
protected open fun getCommentVisibilitySelect() = TomSelect(
label = "代码可见性",
options = getCommentVisibilityOptions(),
) {
addCssClass("col")
maxWidth = 300.px
}
override fun load(root: Container) {
root.alert(AlertType.Info) {
h4 {
+"留下你的友善评论"
}
p {
+"根据我们的反垃圾信息政策,在代码所有者回复你之前,你至多可以发送 5 条评论"
}
notice(this)
formPanel<CommentForm>(className = "row") {
"row gy-2 gx-3 align-items-center p-1".split(" ").forEach {
addCssClass(it)
}
add(
CommentForm::type,
getCommentVisibilitySelect(),
required = true,
requiredMessage = "必须选择一个代码可见性",
)
add(CommentForm::content, TextArea {
width = 600.px
})
button("提交") {
onClick {
if (AuthenticationModel.userToken.value == null) {
Messager.toastError("请先登入后发表评论")
return@onClick
}
AppScope.launch {
val username = AuthenticationModel.info()?.username ?: return@launch
if (shareCommentComponent.getComments().filter {
it.committerUsername == username
}.size >= 5) {
Messager.toastInfo("根据我们的反垃圾信息政策,在代码所有者回复你之前,你至多可以发送 5 条评论")
return@launch
}
val data = getData()
if (data.content == null) {
return@launch Messager.toastInfo("评论不可为空")
}
val type = when (data.type) {
PUBLIC_CODE -> Public
PRIVATE_CODE -> Private
else -> return@launch Messager.toastInfo("无效的可见性选择")
}
Messager.toastInfo(CodeModel.commit(shareId, data.content, type).toString())
shareCommentComponent.refreshComments()
}
}
}
}
}
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/site/share/CommentSubmitter.kt | 2002967656 |
package cn.llonvne
import cn.llonvne.compoent.layout.footer
import cn.llonvne.compoent.layout.header
import io.kvision.Application
import io.kvision.core.Container
import io.kvision.html.div
import io.kvision.panel.root
import io.kvision.routing.Routing
fun Application.layout(routing: Routing, build: Container.() -> Unit) {
root("kvapp") {
header(routing)
div(className = "px-4") {
build()
}
footer()
}
} | OnlineJudge/online-judge-web/src/jsMain/kotlin/cn/llonvne/Layout.kt | 860957247 |
package cn.llonvne.gojudge.api.router
class AbstractLanguageRouterTest {
} | OnlineJudge/go-judger/src/test/kotlin/cn/llonvne/gojudge/api/router/AbstractLanguageRouterTest.kt | 1433894040 |
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.test.Test
class TC {
sealed interface Result {
data class Running(val percent: Long) : Result
data object Finished : Result
}
@Test
fun a() = runBlocking {
suspendCoroutine<Unit> { continuation ->
println("start!")
continuation.resume(Unit)
}
println("end")
}
} | OnlineJudge/go-judger/src/test/kotlin/TC.kt | 1848178787 |
package cn.llonvne.gojudge
import cn.llonvne.gojudge.internal.GoJudgeClient
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.plugins.resources.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json
internal val judgeClient by lazy {
GoJudgeClient(HttpClient(OkHttp) {
engine {
}
install(Logging) {
}
install(Resources) {}
install(ContentNegotiation) {
json(Json {
isLenient = true
prettyPrint = true
})
}
defaultRequest {
port = 5050
host = "localhost"
}
})
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/JudgeClient.kt | 414709820 |
package cn.llonvne.gojudge.docker
import arrow.fx.coroutines.Resource
import cn.llonvne.gojudge.api.spec.bootstrap.GoJudgeEnvSpec
import org.testcontainers.containers.Container
class GoJudgeResolver(private val spec: GoJudgeEnvSpec) {
fun resolve(): Resource<CoroutineContainer> {
return configureGoJudgeContainer(spec = spec)
}
}
fun CoroutineContainer.toJudgeContext() = object : JudgeContext {
override suspend fun exec(command: String): Container.ExecResult {
return [email protected](command)
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/docker/GoJudgeResolver.kt | 4062950700 |
package cn.llonvne.gojudge.docker
import org.testcontainers.containers.Container.ExecResult
/**
* 在Docker虚拟机中执行代码
*
* PS:由于Docker为阻塞式API,所有像Docker的请求都会被切换到一个独立的线程,上层无需手动管理
*/
interface JudgeContext {
suspend fun exec(command: String): ExecResult
}
/**
* 将 [JudgeContext] 作为上下文接收器传入
*/
operator fun JudgeContext.invoke(operation: context(JudgeContext) () -> Unit) {
operation(this)
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/docker/JudgeContext.kt | 2809867240 |
package cn.llonvne.gojudge.docker
import arrow.fx.coroutines.Resource
import arrow.fx.coroutines.resource
import cn.llonvne.gojudge.api.spec.bootstrap.GoJudgeEnvSpec
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.withContext
import org.slf4j.LoggerFactory
import org.testcontainers.DockerClientFactory
import org.testcontainers.containers.Container
import org.testcontainers.containers.ExecInContainerPattern
import org.testcontainers.containers.GenericContainer
import org.testcontainers.utility.DockerImageName
import java.util.*
//"criyle/go-judge"
internal const val GO_JUDGE_DOCKER_NAME = "judger"
/**
* 判断当前是否为Liunx主机
*/
private val isLinux by lazy {
val dockerHost = System.getenv("DOCKER_HOST")
dockerHost != null && dockerHost.startsWith("unix://")
}
/**
* Docker Container 的协程包装器
*/
class CoroutineContainer(private val container: GenericContainer<*>) {
companion object {
/**
* 建立独立的线程为Docker协程服务
*/
@OptIn(ExperimentalCoroutinesApi::class, DelicateCoroutinesApi::class)
private val dockerCoroutinesContext = newSingleThreadContext("DockerThread")
}
/**
* 获得Docker客户端
*/
private val dockerClient = DockerClientFactory.lazyClient()
private suspend fun on(block: suspend (container: GenericContainer<*>) -> Unit) {
withContext(dockerCoroutinesContext) {
block(container)
}
}
internal suspend fun start() {
on {
container.start()
}
}
suspend fun close() {
on { container.close() }
}
suspend fun exec(command: String): Container.ExecResult {
return withContext(dockerCoroutinesContext) {
val result = ExecInContainerPattern
.execInContainer(dockerClient, container.containerInfo, "/bin/sh", "-c", command)
result
}
}
}
private val log = KotlinLogging.logger {}
fun configureGoJudgeContainer(
name: String = UUID.randomUUID().toString().substring(0..6),
isPrivilegedMode: Boolean = true,
reuseContainer: Boolean = false,
envs: MutableMap<String, String> = mutableMapOf(),
spec: GoJudgeEnvSpec = GoJudgeEnvSpec()
): Resource<CoroutineContainer> {
log.info { "building new docker client" }
envs["DEBIAN_FRONTEND"] = "noninteractive"
val container = GenericContainer(DockerImageName.parse(GO_JUDGE_DOCKER_NAME))
.withSharedMemorySize((256 * 1024 * 1024).toLong()) // 256 MB
.withPrivilegedMode(isPrivilegedMode)
.withReuse(reuseContainer)
.withCreateContainerCmdModifier { it.withName(name) }
.withEnv(envs)
applySpec(spec, container)
return resource({
CoroutineContainer(container).also {
it.start()
}
}) { wrapper, _ ->
wrapper.close()
}
}
fun shouldNotHappen(): Nothing =
throw IllegalStateException("it shouldn't be info please report me on Github:Llonvne/OnlineJudge")
fun applySpec(spec: GoJudgeEnvSpec, container: GenericContainer<*>) {
val portBindings = mutableListOf<String>()
val commands = mutableListOf<String>()
fun withCommand(command: String) = commands.add(command)
val logger = LoggerFactory.getLogger(GenericContainer::class.java)
// withCommand("-http-addr=${spec.httpAddr}")
logger.info("go-judge http endpoint on ${spec.httpAddr},port ${spec.httpAddr.port} is exposed")
portBindings.add("5050:5050")
if (spec.enableGrpc != GoJudgeEnvSpec.DEFAULT_ENABLE_GRPC) {
withCommand("-enable-grpc=${spec.enableGrpc}")
logger.info("go-judge grpc is active")
}
if (spec.grpcAddr != GoJudgeEnvSpec.DEFAULT_GRPC_ADDR) {
if (spec.enableGrpc) {
logger.error("you disable grpc service,and set a address,please check your setting")
}
withCommand("-grpc-addr=${spec.grpcAddr}")
logger.info("go-judge grpc endpoint on ${spec.grpcAddr},port ${spec.grpcAddr.port} is exposed")
portBindings.add("${spec.grpcAddr.port}:${spec.grpcAddr.port}")
}
if (!spec.logLevel.isDefault) {
when (spec.logLevel) {
GoJudgeEnvSpec.GoJudgeLogLevel.RELEASE -> withCommand("-release")
GoJudgeEnvSpec.GoJudgeLogLevel.SILENT -> withCommand("-silent")
GoJudgeEnvSpec.GoJudgeLogLevel.INFO -> shouldNotHappen()
}
}
when (spec.authToken) {
GoJudgeEnvSpec.GoJudgeAuthTokenSetting.Disabled -> Unit
is GoJudgeEnvSpec.GoJudgeAuthTokenSetting.Enable -> {
@Suppress("SMARTCAST_IMPOSSIBLE")
container.withCommand("-auth-token=${spec.authToken.token}")
}
}
if (spec.goDebugEndPoint != GoJudgeEnvSpec.DEFAULT_GO_DEBUG_ENDPOINT_ENABLE) {
withCommand("-enable-debug")
}
if (spec.prometheusMetrics != GoJudgeEnvSpec.DEFAULT_PROMETHEUS_METRICS_ENDPOINT_ENABLE) {
withCommand("-enable-metrics")
}
if (spec.goDebugAndPrometheusMetricsAddr != GoJudgeEnvSpec.DEFAULT_MONITOR_ADDR) {
withCommand("-monitor-addr=${spec.goDebugAndPrometheusMetricsAddr}")
logger.info("go-judge monitor endpoint on ${spec.goDebugAndPrometheusMetricsAddr},port ${spec.goDebugAndPrometheusMetricsAddr.port} is exposed")
if (!spec.prometheusMetrics && !spec.goDebugEndPoint) {
logger.error("go-judge: go debug and prometheus metrics is all disabled,but set a addr for it,please check you setting")
}
portBindings.add("${spec.goDebugAndPrometheusMetricsAddr.port}:${spec.goDebugAndPrometheusMetricsAddr.port}")
}
@Suppress("SMARTCAST_IMPOSSIBLE")
when (spec.concurrencyNumber) {
is GoJudgeEnvSpec.ConcurrencyNumberSetting.Customized -> withCommand("-parallelism=${spec.concurrencyNumber.number}")
GoJudgeEnvSpec.ConcurrencyNumberSetting.EqualCpuCore -> Unit
}
when (spec.fileStore) {
GoJudgeEnvSpec.FileStoreSetting.Dir -> withCommand("-dir")
GoJudgeEnvSpec.FileStoreSetting.Memory -> Unit
}
when (spec.cGroupPrefix) {
is GoJudgeEnvSpec.CGroupPrefixSetting.Customized -> withCommand("-cgroup-prefix=${spec.cGroupPrefix.prefix}")
GoJudgeEnvSpec.CGroupPrefixSetting.Default -> Unit
}
if (spec.srcPrefix.isNotEmpty()) {
withCommand("-src-prefix=${spec.srcPrefix.joinToString(",")}")
}
when (spec.timeLimitCheckerInterval) {
GoJudgeEnvSpec.GoJudgeTimeInterval.Default -> Unit
is GoJudgeEnvSpec.GoJudgeTimeInterval.Ms -> withCommand("-time-limit-checker-interval=${spec.timeLimitCheckerInterval.time}")
is GoJudgeEnvSpec.GoJudgeTimeInterval.Second -> withCommand("-time-limit-checker-interval=${spec.timeLimitCheckerInterval.time}")
}
when (spec.outputLimit) {
is GoJudgeEnvSpec.OutputLimitSetting.Customize -> withCommand("-output-limit=${spec.outputLimit.byte} b")
GoJudgeEnvSpec.OutputLimitSetting.Default -> Unit
}
when (spec.extraMemoryLimit) {
is GoJudgeEnvSpec.ExtraMemoryLimitSetting.Customized -> withCommand("-extra-memory-limit=${spec.extraMemoryLimit.byte} b")
GoJudgeEnvSpec.ExtraMemoryLimitSetting.Default -> Unit
}
when (spec.copyOutLimit) {
is GoJudgeEnvSpec.CopyOutLimitSetting.Customized -> withCommand("-copy-out-limit=${spec.copyOutLimit.byte} b")
GoJudgeEnvSpec.CopyOutLimitSetting.Default -> Unit
}
when (spec.openFileLimit) {
GoJudgeEnvSpec.OpenFileLimitSetting.Default -> Unit
is GoJudgeEnvSpec.OpenFileLimitSetting.Customized -> withCommand("-open-file-limit=${spec.openFileLimit.limit}")
}
@Suppress("SMARTCAST_IMPOSSIBLE")
when (spec.linuxOnlySpec) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec -> {
if (!isLinux) {
logger.error("You are not in a liunx platform but set some liunx setting,we will apply this setting,but may not valid")
}
val linuxSpec = spec.linuxOnlySpec as GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec
when (linuxSpec.cpuSets) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.CpuSetting.Customized -> withCommand("-cpuset=${(linuxSpec.cpuSets as GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.CpuSetting.Customized).settings}")
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.CpuSetting.Default -> Unit
}
when (linuxSpec.containerCredStart) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.ContainerCredStartSetting.Customized -> withCommand("-container-cred-start=${linuxSpec.containerCredStart.start}")
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.ContainerCredStartSetting.Default -> Unit
}
when (linuxSpec.enableCpuRate) {
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.CpuRateSetting.Disable -> Unit
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.CpuRateSetting.Enable -> withCommand("-enable-cpu-rate=true")
}
when (linuxSpec.seccompConf) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.SeccompConfSetting.Customized -> withCommand("-seccomp-conf=${(linuxSpec.seccompConf as GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.SeccompConfSetting.Customized).settings}")
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.SeccompConfSetting.Disable -> Unit
}
when (linuxSpec.tmpFsParam) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.TmsFsParamSetting.Customized -> withCommand("-tmp-fs-param=${(linuxSpec.tmpFsParam as GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.TmsFsParamSetting.Customized).command}")
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.TmsFsParamSetting.Default -> Unit
}
when (linuxSpec.mountConf) {
is GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.MountConfSetting.Customized -> withCommand("-mount-conf=${(linuxSpec.mountConf as GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.MountConfSetting.Customized).settings}")
GoJudgeEnvSpec.LinuxOnlySpec.LinuxPlatformSpec.MountConfSetting.Default -> Unit
}
}
GoJudgeEnvSpec.LinuxOnlySpec.NotLinuxPlatform -> {
Unit
}
}
when (spec.preFork) {
is GoJudgeEnvSpec.PreForkSetting.Customized -> withCommand("-pre-fork=${(spec.preFork as GoJudgeEnvSpec.PreForkSetting.Customized).instance}")
GoJudgeEnvSpec.PreForkSetting.Default -> Unit
}
when (spec.fileTimeout) {
GoJudgeEnvSpec.FileTimeoutSetting.Disabled -> Unit
is GoJudgeEnvSpec.FileTimeoutSetting.Timeout -> withCommand("-file-timeout=${(spec.fileTimeout as GoJudgeEnvSpec.FileTimeoutSetting.Timeout).seconds}")
}
container.withCommand(*commands.toTypedArray())
container.portBindings = portBindings
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/docker/GoJudgeContainer.kt | 3301883308 |
package cn.llonvne.gojudge.app
import cn.llonvne.gojudge.api.JudgeServerInfo
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.api.router.gpp.gpp
import cn.llonvne.gojudge.api.router.install
import cn.llonvne.gojudge.api.router.installLanguageRouter
import cn.llonvne.gojudge.api.router.java.java
import cn.llonvne.gojudge.api.router.kotlin.kotlin
import cn.llonvne.gojudge.api.router.python3.python3
import cn.llonvne.gojudge.api.task.gpp.CppVersion
import cn.llonvne.gojudge.docker.JudgeContext
import cn.llonvne.gojudge.docker.invoke
import cn.llonvne.gojudge.internal.config
import cn.llonvne.gojudge.judgeClient
import cn.llonvne.gojudge.ktor.installKtorOfficialPlugins
import cn.llonvne.gojudge.web.links.LinkTreeConfigurer
import cn.llonvne.gojudge.web.links.get
import cn.llonvne.gojudge.web.links.linkTr
import cn.llonvne.gojudge.web.links.linkTrUri
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.lang.management.ManagementFactory
import java.net.InetAddress
context(JudgeContext, LinkTreeConfigurer, Routing)
fun installAllGpp() {
SupportLanguages.entries
.filter {
it.name.startsWith("Cpp")
}
.forEach { supportLanguage ->
with(supportLanguage) {
installLanguageRouter(
languageName + languageVersion, "/$path", decr = "",
gpp(CppVersion.valueOf("Cpp$languageVersion"))
)
}
}
}
private val runtime = Runtime.getRuntime()
/**
* @param judgeContext 评测机运行时
*/
fun Application.judging(judgeContext: JudgeContext, port: Int) {
installKtorOfficialPlugins()
routing {
get("/info") {
call.respond(
JudgeServerInfo(
name = "judge", // TODO JudgeName
cpuCoresCount = runtime.availableProcessors(),
cpuUsage = ManagementFactory.getOperatingSystemMXBean().systemLoadAverage,
host = InetAddress.getLocalHost().hostAddress,
port = port.toString(),
isOnline = true,
memoryUsage = runtime.totalMemory().toInt() - runtime.freeMemory().toInt()
)
)
}
linkTrUri("/link") {
get { call.respondRedirect(linkTreeUri) }
linkTr {
judgeContext {
installAllGpp()
install(SupportLanguages.Java, java())
install(SupportLanguages.Python3, python3())
install(SupportLanguages.Kotlin, kotlin())
get("config", "config") {
call.respondText(judgeClient.config(), ContentType.Application.Json)
}
}
}
}
}
}
| OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/app/Jugder.kt | 1124003661 |
package cn.llonvne.gojudge.web.links
import io.ktor.server.application.*
import io.ktor.server.html.*
import io.ktor.server.routing.*
import kotlinx.html.*
/**
* @property name 链接的名称
* @property decr 链接的描述
* @property uri 链接的地址
* @property render 自定义渲染函数,可选
*/
internal data class LinkEntity(val name: String, val decr: String, val uri: String, val render: A.() -> Unit = {})
/**
* 链接树描述器
*/
internal interface LinkTreeConfigurer {
/**
* 添加一个链接目标
*/
fun link(linkEntity: LinkEntity)
/**
* 获取所有链接
*/
fun getLink(): List<LinkEntity>
/**
* 调整样式
*/
fun name(): H1.() -> Unit = {}
/**
* 调整样式
*/
fun decr(): H4.() -> Unit = {}
/**
* 调整样式
*/
fun link(): A.() -> Unit = {}
}
context(LinkTreeAware)
internal fun Route.linkTr(
name: String = "Links",
decr: String = "LinkTree",
configurer: LinkTreeConfigurer = LinkTreeConfigurerImpl(),
build: LinkTreeConfigurer.() -> Unit,
) {
linkTr(linkTreeUri, name, decr, configurer, build)
}
/**
* @param url 链接树的地址
* @param decr 链接树的描述
* @param build 构建链接树的函数
* @param configurer 允许用户自定义存储类型,默认使用 list
*
* 在 [url] 建立一颗链接树,以[build]描述
*/
internal fun Route.linkTr(
url: String,
name: String = "Links",
decr: String = "LinkTree",
configurer: LinkTreeConfigurer = LinkTreeConfigurerImpl(),
build: LinkTreeConfigurer.() -> Unit,
) {
configurer.build()
get(url) {
call.respondHtml {
body {
h1 {
+name
configurer.name().invoke(this)
}
h4 {
+decr
configurer.decr().invoke(this)
}
configurer.getLink().forEach { link ->
div {
a {
href = link.uri
+link.name
configurer.link().invoke(this)
link.render.invoke(this)
}
}
}
}
}
}
}
private class LinkTreeConfigurerImpl : LinkTreeConfigurer {
private val links = mutableListOf<LinkEntity>()
override fun link(linkEntity: LinkEntity) {
links.add(linkEntity)
}
override fun getLink(): List<LinkEntity> = links
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/web/links/LinkTr.kt | 2165048988 |
package cn.llonvne.gojudge.web.links
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.util.pipeline.*
import kotlinx.html.A
internal fun LinkTreeConfigurer.linkIn(name: String, decr: String, url: String, render: A.() -> Unit = {}) = link(
LinkEntity(name, decr, url, render)
)
context(LinkTreeConfigurer)
internal fun Route.get(
path: String,
decr: String,
render: A.() -> Unit = {},
body: PipelineInterceptor<Unit, ApplicationCall>
) {
linkIn(path, decr, this.toString() + path, render)
get(path, body)
}
context(LinkTreeConfigurer)
internal fun Route.post(
path: String,
decr: String,
render: A.() -> Unit = {},
body: PipelineInterceptor<Unit, ApplicationCall>
) {
linkIn(path, decr, this.toString() + path, render)
post(path, body)
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/web/links/LinkTrExts.kt | 2301614881 |
package cn.llonvne.gojudge.web.links
interface LinkTreeAware {
val linkTreeUri: String
}
private data class LinkTreeAwareImpl(override val linkTreeUri: String) : LinkTreeAware
/**
* 预先定义 LinkTree 的地址
* 可以使用 [linkTr] 函数来获取内部的定义的 uri
*/
fun linkTrUri(uri: String, context: context(LinkTreeAware) () -> Unit) {
val impl = LinkTreeAwareImpl(uri)
context(impl)
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/web/links/LinkTreeAware.kt | 3492706483 |
package cn.llonvne.gojudge.env
import arrow.core.Either
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import arrow.core.raise.either
import cn.llonvne.gojudge.api.spec.bootstrap.*
import com.github.dockerjava.zerodep.shaded.org.apache.hc.core5.net.InetAddressUtils
import io.github.cdimascio.dotenv.Dotenv
import io.github.oshai.kotlinlogging.KotlinLogging
import java.math.BigInteger
import java.security.SecureRandom
private const val ENABLE_JUDGE_KEY = "JUDGE"
private const val ENABLE_JUDGE_TOKEN_AUTH = "JUDGE_AUTH_KEY_ENABLE"
private const val JUDGE_TOKEN = "JUDGE_AUTH_KEY"
private const val SECURE_TOKEN_LENGTH = 32
private const val GO_JUDGE_IP = "JUDGE_IP"
private const val GO_JUDGE_PORT = "JUDGE_PORT"
internal data class EnvConfig(val rawEnv: Dotenv, val judgeSpec: Option<GoJudgeEnvSpec>)
internal class TokenIsTooWeak(value: String) : Exception(value)
@JvmInline
value class Token(val token: String)
private val log = KotlinLogging.logger {}
private fun generateSecureKey(length: Int): String {
val secureRandom = SecureRandom()
val randomBytes = ByteArray(length)
secureRandom.nextBytes(randomBytes)
return BigInteger(1, randomBytes).toString(16)
}
internal fun loadConfigFromEnv(): EnvConfig {
log.info { "loading envs from system ..." }
val env = Dotenv.load()
val spec = env.loadJudgeConfig()
return EnvConfig(env, spec)
}
private fun Dotenv.loadJudgeConfig(): Option<GoJudgeEnvSpec> {
var spec = GoJudgeEnvSpec()
ifNull(this.get(ENABLE_JUDGE_KEY, "false").toBooleanStrictOrNull()) {
log.error { "go-judge is disabled,please confirm your setting!" }
return None
}
setToken(spec)
ifNotNull(this.get(GO_JUDGE_IP)) { ipStr ->
require(isValidIP(ipStr)) { "$ipStr is not a valid ip" }
spec = GoJudgeEnvSpec.httpAddr.url.modify(spec) { ipStr }
}
ifNotNull(this.get(GO_JUDGE_PORT)) { portStr ->
val port = portStr.toIntOrNull()
require(port != null && isValidPort(port)) {
"$portStr is not valid port"
}
spec = GoJudgeEnvSpec.httpAddr.port.modify(spec) {
port
}
}
return Some(spec)
}
private fun Dotenv.isEnableJudgeAuthToken(): Boolean {
return this.get(ENABLE_JUDGE_TOKEN_AUTH, "false").toBooleanStrictOrNull() ?: false
}
private fun Dotenv.getToken() = either {
val token = [email protected](JUDGE_TOKEN, generateSecureKey(SECURE_TOKEN_LENGTH * 2))
if (token.length < SECURE_TOKEN_LENGTH) {
log.error { "token is too weak" }
raise("token is too weak")
}
Token(token)
}
private fun Dotenv.setToken(spec: GoJudgeEnvSpec) {
val enableToken = isEnableJudgeAuthToken()
if (enableToken) {
val token = when (val token = getToken()) {
is Either.Left -> throw TokenIsTooWeak(token.value)
is Either.Right -> token.value
}
log.info { "judge token is ${token.token}" }
GoJudgeEnvSpec.authToken.modify(spec) {
GoJudgeEnvSpec.GoJudgeAuthTokenSetting.Enable(token.token)
}
}
}
private fun isValidIP(ip: String): Boolean {
return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv4Address(ip)
}
private inline fun <reified T> ifNotNull(value: T?, then: (T) -> Unit) {
if (value != null) {
then(value)
}
}
private inline fun <reified T> ifNull(value: T?, then: () -> Unit) {
if (value == null) {
then()
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/env/Env.kt | 3915155310 |
package cn.llonvne.gojudge.api.router.python3
import cn.llonvne.gojudge.api.router.LanguageRouter
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.python.python3CompileTask
import cn.llonvne.gojudge.docker.JudgeContext
import cn.llonvne.gojudge.judgeClient
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
context(JudgeContext)
internal fun python3() = object : LanguageRouter {
val pythonCompileTask = python3CompileTask()
context(PipelineContext<Unit, ApplicationCall>) override suspend fun version() {
call.respondText(exec("python3 --version").stderr, contentType = ContentType.Application.Json)
}
context(PipelineContext<Unit, ApplicationCall>) override suspend fun judge(code: String, stdin: String) {
val result = pythonCompileTask.run(CodeInput(code, stdin), judgeClient)
call.respond(result)
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/python3/Python3Router.kt | 2391153426 |
package cn.llonvne.gojudge.api.router.java
import cn.llonvne.gojudge.api.router.LanguageRouter
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.java.javaCompileTask
import cn.llonvne.gojudge.docker.JudgeContext
import cn.llonvne.gojudge.judgeClient
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
context(JudgeContext)
internal fun java() = object : LanguageRouter {
val javaCompileTask = javaCompileTask()
context(PipelineContext<Unit, ApplicationCall>) override suspend fun version() {
val version = exec("java -version").stderr
call.respondText(version, contentType = ContentType.Application.Json)
}
context(PipelineContext<Unit, ApplicationCall>) override suspend fun judge(code: String, stdin: String) {
val result = javaCompileTask.run(CodeInput(code, stdin), judgeClient)
call.respond(result)
}
}
| OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/java/JavaRouter.kt | 3871816093 |
package cn.llonvne.gojudge.api.router.kotlin
import cn.llonvne.gojudge.api.router.LanguageRouter
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.kotlin.kotlinCompileTask
import cn.llonvne.gojudge.docker.JudgeContext
import cn.llonvne.gojudge.judgeClient
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
context(JudgeContext)
internal fun kotlin() = object : LanguageRouter {
val kotlinCompileTask = kotlinCompileTask()
context(PipelineContext<Unit, ApplicationCall>) override suspend fun version() {
call.respondText(exec("kotlinc -version").stderr, ContentType.Application.Json)
}
context(PipelineContext<Unit, ApplicationCall>) override suspend fun judge(code: String, stdin: String) {
call.respond(kotlinCompileTask.run(CodeInput(code, stdin), judgeClient))
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/kotlin/KotlinRouter.kt | 3843934015 |
package cn.llonvne.gojudge.api.router
import cn.llonvne.gojudge.api.SupportLanguages
import cn.llonvne.gojudge.web.links.LinkTreeConfigurer
import cn.llonvne.gojudge.web.links.get
import cn.llonvne.gojudge.web.links.linkIn
import cn.llonvne.gojudge.web.links.linkTr
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.html.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.pipeline.*
import kotlinx.html.body
context(Routing)
internal fun LinkTreeConfigurer.install(supportLanguages: SupportLanguages, languageRouter: LanguageRouter) {
installLanguageRouter(
supportLanguages.name,
path = "/${supportLanguages.path}",
decr = supportLanguages.name + supportLanguages.languageVersion,
languageRouter
)
}
context(Routing)
internal fun LinkTreeConfigurer.installLanguageRouter(
name: String,
path: String,
decr: String = name,
languageRouter: LanguageRouter
) {
linkIn(name, decr, "$path/link")
LanguageRouterLoader(name, path, languageRouter, decr = decr)
}
/**
* 定义了语言服务的标准接口
*/
internal interface LanguageRouter {
/**
* [version] 返回语言编译器/执行器的版本信息,默认使用 Application/Json
*/
context(PipelineContext<Unit, ApplicationCall>)
suspend fun version()
/**
* [judge] 传入代码,开始评测语言
*/
context(PipelineContext<Unit, ApplicationCall>)
suspend fun judge(code: String, stdin: String)
context(PipelineContext<Unit, ApplicationCall>)
suspend fun playground(languageName: String, judgePath: String) {
call.respondHtml {
body {
this.playground(languageName, judgePath)
}
}
}
}
context(Route)
private class LanguageRouterLoader(
private val name: String, private val path: String,
private val languageRouter: LanguageRouter, private val decr: String = name
) {
private val logger = KotlinLogging.logger("LanguageRouter")
init {
route(path) {
linkTr(
url = "/link",
name = name,
decr = decr,
) {
get("/version", "version") {
languageRouter.version()
}
post {
val code = call.receiveParameters()["code"]
?: return@post call.respond(HttpStatusCode.BadRequest, "代码为空")
val stdin = call.receiveParameters()["stdin"]
?: return@post call.respond(HttpStatusCode.BadRequest, "输入为空")
logger.info {
"$name 评测代码 $code,标准输入为 $stdin"
}
languageRouter.judge(code, stdin)
}
get("/playground", "Playground") {
languageRouter.playground(name, path)
}
}
}
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/LanguageRouter.kt | 3863006586 |
package cn.llonvne.gojudge.api.router
import kotlinx.html.*
internal fun BODY.playground(languageName: String, judgePath: String = languageName) {
h1 {
+"$languageName Playground"
}
form {
method = FormMethod.post
action = judgePath
label {
htmlFor = "code"
+"Your Code here"
}
br { }
textArea {
id = "code"
required = true
cols = "30"
rows = "10"
name = "code"
}
br {}
label {
htmlFor = "stdin"
+"Your stdin here"
}
br { }
textArea {
id = "stdin"
required = false
name = "stdin"
cols = "30"
rows = "10"
}
input {
type = InputType.submit
value = "Submit"
}
}
}
| OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/Playground.kt | 3127937545 |
package cn.llonvne.gojudge.api.router.gpp
import cn.llonvne.gojudge.api.router.LanguageRouter
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.gpp.CppVersion
import cn.llonvne.gojudge.api.task.gpp.gppCompileTask
import cn.llonvne.gojudge.docker.JudgeContext
import cn.llonvne.gojudge.judgeClient
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.util.pipeline.*
context(JudgeContext)
internal fun gpp(cppVersion: CppVersion) = object : LanguageRouter {
val gppCompileTask = gppCompileTask(cppVersion)
context(PipelineContext<Unit, ApplicationCall>)
override suspend fun version() {
val version = exec("g++ -v")
call.respondText(version.stderr, contentType = ContentType.Application.Json)
}
context(PipelineContext<Unit, ApplicationCall>)
override suspend fun judge(code: String, stdin: String) {
val result = gppCompileTask.run(CodeInput(code, stdin), judgeClient)
call.respond(result)
}
}
| OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/api/router/gpp/GppRouter.kt | 2164507795 |
package cn.llonvne.gojudge.ktor
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.routing.*
const val GLOBAL_AUTHENTICATION = "auth-bearer"
fun Route.globalAuth(build: Route.() -> Unit) =
authenticate(GLOBAL_AUTHENTICATION, build = build)
fun Application.installAuthentication() {
authentication {
bearer(GLOBAL_AUTHENTICATION) {
realm = "Access to the '/' path"
skipWhen {
it.request.queryParameters["dev"] == "true"
}
authenticate { tokenCredential ->
if (tokenCredential.token == "abc123") {
return@authenticate UserIdPrincipal("jetbrains")
}
null
}
}
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/Authentication.kt | 4001356982 |
package cn.llonvne.gojudge.ktor
import io.ktor.server.application.*
import io.ktor.server.metrics.micrometer.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Application.installMicrometer() {
val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
install(MicrometerMetrics) {
registry = appMicrometerRegistry
}
routing {
globalAuth {
get("/health") {
call.respondText(appMicrometerRegistry.scrape())
}
}
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/Micrometer.kt | 3666025990 |
package cn.llonvne.gojudge.ktor
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.cors.routing.*
fun Application.installCORS() {
install(CORS){
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Delete)
allowMethod(HttpMethod.Patch)
allowHeader(HttpHeaders.Authorization)
allowCredentials = true
anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/CORS.kt | 2985930427 |
package cn.llonvne.gojudge.ktor
import cn.llonvne.gojudge.docker.shouldNotHappen
import de.jensklingenberg.ktorfit.http.*
import io.github.oshai.kotlinlogging.KLogger
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.util.*
import io.ktor.util.reflect.*
import kotlinx.coroutines.launch
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.full.callSuspend
import kotlin.reflect.full.functions
import kotlin.reflect.full.superclasses
private annotation class KtorfitRouterService
private class KtorfitRouterConfig {
var services: List<Any> = listOf<Any>()
}
private val KtorfitRouter = createApplicationPlugin("KtorfitRouter", ::KtorfitRouterConfig) {
val log = KotlinLogging.logger { }
application.environment.monitor.subscribe(ApplicationStarted) {
pluginConfig.services.forEach { service ->
// IMPL CLASS
val implCls = service::class
// IMPL METHOD
val implMethods = implCls.functions.filterUserDefinedMethod()
log.info { "process on ${implCls.simpleName}" }
// ABSTRACT CLASS METHODS
val abstractMethods = getSatisfiedMethodFromAbstract(getAnnotatedInterface(implCls), log)
log.info { "find satisfied methods: ${abstractMethods.map { it.name }}" }
// HTTP METHOD DESCR
val httpMethodDescriptors = abstractMethods.map { method ->
// filter Ktorfit Http Annotation
val httpMethodUrls = method.annotations.filterKtorfitAnnotations().map { parseAnnotation(it) }
HttpMethodDescriptor(method, httpMethodUrls)
}
// ROUTE
val routing = it.pluginRegistry[AttributeKey("Routing")] as Routing
// FOR EACH DESCR
httpMethodDescriptors.forEach { descriptor ->
// FOR EACH (PATH,METHOD)
descriptor.httpMethodUrls.forEach { (path, method) ->
// FIND TARGET METHOD
val targetMethod = findMethod(implMethods, descriptor)
// PARSE METHOD PACK
val methodArgTypes = parseMethodArgTypes(targetMethod, service)
// GENERATE A ROUTE FOR PATH
val curRoute = routing.createRouteFromPath(path)
// APPLY METHOD TO ROUTE
curRoute.method(method) {
handle {
launch {
// CALL
val args = methodArgTypes.map {
if (it.kotlinType?.isMarkedNullable == true) {
call.receiveNullable<Any>(it)
} else {
call.receive(it)
}
}
call.respond(targetMethod.callSuspend(service, *args.toTypedArray()) as Any)
}
}
}
}
}
}
}
}
private enum class ParameterType {
Body, FormData, Header, HeadersMap, Tag, RequestBuilder
}
private data class TypeInfoPack(val typeInfo: TypeInfo)
private fun parseMethodArgTypes(targetMethod: KFunction<*>, service: Any): List<TypeInfo> {
return targetMethod.parameters.map {
TypeInfo(it.type.classifier as KClass<*>, it.type.platformType, it.type)
}.filter {
it.type != service::class
}
}
private fun getAnnotatedInterface(implCls: KClass<out Any>): KClass<*> {
val abstracts = implCls.superclasses.filter {
it.annotations.any { annotation ->
annotation.annotationClass.qualifiedName == KtorfitRouterService::class.qualifiedName
}
}.toList()
val abstract = if (abstracts.size != 1) {
throw IllegalStateException("it should has only one interface annotated with KtorfitRouterService,now is ${abstracts.size}")
} else {
abstracts[0]
}
return abstract
}
private fun getSatisfiedMethodFromAbstract(
cls: KClass<*>, log: KLogger
) = cls.functions
// excludes equals hashCode toString functions
.filter {
it.name !in setOf("equals", "hashCode", "toString")
}
// excludes not suspend function functions
.filter {
if (!it.isSuspend) {
log.error { "find ${it.name} function is not suspend..., not suspend function is not support by Ktor" }
}
it.isSuspend
}
// excludes not annotated with Ktorfit Annotations
.filter {
isAnnotatedByKtorfit(it).also { result ->
if (!result) {
log.error {
"""${it.name} function is not annotated with any Ktorfit anntotaions and it's not abstract,please check your code
|if you have install Ktorfit correct,you might not to see this error,becase Ktorfit will prevent you to compile
|this code,please check your Ktorfit installation,or maybe any functions in this interface are not annotated with Ktorfit annotations
""".trimMargin()
}
}
}
}.toList()
private val ktorfitAnnotationsFqNameSet by lazy {
listOf(GET::class, POST::class, PUT::class, DELETE::class, HEAD::class, OPTIONS::class, PATCH::class).mapNotNull {
it.qualifiedName
}.toSet()
}
private fun isAnnotatedByKtorfit(kFunction: KFunction<*>) = kFunction.annotations.filterKtorfitAnnotations().any()
private fun Collection<Annotation>.filterKtorfitAnnotations() =
filter { it.annotationClass.qualifiedName in ktorfitAnnotationsFqNameSet }
private data class HttpMethodUrl(val url: String, val method: HttpMethod)
private data class HttpMethodDescriptor(val method: KFunction<*>, val httpMethodUrls: List<HttpMethodUrl>)
private fun parseAnnotation(annotation: Annotation): HttpMethodUrl {
return when (annotation) {
is GET -> HttpMethodUrl(annotation.value, HttpMethod.Get)
is POST -> HttpMethodUrl(annotation.value, HttpMethod.Post)
is PUT -> HttpMethodUrl(annotation.value, HttpMethod.Put)
is DELETE -> HttpMethodUrl(annotation.value, HttpMethod.Delete)
is HEAD -> HttpMethodUrl(annotation.value, HttpMethod.Head)
is OPTIONS -> HttpMethodUrl(annotation.value, HttpMethod.Options)
is PATCH -> HttpMethodUrl(annotation.value, HttpMethod.Patch)
else -> shouldNotHappen()
}
}
private fun Collection<KFunction<*>>.filterUserDefinedMethod() = filter {
it.name !in setOf("equals", "hashCode", "toString")
}
private fun findMethod(
implMethods: List<KFunction<*>>, httpMethodDescriptor: HttpMethodDescriptor
) = checkNotNull(implMethods.find { it.name == httpMethodDescriptor.method.name })
| OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/KtorfitRouter.kt | 2907855386 |
package cn.llonvne.gojudge.ktor
import cn.llonvne.gojudge.api.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.html.*
import io.ktor.server.plugins.statuspages.*
import kotlinx.html.body
import kotlinx.html.h1
import kotlinx.html.h4
import kotlinx.html.p
fun Application.installJudgeStatusPage() {
install(StatusPages) {
// exception<Throwable> { call, cause ->
// call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError)
// }
status(HttpStatusCode.BadRequest) { call, cause ->
call.respondHtml {
body {
h1 {
+"Bad Request"
}
}
}
}
status(HttpStatusCode.NotFound) { call, stat ->
call.respondHtml {
body {
h1 {
+"Not found"
}
}
}
}
status(HttpStatusCode.Unauthorized) { call, stat ->
call.respondHtml(stat) {
body {
h1 {
+"Unauthorized Request"
}
}
}
}
status(HttpStatusCode.TooManyRequests) { call, status ->
val retryAfter = call.response.headers["Retry-After"]
val permission = call.userJudgePermission
call.respondHtml(status) {
body {
h1 {
+"Too Many Request"
}
h4 {
+"wait for $retryAfter seconds to refill your token"
}
p {
+"you are ${permission.name},you only have $TOTAL_TOKEN_IN_DURATION tokens in in $JUDGE_TOKEN_REFILL_DURATION,you will cost ${permission.costTokenPer} for a request"
}
}
}
}
}
}
val ApplicationCall.userJudgePermission: UserJudgePermission
get() {
return try {
cn.llonvne.gojudge.api.UserJudgePermission.valueOf(
this.request.queryParameters[KEY_IN_QUERY] ?: FALL_BACK_PERMISSION.name
)
} catch (e: IllegalArgumentException) {
FALL_BACK_PERMISSION
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/StatusPage.kt | 1851395913 |
package cn.llonvne.gojudge.ktor
import cn.llonvne.gojudge.api.JUDGE_TOKEN_REFILL_DURATION
import cn.llonvne.gojudge.api.TOTAL_TOKEN_IN_DURATION
import cn.llonvne.gojudge.api.UserJudgePermission
import io.ktor.server.application.*
import io.ktor.server.plugins.ratelimit.*
val RACE_LIMIT_JUDGE_NAME = RateLimitName("judge")
fun Application.installJudgeRateLimit() {
install(RateLimit) {
register(RACE_LIMIT_JUDGE_NAME) {
// 每个用户一分钟 1000 个令牌
rateLimiter(limit = TOTAL_TOKEN_IN_DURATION, refillPeriod = JUDGE_TOKEN_REFILL_DURATION)
// 获得用户代码
requestKey {
it.userJudgePermission
}
// 判断用户身份
requestWeight { call, key ->
if (key is UserJudgePermission) {
key.costTokenPer
} else {
TOTAL_TOKEN_IN_DURATION
}
}
}
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/RateLimit.kt | 2870144386 |
package cn.llonvne.gojudge.ktor
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.plugins.doublereceive.*
import io.ktor.server.plugins.requestvalidation.*
import io.ktor.server.request.*
import io.ktor.server.resources.*
import io.ktor.server.routing.*
import kotlinx.serialization.json.Json
import org.slf4j.event.Level
fun Application.installKtorOfficialPlugins() {
install(Routing)
install(Resources)
install(AutoHeadResponse)
install(RequestValidation)
install(ContentNegotiation) {
json(Json {
prettyPrint = true
})
}
install(DoubleReceive)
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
installJudgeStatusPage()
installJudgeRateLimit()
installAuthentication()
installCompression()
installMicrometer()
installCORS()
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/KtorPluginInstaller.kt | 201594591 |
package cn.llonvne.gojudge.ktor
import io.ktor.server.application.*
import io.ktor.server.plugins.compression.*
fun Application.installCompression() {
install(Compression) {
gzip {
priority = 1.0
}
deflate {
priority = 10.0
minimumSize(1024) // condition
}
}
} | OnlineJudge/go-judger/src/main/kotlin/cn/llonvne/gojudge/ktor/Compression.kt | 1636057218 |
import arrow.continuations.SuspendApp
import arrow.continuations.ktor.server
import arrow.core.getOrElse
import arrow.fx.coroutines.resourceScope
import cn.llonvne.gojudge.app.judging
import cn.llonvne.gojudge.docker.GoJudgeResolver
import cn.llonvne.gojudge.docker.toJudgeContext
import cn.llonvne.gojudge.env.loadConfigFromEnv
import io.github.oshai.kotlinlogging.KotlinLogging
import io.ktor.server.netty.*
import kotlinx.coroutines.awaitCancellation
private fun main() = SuspendApp {
val log = KotlinLogging.logger(name = "go-judger-main")
log.info { "Initialization Go Judge ...." }
val env = loadConfigFromEnv()
resourceScope {
val judgeContext = env.judgeSpec.map {
GoJudgeResolver(it).resolve().bind()
}.getOrElse {
throw RuntimeException("Failed to init judge")
}.toJudgeContext()
val port = 8081
server(Netty, port = port) {
judging(judgeContext, port)
}
awaitCancellation()
}
}
| OnlineJudge/go-judger/src/main/kotlin/Main.kt | 1358620284 |
package cn.llonvne.gojudge
/**
* 类似于 Rust Option 的 map
* 用于 A? -> B?
* ```kotlin
* val a:Int? = 1 // a 为 Int?
* val b = a.map { it.toString() } // b 为 String?
* ```
*/
//fun <T : Any, R> T?.map(transform: (T) -> R?): R? = this?.let(transform)
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/extensions.kt | 1385554062 |
package cn.llonvne.gojudge.internal
import io.ktor.client.*
import kotlin.jvm.JvmInline
@JvmInline
value class GoJudgeClient(internal val httpClient: HttpClient) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/internal/GoJudgeClient.kt | 1541688349 |
package cn.llonvne.gojudge.internal
import cn.llonvne.gojudge.api.spec.runtime.Cmd
import cn.llonvne.gojudge.api.spec.runtime.PipeMap
import cn.llonvne.gojudge.api.spec.runtime.RequestType
import cn.llonvne.gojudge.api.spec.runtime.default
class CmdListBuilder {
private val commands = mutableListOf<Cmd>()
internal fun build(): List<Cmd> {
return commands
}
fun add(cmd: Cmd) {
this.commands.add(cmd)
}
}
fun request(
requestId: String? = null,
pipeMap: List<PipeMap>? = null,
cmdListBuilder: CmdListBuilder.() -> Unit
): RequestType.Request {
val cmd = CmdListBuilder()
cmd.cmdListBuilder()
return RequestType.Request(requestId, cmd = cmd.build(), pipeMapping = pipeMap)
}
fun cmd(build: Cmd.() -> Unit): Cmd {
val cmd = Cmd(emptyList())
cmd.default()
cmd.build()
return cmd
}
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/internal/RuntimeServiceExtensions.kt | 1834824784 |
package cn.llonvne.gojudge.internal
import cn.llonvne.gojudge.api.spec.runtime.RequestType
import cn.llonvne.gojudge.api.spec.runtime.Result
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
suspend fun GoJudgeClient.version(): String = httpClient.get("/version").body()
suspend fun GoJudgeClient.config(): String = httpClient.get("/config").body()
suspend fun GoJudgeClient.run(request: RequestType.Request): List<Result> {
val resp: List<Result> = httpClient.post("/run") {
setBody(request)
contentType(ContentType.Application.Json)
}.body()
return resp
}
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/internal/JudgeController.kt | 621807031 |
package cn.llonvne.gojudge.api
import kotlinx.serialization.Serializable
sealed interface ISupportLanguages {
val languageId: Int
val languageName: String
val languageVersion: String
val path: String
}
@Serializable
enum class SupportLanguages(
override val languageId: Int,
override val languageName: String,
override val languageVersion: String,
override val path: String
) : ISupportLanguages {
Java(1, "java", "11", "java"),
Python3(2, "python", "3", "python3"),
Kotlin(3, "kotlin", "1.9.20", "kotlin"),
Cpp11(4, "cpp", "11", "gpp11"),
Cpp14(5, "cpp", "14", "gpp14"),
Cpp17(6, "cpp", "17", "gpp17"),
Cpp98(7, "cpp", "98", "gpp98"),
Cpp20(8, "cpp", "20", "gpp20"),
Cpp23(9, "cpp", "23", "gpp23"),
}
private val idSet = SupportLanguages.entries.associateBy { it.languageId }
fun SupportLanguages.Companion.fromId(id: Int): SupportLanguages? = idSet[id] | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/SupportLanguages.kt | 1208067218 |
package cn.llonvne.gojudge.api
import cn.llonvne.gojudge.api.task.Output
import de.jensklingenberg.ktorfit.Ktorfit
import de.jensklingenberg.ktorfit.http.*
import io.ktor.client.*
internal interface LanguageRouterKtorfitInternalApi {
@Headers("Content-Type:Application/Json")
@GET("{language}/version")
suspend fun version(
@Path language: String
): String
@Headers("Content-Type:Application/Json")
@POST("{language}")
@FormUrlEncoded
suspend fun judge(
@Path language: String,
@Field("code") code: String,
@Field("stdin") stdin: String,
): Output
}
interface LanguageRouterKtorfitApi {
suspend fun version(): String
suspend fun judge(
code: String, stdin: String,
): Output
}
interface LanguageFactory {
fun getLanguageApi(language: SupportLanguages): LanguageRouterKtorfitApi
companion object {
fun get(baseUrl: String, httpClient: HttpClient): LanguageFactory {
return object : LanguageFactory {
private val ktorfit = Ktorfit.Builder()
.baseUrl(baseUrl)
.httpClient(httpClient)
.build()
override fun getLanguageApi(language: SupportLanguages): LanguageRouterKtorfitApi {
return object : LanguageRouterKtorfitApi {
private val service = ktorfit.create<LanguageRouterKtorfitInternalApi>()
override suspend fun version(): String {
return service.version(language.path)
}
override suspend fun judge(code: String, stdin: String): Output {
return service.judge(language.path, code, stdin)
}
}
}
}
}
}
}
interface LanguageDispatcher {
suspend fun <R> dispatch(language: SupportLanguages, on: suspend LanguageRouterKtorfitApi.() -> R): R
companion object {
fun get(languageFactory: LanguageFactory): LanguageDispatcher = LanguageDispatcherImpl(languageFactory)
}
}
private class LanguageDispatcherImpl(
private val languageFactory: LanguageFactory
) : LanguageDispatcher {
private val languageApiSet: Map<SupportLanguages, LanguageRouterKtorfitApi> =
SupportLanguages.entries.associateWith { language ->
languageFactory.getLanguageApi(language)
}
override suspend fun <R> dispatch(language: SupportLanguages, on: suspend LanguageRouterKtorfitApi.() -> R): R {
val api = languageApiSet[language]
if (api == null) {
throw RuntimeException("语言存在于 SupportLanguages 但服务未被发现")
} else {
return api.on()
}
}
}
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/LanguageRouterKtorfitInternalApi.kt | 1513380567 |
@file:Suppress("unused")
package cn.llonvne.gojudge.api.spec.bootstrap
import arrow.optics.optics
import cn.llonvne.gojudge.api.spec.LATEST
import cn.llonvne.gojudge.api.spec.LOCALHOST
import com.benasher44.uuid.uuid4
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Serializable
sealed interface GoJudgeVersion {
val tag: String
@Serializable
data object Latest : GoJudgeVersion {
override val tag: String = LATEST
}
@Serializable
data class Customized(override val tag: String) : GoJudgeVersion
}
@Serializable
data class GoJudgePortMapping(
val outer: Int = 5050, val inner: Int = 5050
) {
init {
require(isValidPort(outer)) {
"outer:$outer is not a valid port in 1..65535"
}
require(isValidPort(inner)) {
"inner:$inner is not a valid port in 1..65535"
}
}
val asDockerPortMappingString get() = "$inner:$outer"
}
@Serializable
sealed interface GoJudgePortMappings {
val binds: List<GoJudgePortMapping>
@Serializable
data object Default : GoJudgePortMappings {
override val binds: List<GoJudgePortMapping> = listOf(GoJudgePortMapping())
}
@Serializable
data class Customized(override val binds: List<GoJudgePortMapping>) : GoJudgePortMappings
}
@Serializable
sealed interface ContainerName {
val name: String
@Serializable
data class GeneratorWithPrefix(val prefix: String, val randomLatterLength: Int = 6) : ContainerName {
override val name: String = "$prefix:${uuid4().toString().subSequence(0..randomLatterLength)}"
}
data class Customized(override val name: String) : ContainerName
}
@Serializable
@optics
/**
* 表示一个网络地址
* 会对 [port] 正确性检查,不会对 [url] 进行任何检查
*/
data class HttpAddr(val url: String, val port: Int) {
init {
require(isValidPort(port))
}
override fun toString(): String {
return "$url:$port"
}
companion object
}
/**
* 指示是否为默认值,该变量不会在序列化时被表示
*/
interface IsDefaultSetting {
@Transient
val isDefault: Boolean
}
@Serializable
@optics
/**
* 表示 Go-Judge 启动时
*/
data class GoJudgeEnvSpec(
val httpAddr: HttpAddr = DEFAULT_HTTP_ADDR,
val enableGrpc: Boolean = DEFAULT_ENABLE_GRPC,
val grpcAddr: HttpAddr = DEFAULT_GRPC_ADDR,
val logLevel: GoJudgeLogLevel = GoJudgeLogLevel.INFO,
val authToken: GoJudgeAuthTokenSetting = GoJudgeAuthTokenSetting.Disabled,
val goDebugEndPoint: Boolean = DEFAULT_GO_DEBUG_ENDPOINT_ENABLE,
val prometheusMetrics: Boolean = DEFAULT_PROMETHEUS_METRICS_ENDPOINT_ENABLE,
val goDebugAndPrometheusMetricsAddr: HttpAddr = DEFAULT_MONITOR_ADDR,
val concurrencyNumber: ConcurrencyNumberSetting = ConcurrencyNumberSetting.EqualCpuCore,
val fileStore: FileStoreSetting = FileStoreSetting.Memory,
// 默认的CGroup前缀是 gojudge ,可以用 -cgroup-prefix flag指定。
val cGroupPrefix: CGroupPrefixSetting = CGroupPrefixSetting.Default,
// 限制 src copyIn 路径用逗号分割(必须是绝对路径)(示例: /bin,/usr )
val srcPrefix: List<String> = listOf(),
val timeLimitCheckerInterval: GoJudgeTimeInterval = GoJudgeTimeInterval.Default,
val outputLimit: OutputLimitSetting = OutputLimitSetting.Default,
// 指定用于检查超出内存限制的额外内存限制(默认为 16KiB)
val extraMemoryLimit: ExtraMemoryLimitSetting = ExtraMemoryLimitSetting.Default,
val copyOutLimit: CopyOutLimitSetting = CopyOutLimitSetting.Default,
val openFileLimit: OpenFileLimitSetting = OpenFileLimitSetting.Default,
val linuxOnlySpec: LinuxOnlySpec = LinuxOnlySpec.default(),
val preFork: PreForkSetting = PreForkSetting.Default,
val fileTimeout: FileTimeoutSetting = FileTimeoutSetting.Disabled
) {
companion object {
val DEFAULT_HTTP_ADDR = HttpAddr(LOCALHOST, 5050)
val DEFAULT_GRPC_ADDR = HttpAddr(LOCALHOST, 5051)
const val DEFAULT_ENABLE_GRPC = false
const val DEFAULT_GO_DEBUG_ENDPOINT_ENABLE = false
const val DEFAULT_PROMETHEUS_METRICS_ENDPOINT_ENABLE = false
val DEFAULT_MONITOR_ADDR = HttpAddr(LOCALHOST, 5052)
}
@Serializable
@optics
sealed interface GoJudgeLogLevel : IsDefaultSetting {
companion object {}
override val isDefault get() = this is INFO
@Serializable
data object INFO : GoJudgeLogLevel
@Serializable
data object SILENT : GoJudgeLogLevel
@Serializable
data object RELEASE : GoJudgeLogLevel
}
@Serializable
@optics
sealed interface GoJudgeAuthTokenSetting : IsDefaultSetting {
companion object {}
override val isDefault: Boolean get() = this is Disabled
@Serializable
data object Disabled : GoJudgeAuthTokenSetting
@Serializable
@optics
data class Enable(val token: String) : GoJudgeAuthTokenSetting {
companion object
}
}
@Serializable
@optics
sealed interface ConcurrencyNumberSetting : IsDefaultSetting {
override val isDefault: Boolean get() = this is EqualCpuCore
@Serializable
data object EqualCpuCore : ConcurrencyNumberSetting
@Serializable
@optics
data class Customized(val number: Int) : ConcurrencyNumberSetting {
init {
require(number > 0)
}
companion object
}
companion object
}
@Serializable
sealed interface FileStoreSetting : IsDefaultSetting {
override val isDefault: Boolean get() = this is Memory
@Serializable
data object Memory : FileStoreSetting
@Serializable
data object Dir : FileStoreSetting
}
@Serializable
@optics
sealed interface CGroupPrefixSetting : IsDefaultSetting {
val prefix: String
override val isDefault: Boolean get() = this is Default
@Serializable
data object Default : CGroupPrefixSetting {
override val prefix: String = "gojudge"
}
@Serializable
@optics
data class Customized(override val prefix: String) : CGroupPrefixSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface GoJudgeTimeInterval : IsDefaultSetting {
val time: String
override val isDefault: Boolean get() = this is Default
@Serializable
data object Default : GoJudgeTimeInterval {
override val time: String = "100ms"
}
@Serializable
@optics
data class Ms(val ms: Int) : GoJudgeTimeInterval {
override val time: String = "${ms}ms"
companion object
}
@Serializable
@optics
data class Second(val second: Int) : GoJudgeTimeInterval {
override val time: String = "${second}s"
companion object
}
companion object
}
@Serializable
@optics
sealed interface OutputLimitSetting : IsDefaultSetting {
val byte: Long
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : OutputLimitSetting {
override val byte: Long
get() = 256L.Mib
}
@Serializable
@optics
data class Customize(override val byte: Long) : OutputLimitSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface ExtraMemoryLimitSetting : IsDefaultSetting {
val byte: Long
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : ExtraMemoryLimitSetting {
override val byte: Long = 16L.Kib
}
@Serializable
@optics
data class Customized(override val byte: Long) : ExtraMemoryLimitSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface CopyOutLimitSetting : IsDefaultSetting {
val byte: Long
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : CopyOutLimitSetting {
override val byte: Long = 64L.Mib
}
@Serializable
@optics
data class Customized(override val byte: Long) : CopyOutLimitSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface OpenFileLimitSetting : IsDefaultSetting {
val limit: Long
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : OpenFileLimitSetting {
override val limit: Long = 256
}
@Serializable
@optics
data class Customized(override val limit: Long) : OpenFileLimitSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface LinuxOnlySpec : IsDefaultSetting {
@Serializable
data object NotLinuxPlatform : LinuxOnlySpec {
override val isDefault: Boolean
get() = true
}
companion object {
fun default() = NotLinuxPlatform
}
@Serializable
@optics
data class LinuxPlatformSpec(
// specifies cpuset.cpus cgroup for each container (Linux only)
val cpuSets: CpuSetting = CpuSetting.Default,
val containerCredStart: ContainerCredStartSetting = ContainerCredStartSetting.Default,
val enableCpuRate: CpuRateSetting = CpuRateSetting.Disable,
// specifies seecomp filter setting to load when running program (need build tag seccomp) (Linux only)
val seccompConf: SeccompConfSetting = SeccompConfSetting.Disable,
// 指定使用默认挂载时 /tmp 的 /w tmpfs 参数(仅限 Linux)
val tmpFsParam: TmsFsParamSetting = TmsFsParamSetting.Default,
val mountConf: MountConfSetting = MountConfSetting.Default
) : LinuxOnlySpec {
override val isDefault: Boolean
get() = false
companion object {}
@Serializable
@optics
sealed interface CpuSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : CpuSetting
@Serializable
@optics
data class Customized(val settings: String) : CpuSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface ContainerCredStartSetting : IsDefaultSetting {
val start: Int
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : ContainerCredStartSetting {
override val start: Int
get() = 10000
}
@Serializable
@optics
data class Customized(override val start: Int) : ContainerCredStartSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface CpuRateSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Disable
@Serializable
data object Disable : CpuRateSetting
@Serializable
data object Enable : CpuRateSetting
companion object
}
@Serializable
@optics
sealed interface SeccompConfSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Disable
@Serializable
data object Disable : SeccompConfSetting
@Serializable
@optics
data class Customized(val settings: String) : SeccompConfSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface TmsFsParamSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : TmsFsParamSetting
@Serializable
@optics
data class Customized(val command: String) : TmsFsParamSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface MountConfSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : MountConfSetting
@Serializable
@optics
data class Customized(val settings: String) : MountConfSetting {
companion object
}
companion object
}
}
}
@Suppress("unused")
@Serializable
@optics
sealed interface PreForkSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Default
@Serializable
data object Default : PreForkSetting
@Serializable
@optics
data class Customized(val instance: Int) : PreForkSetting {
companion object
}
companion object
}
@Serializable
@optics
sealed interface FileTimeoutSetting : IsDefaultSetting {
override val isDefault: Boolean
get() = this is Disabled
@Serializable
data object Disabled : FileTimeoutSetting
@Serializable
@optics
data class Timeout(val minutes: Int) : FileTimeoutSetting {
val seconds = (minutes * 60).toString() + "s"
companion object
}
companion object
}
}
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/spec/bootstrap/bootstrap.kt | 1147207635 |
package cn.llonvne.gojudge.api.spec.bootstrap
/**
* 检查端口是否合法
* @param port 端口号
*/
fun isValidPort(port: Int) = port in 1..65535
/**
* 表示输入的数字表示的是 Kib
* 将自动转换为 bit
*/
val Long.Kib get() = this * 1024
/**
* 表示输入的单位是 Mib
* 将自动转换为 bit
*/
val Long.Mib get() = this.Kib * 1024 | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/spec/bootstrap/BoostrapExtension.kt | 3772715457 |
package cn.llonvne.gojudge.api.spec.runtime
/**
* 传入 stdin,
* 通过收集器收集 stdout 和 stderr
*/
internal fun useStdOutErrForFiles(stdin: String = "", max: Int = 10240) = mutableListOf(
GoJudgeFile.MemoryFile(
content = stdin
), GoJudgeFile.Collector(
name = "stdout", max = max
), GoJudgeFile.Collector(
name = "stderr", max = max
)
)
/**
* 导出 stdout,stderr
*/
internal fun useStdOutErrForCopyOut() = mutableListOf("stdout", "stderr")
/**
* 将代码[content]作为内存文件以[sourceFilename]作为文件名导入
*/
internal fun useMemoryCodeCopyIn(sourceFilename: String, content: String) = mutableMapOf(
sourceFilename to GoJudgeFile.MemoryFile(content)
)
/**
* 将 [fileId] 导入到以 [newName] 作为文件名
*/
internal fun useFileIdCopyIn(fileId: String, newName: String) = mapOf(newName to GoJudgeFile.PreparedFile(fileId))
val useUsrBinEnv = listOf("PATH=/usr/bin:/bin")
/**
* cmd 的默认设置
*/
internal fun Cmd.default() {
procLimit = 50
memoryLimit = 104857600
cpuLimit = 10000000000
}
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/spec/runtime/RuntimeExtension.kt | 1130757934 |
@file:Suppress("UNUSED")
package cn.llonvne.gojudge.api.spec.runtime
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
sealed interface GoJudgeFile {
@Serializable
data class LocalFile(
val src: String // absolute path for the file
) : GoJudgeFile
@Serializable
data class MemoryFile(
val content: String // file contents, can be String or ByteArray (Buffer in TypeScript)
) : GoJudgeFile
@Serializable
data class PreparedFile(
val fileId: String // fileId defines file uploaded by /file
) : GoJudgeFile
@Serializable
data class Collector(
val name: String, // file name in copyOut
val max: Int, // maximum bytes to collect from pipe
val pipe: Boolean? = null // collect over pipe or not (default false)
) : GoJudgeFile
}
@Serializable
data class Symlink(
val symlink: String // symlink destination (v1.6.0+)
)
@Serializable
data class Cmd(
var args: List<String>, // command line argument
var env: List<String>? = null, // environment
// specifies file input / pipe collector for program file descriptors
var files: List<GoJudgeFile>? = null, // Any can be LocalFile, MemoryFile, PreparedFile, Collector
var tty: Boolean? = null, // enables tty on the input and output pipes (should have just one input & one output)
// Notice: must have TERM environment variables (e.g. TERM=xterm)
// limitations
var cpuLimit: Long? = null, // ns
var realCpuLimit: Long? = null, // deprecated: use clock limit instead (still working)
var clockLimit: Long? = null, // ns
var memoryLimit: Long? = null, // byte
var stackLimit: Long? = null, // byte (N/A on windows, macOS cannot set over 32M)
var procLimit: Int? = null,
var cpuRateLimit: Int? = null, // limit cpu usage (1000 equals 1 cpu)
var cpuSetLimit: String? = null, // Linux only: set the cpuSet for cgroup
var strictMemoryLimit: Boolean? = null, // deprecated: use dataSegmentLimit instead (still working)
var dataSegmentLimit: Boolean? = null, // Linux only: use (+ rlimit_data limit) enable by default if cgroup not enabled
var addressSpaceLimit: Boolean? = null, // Linux only: use (+ rlimit_address_space limit)
// copy the correspond file to the container dst path
var copyIn: Map<String, GoJudgeFile>? = null, // Any can be LocalFile, MemoryFile, PreparedFile, Symlink
// copy out specifies files need to be copied out from the container after execution
// append '?' after file name will make the file optional and do not cause FileError when missing
var copyOut: List<String>? = null,
// similar to copyOut but stores file in go judge and returns fileId, later download through /file/:fileId
var copyOutCached: List<String>? = null,
// specifies the directory to dump container /w content
var copyOutDir: String? = null,
// specifies the max file size to copy out
var copyOutMax: Int? = null // byte
)
@Serializable
enum class Status {
Accepted, // normal
@SerialName("Memory Limit Exceeded")
MemoryLimitExceeded, // mle
@SerialName("Time Limit Exceeded")
TimeLimitExceeded, // tle
@SerialName("Output Limit Exceeded")
OutputLimitExceeded, // ole
@SerialName("File Error")
FileError, // fe
@SerialName("Nonzero Exit Status")
NonzeroExitStatus,
Signalled,
@SerialName("Internal Error")
InternalError // system error
}
@Serializable
data class PipeIndex(
val index: Int, // the index of cmd
val fd: Int // the fd number of cmd
)
@Serializable
data class PipeMap(
@SerialName("in")
val In: PipeIndex, // input end of the pipe
val out: PipeIndex, // output end of the pipe
// enable pipe proxy from in to out,
// content from in will be discarded if out closes
val proxy: Boolean? = null,
val name: String? = null, // copy out proxy content if proxy enabled
// limit the copy out content size,
// proxy will still functioning after max
val max: Int? = null
)
@Serializable
enum class FileErrorType {
CopyInOpenFile,
CopyInCreateFile,
CopyInCopyContent,
CopyOutOpen,
CopyOutNotRegularFile,
CopyOutSizeExceeded,
CopyOutCreateFile,
CopyOutCopyContent,
CollectSizeExceeded
}
@Serializable
data class FileError(
val name: String, // error file name
val type: FileErrorType, // type
val message: String? = null // detailed message
)
@Serializable
sealed interface RequestType {
@Serializable
data class Request(
val requestId: String? = null, // for WebSocket requests
val cmd: List<Cmd>,
val pipeMapping: List<PipeMap>? = null
) : RequestType
@Serializable
data class CancelRequest(
val cancelRequestId: String
) : RequestType
}
// WebSocket request
typealias WSRequest = RequestType // Any can be Request or CancelRequest
@Serializable
data class Result(
val status: Status,
val error: String? = null, // potential system error message
val exitStatus: Int,
val time: Long, // ns (cgroup recorded time)
val memory: Long, // byte
val runTime: Long, // ns (wall clock time)
// copyFile name -> content
val files: Map<String, String?>? = null,
// copyFileCached name -> fileId
val fileIds: Map<String, String>? = null,
// fileError contains detailed file errors
val fileError: List<FileError>? = null
)
@Serializable
// WebSocket results
data class WSResult(
val requestId: String,
val results: List<Result>,
val error: String? = null
) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/spec/runtime/runtime.kt | 1555895687 |
package cn.llonvne.gojudge.api.spec
internal const val LATEST = "latest"
internal const val LOCALHOST = "localhost" | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/spec/constants.kt | 3527266518 |
package cn.llonvne.gojudge.api.task
interface Input {
val code: String
val stdin: String
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/Input.kt | 3930843802 |
package cn.llonvne.gojudge.api.task
import arrow.core.None
import arrow.core.Option
import arrow.core.Some
import cn.llonvne.gojudge.api.Task
import cn.llonvne.gojudge.api.spec.runtime.Cmd
import cn.llonvne.gojudge.api.spec.runtime.RequestType
import cn.llonvne.gojudge.api.spec.runtime.Result
import cn.llonvne.gojudge.api.spec.runtime.Status
import cn.llonvne.gojudge.api.task.Output.Failure.CompileError
import cn.llonvne.gojudge.api.task.Output.Failure.CompileResultIsNull
import cn.llonvne.gojudge.internal.GoJudgeClient
import cn.llonvne.gojudge.internal.request
import cn.llonvne.gojudge.internal.run
import com.benasher44.uuid.uuid4
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
/**
* 通过评测机执行评测任务的基类
*/
internal abstract class AbstractTask<I : Input> : Task<I, Output> {
/**
* 源代码拓展名
* 返回 None 时将没有后缀
*/
abstract val sourceCodeExtension: Option<String>
/**
* 编译后源代码拓展名
* 返回 None 时将没有后缀
*/
abstract val compiledFileExtension: Option<String>
abstract fun getCompileCmd(input: I, filenames: Filenames): Cmd
abstract fun getRunCmd(input: I, compileResult: Result, runFilename: Filename, runFileId: String): Cmd
@Serializable
sealed interface HookError<E, R> {
@Serializable
data class Error<E, R>(val output: E) : HookError<E, R>
@Serializable
data class Resume<E, R>(val result: R) : HookError<E, R>
}
@Serializable
data class Filenames(val source: Filename, val compiled: Filename)
@Serializable
data class Filename(val name: String, @Contextual val extension: Option<String>) {
fun asString() = when (extension) {
None -> name
is Some -> "$name.${extension.value}"
}
override fun toString(): String {
return asString()
}
}
open fun beforeAll() {
}
open suspend fun installDependency() {
}
/**
* 在生成完文件名,可以调用该函数进行修改
* 生成文件名依赖的下列拓展名已被包含在文件中
*
* 默认生成的源代码名称为
* 随机UUID.sourceCodeExtension
* 默认生成的编译后代码名称为
* 随机UUID.compiledFileExtension
*
* [sourceCodeExtension]
* [compiledFileExtension]
*/
open fun transformSourceOrCompiledFilename(filenames: Filenames): Filenames {
return filenames
}
/**
* 在构建完 runRequest 使用 [getCompileCmd] 后
* 调用该函数对 request 进行修改
*/
open fun hookOnBeforeCompile(request: RequestType.Request) {}
/**
* 如果编译存在结果(不为 null)则会调用该函数
*/
open fun hookOnCompileResult(result: Result) {}
/**
* 编译结果是null,调用该函数
*/
open fun transformCompileResultNull(
request: RequestType.Request, expectOutput: Output
): HookError<Output, Result> {
return HookError.Error(expectOutput)
}
/**
* 尝试改变编译状态
*/
open fun transformCompileStatus(compileStatus: Status, compileResult: Result): Status {
return compileStatus
}
/**
* 预期的正常编译状态
* 正常为返回 Accepted
*/
open fun expectCompileStatus(): Status {
return Status.Accepted
}
/**
* 改变 RunFilename
*/
open fun transformRunFilename(filename: Filename) = filename
/**
* 改变运行要求
*/
open fun transformRunRequest(request: RequestType.Request): RequestType.Request {
return request
}
/**
* 改变运行结果
*/
open fun transformRunResult(request: RequestType.Request, result: Result) = result
/**
* 改变运行错误的结果
*/
open fun transformRunError(request: RequestType.Request, expect: Output): Output {
return expect
}
/**
* 改变运行成功的结果
*/
open fun transformRunSuccess(result: Result, expectOutput: Output): Output {
return expectOutput
}
/**
* 在即将返回结果的时候做一些事
*/
open fun hookOnReturnRunOutput(expectOutput: Output) {
}
sealed interface FlowOutputStatus {
data class BeforeAll(val input: Input, val service: GoJudgeClient) : FlowOutputStatus
data class BeforeCompile(val request: RequestType.Request) : FlowOutputStatus
// 包装 Output 类型
data class Output(val output: cn.llonvne.gojudge.api.task.Output) : FlowOutputStatus
// 文件名
data class FilenamesFlowOutput(val filenames: Filenames) : FlowOutputStatus
// 完成编译
data class CompileSuccess(val result: Result) : FlowOutputStatus
data class RunFilename(val filename: Filename) : FlowOutputStatus
data class RunRequest(val request: RequestType.Request) : FlowOutputStatus
}
/**
* runFlow 不支持HOOK函数的形式
*/
suspend fun runFlow(input: I, service: GoJudgeClient): Flow<FlowOutputStatus> = flow {
emit(FlowOutputStatus.BeforeAll(input, service))
val filenames = transformSourceOrCompiledFilename(
Filenames(
source = Filename(uuid4().toString(), sourceCodeExtension),
compiled = Filename(uuid4().toString(), compiledFileExtension)
)
)
emit(FlowOutputStatus.FilenamesFlowOutput(filenames))
val compileRequest = request {
add(getCompileCmd(input, filenames))
}
emit(FlowOutputStatus.BeforeCompile(compileRequest))
val compileResult = service.run(compileRequest).getOrNull(0)
?: return@flow emit(FlowOutputStatus.Output(CompileResultIsNull(compileRequest)))
emit(FlowOutputStatus.CompileSuccess(compileResult))
if (transformCompileStatus(compileResult.status, compileResult) != expectCompileStatus()) {
return@flow emit(FlowOutputStatus.Output(CompileError(compileRequest, compileResult)))
}
val fileId = compileResult.fileIds?.get(filenames.compiled.asString()) ?: return@flow emit(
FlowOutputStatus.Output(
Output.Failure.TargetFileNotExist(
compileRequest, compileResult
)
)
)
val runFilename = Filename(uuid4().toString(), None)
emit(FlowOutputStatus.RunFilename(runFilename))
val runRequest = request {
add(getRunCmd(input, compileResult, runFilename, fileId))
}
emit(FlowOutputStatus.RunRequest(runRequest))
val result = service.run(runRequest).firstOrNull() ?: return@flow emit(
FlowOutputStatus.Output(
Output.Failure.RunResultIsNull(
compileRequest, compileResult, runRequest
)
)
)
emit(
FlowOutputStatus.Output(
Output.Success(compileRequest, compileResult, runRequest, result)
)
)
}
override suspend fun run(input: I, service: GoJudgeClient): Output {
beforeAll()
val filenames = transformSourceOrCompiledFilename(
Filenames(
Filename(uuid4().toString(), sourceCodeExtension), Filename(uuid4().toString(), compiledFileExtension)
)
)
val compileRequest = request {
add(getCompileCmd(input, filenames))
}
hookOnBeforeCompile(compileRequest)
val compileResult = service.run(compileRequest).getOrNull(0) ?: when (val result =
transformCompileResultNull(compileRequest, CompileResultIsNull(compileRequest))) {
is HookError.Error -> return result.output
is HookError.Resume -> result.result
}
hookOnCompileResult(compileResult)
if (transformCompileStatus(compileResult.status, compileResult) != expectCompileStatus()) {
return CompileError(compileRequest, compileResult)
}
val fileId =
compileResult.fileIds?.get(filenames.compiled.asString()) ?: return Output.Failure.TargetFileNotExist(
compileRequest, compileResult
)
val runFilename = transformRunFilename(Filename(uuid4().toString(), None))
val runRequest = transformRunRequest(request {
add(getRunCmd(input, compileResult, runFilename, fileId))
})
return when (val result = service.run(runRequest).getOrNull(0)) {
null -> transformRunError(
compileRequest, Output.Failure.RunResultIsNull(
compileRequest, compileResult, runRequest
)
)
else -> transformRunSuccess(
result, Output.Success(
compileRequest, compileResult, runRequest, transformRunResult(runRequest, result)
)
)
}.also {
hookOnReturnRunOutput(it)
}
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/AbstractTask.kt | 836829392 |
package cn.llonvne.gojudge.api.task.python
import arrow.core.Option
import arrow.core.some
import cn.llonvne.gojudge.api.Task
import cn.llonvne.gojudge.api.spec.runtime.*
import cn.llonvne.gojudge.api.task.AbstractTask
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.Output
import cn.llonvne.gojudge.internal.cmd
fun python3CompileTask(): Task<CodeInput, Output> = PythonCompileTask()
private class PythonCompileTask(
private val pyCmd: String = "python3"
) : AbstractTask<CodeInput>() {
/**
* 源代码拓展名
* 返回 None 时将没有后缀
*/
override val sourceCodeExtension: Option<String>
get() = "py".some()
/**
* 编译后源代码拓展名
* 返回 None 时将没有后缀
*/
override val compiledFileExtension: Option<String>
get() = "py".some()
override fun transformSourceOrCompiledFilename(filenames: Filenames): Filenames {
return Filenames(filenames.source, filenames.source)
}
override fun getCompileCmd(input: CodeInput, filenames: Filenames): Cmd {
return cmd {
args = listOf()
env = useUsrBinEnv
files = useStdOutErrForFiles()
copyIn = useMemoryCodeCopyIn(filenames.source.asString(), input.code)
copyOut = useStdOutErrForCopyOut()
copyOutCached = listOf(filenames.source.asString(), filenames.compiled.asString())
}
}
override fun transformCompileStatus(compileStatus: Status, compileResult: Result): Status {
return Status.Accepted
}
override fun getRunCmd(input: CodeInput, compileResult: Result, runFilename: Filename, runFileId: String): Cmd {
return cmd {
args = listOf(pyCmd, runFilename.name)
env = useUsrBinEnv
files = useStdOutErrForFiles(input.stdin)
copyIn = useFileIdCopyIn(fileId = runFileId, newName = runFilename.asString())
}
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/python/PythonCompileTask.kt | 3553924383 |
package cn.llonvne.gojudge.api.task
import cn.llonvne.gojudge.api.spec.runtime.RequestType
import cn.llonvne.gojudge.api.spec.runtime.Result
import kotlinx.serialization.Serializable
@Serializable
sealed interface Output {
@Serializable
sealed interface Failure : Output {
@Serializable
data class CompileResultIsNull(val compileRequest: RequestType.Request) : Failure
@Serializable
data class CompileError(val compileRequest: RequestType.Request, val compileResult: Result) : Failure
@Serializable
data class TargetFileNotExist(val compileRequest: RequestType.Request, val compileResult: Result) : Failure
@Serializable
data class RunResultIsNull(
val compileRequest: RequestType.Request,
val compileResult: Result,
val runRequest: RequestType.Request
) : Failure
}
@Serializable
data class Success(
val compileRequest: RequestType.Request,
val compileResult: Result,
val runRequest: RequestType.Request,
val runResult: Result
) : Output
companion object {
fun Output.formatOnSuccess(notSuccess: String, onSuccess: (Success) -> String): String {
return when (this) {
is Success -> onSuccess(this)
else -> notSuccess
}
}
val Output?.runTimeRepr: String
get() {
return format("-") {
formatOnSuccess("-") {
it.runResult.runTime.toString()
}
}
}
val Output?.memoryRepr: String
get() {
return format("-") {
formatOnSuccess("-") {
it.runResult.memory.toString()
}
}
}
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/Output.kt | 2058292637 |
package cn.llonvne.gojudge.api.task.java
import arrow.core.Option
import arrow.core.some
import cn.llonvne.gojudge.api.Task
import cn.llonvne.gojudge.api.spec.runtime.*
import cn.llonvne.gojudge.api.task.AbstractTask
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.Output
import cn.llonvne.gojudge.internal.cmd
fun javaCompileTask(): Task<CodeInput, Output> = JavaCompileTask()
private class JavaCompileTask : AbstractTask<CodeInput>() {
override val sourceCodeExtension: Option<String>
get() = "java".some()
override val compiledFileExtension: Option<String>
get() = "class".some()
override fun getCompileCmd(input: CodeInput, filenames: Filenames) = cmd {
args = useJavacArgs(filenames)
env = useUsrBinEnv
files = useStdOutErrForFiles()
copyIn = useMemoryCodeCopyIn(filenames.source.asString(), input.code)
copyOut = useStdOutErrForCopyOut()
copyOutCached = listOf(filenames.source.asString(), filenames.compiled.asString())
}
override fun transformSourceOrCompiledFilename(filenames: Filenames): Filenames {
return filenames.copy(
source = filenames.source.copy(name = "Main"),
compiled = filenames.compiled.copy(name = "Main")
)
}
override fun transformRunFilename(filename: Filename): Filename {
return filename.copy(name = "Main", extension = "class".some())
}
override fun getRunCmd(input: CodeInput, compileResult: Result, runFilename: Filename, runFileId: String) = cmd {
args = listOf("java", runFilename.name)
env = useUsrBinEnv
files = useStdOutErrForFiles(input.stdin)
copyIn = useFileIdCopyIn(fileId = runFileId, newName = runFilename.asString())
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/java/JavaCompileTask.kt | 4246400415 |
package cn.llonvne.gojudge.api.task.java
import cn.llonvne.gojudge.api.task.AbstractTask
internal fun useJavacArgs(filenames: AbstractTask.Filenames) =
listOf("javac", filenames.source.asString()) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/java/JavaCompileExts.kt | 1212585479 |
package cn.llonvne.gojudge.api.task.gcc
import arrow.core.Option
import arrow.core.some
import cn.llonvne.gojudge.api.spec.runtime.Cmd
import cn.llonvne.gojudge.api.spec.runtime.Result
import cn.llonvne.gojudge.api.task.AbstractTask
import cn.llonvne.gojudge.api.task.CodeInput
internal class GccCompileTask : AbstractTask<CodeInput>() {
override val sourceCodeExtension: Option<String>
get() = "c".some()
override val compiledFileExtension: Option<String>
get() = "out".some()
override fun getCompileCmd(input: CodeInput, filenames: Filenames): Cmd {
TODO("Not yet implemented")
}
override fun getRunCmd(input: CodeInput, compileResult: Result, runFilename: Filename, runFileId: String): Cmd {
TODO("Not yet implemented")
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/gcc/GccCompileTask.kt | 3975311114 |
package cn.llonvne.gojudge.api.task.kotlin
import arrow.core.Option
import arrow.core.some
import cn.llonvne.gojudge.api.Task
import cn.llonvne.gojudge.api.spec.runtime.*
import cn.llonvne.gojudge.api.task.AbstractTask
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.Output
import cn.llonvne.gojudge.internal.cmd
fun kotlinCompileTask(): Task<CodeInput, Output> = KotlinCompileTask()
internal class KotlinCompileTask : AbstractTask<CodeInput>() {
override val sourceCodeExtension: Option<String>
get() = "kt".some()
override val compiledFileExtension: Option<String>
get() = "class".some()
override fun transformSourceOrCompiledFilename(filenames: Filenames): Filenames {
return filenames.copy(source = Filename("Main", "kt".some()), compiled = Filename("MainKt", "class".some()))
}
override fun getCompileCmd(input: CodeInput, filenames: Filenames): Cmd {
return cmd {
args = useKotlincArgs(filenames)
env = useUsrBinEnv
files = useStdOutErrForFiles()
copyIn = useMemoryCodeCopyIn(filenames.source.asString(), input.code)
copyOut = useStdOutErrForCopyOut()
copyOutCached =
listOf(filenames.source.asString(), filenames.compiled.asString())
}
}
override fun transformCompileStatus(compileStatus: Status, compileResult: Result): Status {
return if (compileResult.exitStatus == 0) {
Status.Accepted
} else {
compileStatus
}
}
override fun transformRunFilename(filename: Filename): Filename {
return Filename("MainKt", "class".some())
}
override fun getRunCmd(input: CodeInput, compileResult: Result, runFilename: Filename, runFileId: String) = cmd {
args = listOf("kotlin", runFilename.name)
env = useUsrBinEnv
files = useStdOutErrForFiles(input.stdin)
copyIn = useFileIdCopyIn(fileId = runFileId, newName = runFilename.asString())
}
}
internal fun useKotlincArgs(filenames: AbstractTask.Filenames) =
listOf("kotlinc", filenames.source.asString()) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/kotlin/KotlinCompileTask.kt | 3666233360 |
package cn.llonvne.gojudge.api.task
data class CodeInput(override val code: String, override val stdin: String) : Input
| OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/CodeInput.kt | 2012536832 |
package cn.llonvne.gojudge.api.task.gpp
import cn.llonvne.gojudge.api.task.AbstractTask
/**
* G++ 编译器命令
*/
private fun gppCompileCommand(source: String, output: String, cppVersion: CppVersion): List<String> {
return listOf("/usr/bin/g++", source, "-o", output, cppVersion.asArg())
}
/**
* 将传入的文件名转换为 G++编译命令
*/
internal fun buildGppCompileCommand(filenames: AbstractTask.Filenames, cppVersion: CppVersion) =
gppCompileCommand(
filenames.source.asString(),
filenames.compiled.asString(),
cppVersion
) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/gpp/GppCompileExts.kt | 1659402241 |
package cn.llonvne.gojudge.api.task.gpp
enum class CppVersion {
Cpp98,
Cpp11,
Cpp14,
Cpp17,
Cpp20,
Cpp23
}
fun CppVersion.asArg() = "-std=c++" + this.name.substring(3) | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/gpp/CppVersion.kt | 3185003364 |
package cn.llonvne.gojudge.api.task.gpp
import arrow.core.None
import arrow.core.Option
import arrow.core.some
import cn.llonvne.gojudge.api.Task
import cn.llonvne.gojudge.api.spec.runtime.*
import cn.llonvne.gojudge.api.task.AbstractTask
import cn.llonvne.gojudge.api.task.CodeInput
import cn.llonvne.gojudge.api.task.Output
import cn.llonvne.gojudge.internal.cmd
fun gppCompileTask(cppVersion: CppVersion): Task<CodeInput, Output> = GppCompileTask(cppVersion)
private class GppCompileTask(private val cppVersion: CppVersion) : AbstractTask<CodeInput>() {
override val sourceCodeExtension: Option<String>
get() = "cpp".some()
override val compiledFileExtension: Option<String>
get() = None
override fun getCompileCmd(input: CodeInput, filenames: Filenames): Cmd {
return cmd {
args = buildGppCompileCommand(filenames, cppVersion = cppVersion)
env = useUsrBinEnv
files = useStdOutErrForFiles()
copyIn = useMemoryCodeCopyIn(filenames.source.asString(), input.code)
copyOut = useStdOutErrForCopyOut()
copyOutCached = listOf(filenames.source.asString(), filenames.compiled.asString())
}
}
override fun getRunCmd(
input: CodeInput,
compileResult: Result,
runFilename: Filename,
runFileId: String
): Cmd {
return cmd {
args = listOf(runFilename.asString())
env = useUsrBinEnv
files = useStdOutErrForFiles(input.stdin)
copyIn = useFileIdCopyIn(fileId = runFileId, newName = runFilename.asString())
}
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/gpp/GppCompileTask.kt | 3494787440 |
package cn.llonvne.gojudge.api.task
fun Output?.format(onNull: String, onNotNull: Output.() -> String): String {
return if (this == null) {
onNull
} else {
onNotNull(this)
}
} | OnlineJudge/go-judge-api/src/commonMain/kotlin/cn/llonvne/gojudge/api/task/OutputExts.kt | 4217465451 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.