Initial commit

This commit is contained in:
筱傑
2021-08-01 14:53:18 +08:00
commit f167c99525
14 changed files with 893 additions and 0 deletions

183
src/main/kotlin/GlotAPI.kt Normal file
View File

@@ -0,0 +1,183 @@
import com.beust.klaxon.Json
import com.beust.klaxon.Klaxon
import java.security.InvalidKeyException
/**
* # glot.io api 封装
* [https://glot.io/] 是一个开源的在线运行代码的网站
* 它提供了免费API供外界使用API文档见 [https://github.com/glotcode/glot/blob/master/api_docs]
* 本类是对该API文档的封装
* 通过 [listLanguages] 获取支持在线运行的编程语言列表
* ~~通过 [getVersion] 获取对应语言的最新版本请求地址~~
* 通过 [getSupport] 判断指定编程语言是否支持
* 通过 [getFilename] 来获取指定编程语言的文件名runCode需要
* 以上接口均有缓存,仅首次获取不同数据时会发起请求。因此,首次运行可能较慢。
* 通过 [runCode] 运行代码
* 若觉得原版 [runCode] 使用复杂,还可以使用另一个更简单的重载 [runCode]
* @suppress 注意,若传入不支持的语言,或者格式不正确,将无法正确识别
* @author jie65535@github
*/
object GlotAPI {
private const val URL = "https://glot.io/"
private const val URL_NEW = "https://glot.io/new/"
private const val URL_API = URL + "api/"
private const val URL_LIST_LANGUAGES = URL_API + "run"
// 运行代码需要api token这是的我帐号申请的可以在[https://glot.io/auth/page/simple/register]注册帐号
private const val API_TOKEN = "074ef4a7-7a94-47f2-9891-85511ef1fb52"
data class Language(val name: String, val url: String)
data class CodeFile(val name: String, val content: String)
data class RunCodeRequest(@Json(serializeNull = false) val stdin: String?,
@Json(serializeNull = false) val command: String?,
val files: List<CodeFile>)
data class RunResult(val stdout: String, val stderr: String, val error: String)
private var languages: List<Language>? = null
private val filenames: MutableMap<String, String> = mutableMapOf()
// val fileExtensions: Map<String, String> = mapOf("assembly" to "asm", "ats" to "dats", "bash" to "sh", "c" to "c", "clojure" to "clj", "cobol" to "cob", "coffeescript" to "coffee", "cpp" to "cpp", "crystal" to "cr", "csharp" to "cs", "d" to "d", "elixir" to "ex", "elm" to "elm", "erlang" to "erl", "fsharp" to "fs", "go" to "go", "groovy" to "groovy", "haskell" to "hs", "idris" to "idr", "java" to "java", "javascript" to "js", "julia" to "jl", "kotlin" to "kt", "lua" to "lua", "mercury" to "m", "nim" to "nim", "nix" to "nix", "ocaml" to "ml", "perl" to "pl", "php" to "php", "python" to "py", "raku" to "raku", "ruby" to "rb", "rust" to "rs", "scala" to "scala", "swift" to "swift", "typescript" to "ts", "plaintext" to "txt", )
/**
* 列出所有支持在线运行的语言(缓存)
* @return 返回支持的语言列表 示例:
* ```json
* [
* {
* "name": "assembly",
* "url": "https://glot.io/api/run/assembly"
* },
* {
* "name": "c",
* "url": "https://glot.io/api/run/c"
* }
* ]
* ```
*/
fun listLanguages(): List<Language> {
if (languages == null) {
languages = Klaxon().parseArray(HttpUtil.get(URL_LIST_LANGUAGES)) ?: throw Exception("未获取到任何数据")
}
return languages!!
}
/**
* 检查是否支持该语言在线编译
* @param language 编程语言名字(忽略大小写)
* @return 是否支持
*/
fun checkSupport(language: String): Boolean = listLanguages().any { it.name.equals(language, true) }
/**
* 获取编程语言请求地址,若不支持将会抛出异常
* @param language 编程语言名字(忽略大小写)
* @return 返回语言请求地址
* @exception InvalidKeyException 不支持的语言
*/
fun getSupport(language: String): Language =
listLanguages().find { it.name.equals(language, true) } ?: throw InvalidKeyException("不支持的语言")
/**
* 获取指定编程语言文件名(缓存)
* @exception Exception 若不支持或无法获取,将抛出异常
* @return 建议文件名通常是main.c之类的java比较特殊是Main.java所以需要请求避免硬编码
*/
fun getFilename(language: String): String {
val lang = getSupport(language)
if (filenames.containsKey(lang.name))
return filenames[lang.name]!!
val document = HttpUtil.getDocument(URL_NEW + lang.name)
val filename = HttpUtil.documentSelect(document, ".filename").firstOrNull()?.text() ?: throw Exception("无法获取文件名")
filenames[lang.name] = filename
return filename
}
/**
* # 运行代码
*
* ## 简单示例:
* 请求
* ```json
* {
* "files": [
* {
* "name": "main.py",
* "content": "print(42)"
* }
* ]
* }
* ```
* 响应
* ```json
* {
* "stdout": "42\n",
* "stderr": "",
* "error": ""
* }
* ```
*
* ## 读输入流示例:
* 请求
* ```json
* {
* "stdin": "42",
* "files": [
* {
* "name": "main.py",
* "content": "print(input('Number from stdin: '))"
* }
* ]
* }
* ```
* 响应
* ```json
* {
* "stdout": "Number from stdin: 42\n",
* "stderr": "",
* "error": ""
* }
* ```
*
* ## 自定义运行命令示例:
* 请求
* ```json
* {
* "command": "bash main.sh 42",
* "files": [
* {
* "name": "main.sh",
* "content": "echo Number from arg: $1"
* }
* ]
* }
* ```
* 响应
* ```json
* {
* "stdout": "Number from arg: 42\n",
* "stderr": "",
* "error": ""
* }
* ```
* @param language 要运行的编程语言
* @param requestData 运行代码的请求数据
* @return 返回运行结果 若执行了死循环或其它阻塞代码,
* 导致程序无法在限定时间内返回,将会报告超时异常
*/
fun runCode(language: Language, requestData: RunCodeRequest): RunResult {
val response = HttpUtil.post(language.url + "/latest", Klaxon().toJsonString(requestData), mapOf("Authorization" to API_TOKEN))
return Klaxon().parse(response) ?: throw Exception("未获取到任何数据")
}
/**
* # 运行代码
* 更简单的运行代码重载
* @param language 编程语言
* @param code 程序代码
* @param stdin 可选的输入缓冲区数据
* @return 返回运行结果 若执行了死循环或其它阻塞代码,
* 导致程序无法在限定时间内返回,将会报告超时异常
*/
fun runCode(language: String, code: String, stdin: String? = null): RunResult =
runCode(getSupport(language), RunCodeRequest(stdin, null, listOf(CodeFile(getFilename(language), code))))
}

View File

@@ -0,0 +1,82 @@
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.io.File
import java.util.concurrent.TimeUnit
object HttpUtil {
private val JSON: MediaType? = "application/json; charset=utf-8".toMediaTypeOrNull()
private val okHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.build()
}
/**
* ### 下载图片
*/
fun downloadImage(url: String, file: File): ByteArray {
val request = Request.Builder().url(url).build()
val imageByte = okHttpClient.newCall(request).execute().body!!.bytes()
val fileParent = file.parentFile
if (!fileParent.exists()) fileParent.mkdirs()
file.writeBytes(imageByte)
return imageByte
}
/**
* ### 发送GET请求
*/
fun get(url: String): String {
val request = Request.Builder().url(url).build()
return okHttpClient.newCall(request).execute().body!!.string()
}
/**
* ### 发送带Json参数的POST请求
*/
fun post(url: String, json: String): String {
val requestBody = json.toRequestBody(JSON)
val request = Request.Builder().url(url).post(requestBody).build()
return okHttpClient.newCall(request).execute().body!!.string()
}
/**
* ### 发送带Header与Json参数的POST请求
*/
fun post(url: String, json: String, params: Map<String, String>): String {
val requestBody = json.toRequestBody(JSON)
val requestBuilder = Request.Builder().url(url)
for (param in params)
requestBuilder.addHeader(param.key, param.value)
val request = requestBuilder.post(requestBody).build()
return okHttpClient.newCall(request).execute().body!!.string()
}
/**
* ### 解析网页响应
*/
fun parseBody(responseBody: String): Document {
return Jsoup.parse(responseBody)
}
/**
* ### 发送GET请求并解析
*/
fun getDocument(url: String): Document {
return parseBody(get(url))
}
/**
* ### Document 元素选择
*/
fun documentSelect(document: Document, cssQuery: String): Elements {
return document.select(cssQuery)
}
}

99
src/main/kotlin/JCC.kt Normal file
View File

@@ -0,0 +1,99 @@
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.register
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.unregister
import net.mamoe.mirai.console.command.parse.CommandCallParser
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
import net.mamoe.mirai.contact.Group
import net.mamoe.mirai.contact.isBotMuted
import net.mamoe.mirai.event.globalEventChannel
import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.message.data.At
import net.mamoe.mirai.message.data.MessageChainBuilder
import net.mamoe.mirai.utils.info
import okhttp3.internal.indexOfNonWhitespace
object JCC : KotlinPlugin(
JvmPluginDescription(
id = "me.jie65535.jcc",
name = "J Compiler Collection",
version = "0.1",
) {
author("jie65535")
info("""在线编译器集合""")
}
) {
const val CMD_PREFIX = "jcc"
override fun onEnable() {
logger.info { "Plugin loaded" }
JccCommand.register()
globalEventChannel().subscribeMessages {
startsWith(CMD_PREFIX, false) reply {
if (subject is Group && (subject as Group).isBotMuted)
return@reply null
val msg = it.substring(CMD_PREFIX.length).trim()
if (msg.isNotEmpty()) {
val index = msg.indexOfFirst(Char::isWhitespace)
if (index >= 0)
{
val language = msg.substring(0, index)
val code = msg.substring(index).trim()
if (!GlotAPI.checkSupport(language))
return@reply "不支持这种编程语言\n/jcc list #列出所有支持的编程语言"
if (code.isEmpty())
return@reply "请输入要运行的代码"
try {
// subject.sendMessage("正在执行,请稍等...")
logger.info("请求执行代码")
val result = GlotAPI.runCode(language, code)
val builder = MessageChainBuilder()
var c = 0
if (result.stdout.isNotEmpty()) c++
if (result.stderr.isNotEmpty()) c++
if (result.error.isNotEmpty()) c++
val title = c >= 2
var msgLength = 0
if (subject is Group) {
builder.add(At(sender))
builder.add("\n")
}
if (result.error.isNotEmpty()) {
builder.add("error:\n")
builder.add(result.error)
msgLength += result.error.length + 7
}
if (result.stdout.isNotEmpty()) {
if (title) builder.add("\nstdout:\n")
builder.add(result.stdout)
msgLength += result.stdout.length
}
if (result.stderr.isNotEmpty()) {
if (title) builder.add("\nstderr:\n")
builder.add(result.stderr)
msgLength += result.stderr.length
}
val messageChain = builder.build()
if (msgLength > 500) {
val messageContent = messageChain.contentToString()
return@reply "消息内容过长已贴到Pastebin\n" + UbuntuPastebinHelper.paste(messageContent)
} else {
return@reply messageChain
}
} catch (e: Exception) {
logger.warning(e)
return@reply "执行失败\n原因:${e.message}"
}
}
}
return@reply "请输入正确的命令!例如:\n$CMD_PREFIX python print(\"Hello world\")"
}
}
}
override fun onDisable() {
JccCommand.unregister()
}
}

View File

@@ -0,0 +1,24 @@
import net.mamoe.mirai.console.command.CommandSender
import net.mamoe.mirai.console.command.CompositeCommand
object JccCommand : CompositeCommand(
JCC, "jcc",
description = "在线编译器集合"
) {
@SubCommand
@Description("列出所有支持的编程语言")
suspend fun CommandSender.list() {
try {
sendMessage(GlotAPI.listLanguages().joinToString { it.name })
} catch (e: Exception) {
sendMessage("执行失败\n${e.message}")
JCC.logger.warning(e)
}
}
@SubCommand
@Description("帮助")
suspend fun CommandSender.help() {
sendMessage("直接调用jcc即可运行代码\n例如jcc python print(\"Hello world\")\n其它指令:\n$usage")
}
}

View File

@@ -0,0 +1,82 @@
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.jsoup.Jsoup
import java.io.IOException
/**
* # ubuntu pastebin 帮助类
* [https://paste.ubuntu.com] 是一个用于共享文档的网站
* 由于pastebin本身没有对外提供api所以本类使用解析html的方式实现
* 通过 [getSyntaxList] 获取支持的语法列表(缓存)
* 通过 [get] 获取链接的内容
* 通过 [paste] 来粘贴内容
*
* @author jie65535@github
*/
object UbuntuPastebinHelper {
private const val URL = "https://paste.ubuntu.com"
private var syntaxList: Map<String, String>? = null
/**
* 获取支持的语法列表(缓存)
* @return 返回一个map其中key是给人看的value是作为参数传递的
*/
fun getSyntaxList(): Map<String, String> {
if (syntaxList != null)
return syntaxList!!
val document = HttpUtil.getDocument(URL)
val element = HttpUtil.documentSelect(document, "select#id_syntax > option")
val map = mutableMapOf<String, String>()
for (opt in element)
map[opt.text()] = opt.`val`()
syntaxList = map
return map
}
/**
* 获取内容
* @param url pastebin地址https://paste.ubuntu.com/p/nmn8yKMtND/
* @return 返回链接中贴的内容
*/
fun get(url: String): String {
if (url.isEmpty() || !url.startsWith("https://paste.ubuntu.com/p/"))
throw Exception("非法的url")
val document = HttpUtil.getDocument(url)
return HttpUtil.documentSelect(document, ".paste > pre").text()
}
/**
* 上传内容
* @param content 上传内容
* @param syntax 语法例如c/cpp 可以通过getSyntaxList得到所有支持的语法传入pair的value 默认值text
* @param poster 主题文本最大长度30字符 默认值:"temp"
* @param expiration 过期时间((empty)/day/week/month/year 默认值:"day"
* @return 返回访问地址https://paste.ubuntu.com/p/nmn8yKMtND/
*/
fun paste(content: String, syntax: String = "text", poster: String = "temp", expiration: String = "day"): String? {
if (poster.length > 30)
throw Exception("poster length too long!")
if (content.isEmpty())
throw Exception("content cannot be empty!")
val okHttpClient = OkHttpClient().newBuilder()
.followRedirects(false)
.build()
val requestBody = FormBody.Builder()
.add("poster", poster)
.add("syntax", syntax)
.add("expiration", expiration)
.add("content", content)
.build()
val request = Request.Builder()
.url(URL)
.post(requestBody)
.build()
val response = okHttpClient.newCall(request).execute()
if (response.code == 200)
throw Exception("请求已经成功,但无法执行动作,请检查参数")
return if (response.code == 302)
URL + response.header("Location")
else
throw IOException("请求失败,请检查网络或参数")
}
}