core load

This commit is contained in:
jiahua.liu 2020-03-04 22:15:46 +08:00
parent 9ba8801a45
commit e104661ba7
5 changed files with 273 additions and 49 deletions

View File

@ -80,10 +80,11 @@ class MiraiGraphicalUIController : Controller(), MiraiConsoleUI {
}
class GraphicalLoginSolver : LoginSolver() {
override suspend fun onSolvePicCaptcha(bot: Bot, data: IoBuffer): String? {
override suspend fun onSolvePicCaptcha(bot: Bot, data: ByteArray): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override suspend fun onSolveSliderCaptcha(bot: Bot, url: String): String? {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

View File

@ -36,14 +36,42 @@ tasks.withType<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar>() {
val miraiVersion: String by rootProject.ext
dependencies {
implementation("net.mamoe:mirai-core-jvm:$miraiVersion")
implementation("net.mamoe:mirai-core-qqandroid-jvm:$miraiVersion")
compileOnly("net.mamoe:mirai-core-jvm:$miraiVersion")
compileOnly("net.mamoe:mirai-core-qqandroid-jvm:$miraiVersion")
api(kotlin("serialization"))
api(group = "com.alibaba", name = "fastjson", version = "1.2.62")
api(group = "org.yaml", name = "snakeyaml", version = "1.25")
api(group = "com.moandjiezana.toml", name = "toml4j", version = "0.7.2")
api("no.tornado:tornadofx:1.7.19")
api(kotlin("stdlib", kotlinVersion))
api(kotlin("serialization", kotlinVersion))
api("org.jetbrains.kotlinx:atomicfu:$atomicFuVersion")
api(kotlinx("coroutines-io", coroutinesIoVersion))
api(kotlinx("coroutines-core", coroutinesVersion))
api(ktor("client-core-jvm", ktorVersion))
api(kotlinx("serialization-runtime", serializationVersion))
api(kotlinx("coroutines-io", coroutinesIoVersion))
api(kotlinx("coroutines-io-jvm", coroutinesIoVersion))
api(kotlinx("io-jvm", coroutinesIoVersion))
api("org.bouncycastle:bcprov-jdk15on:1.64")
api(kotlin("reflect", kotlinVersion))
api(kotlin("serialization", kotlinVersion))
api(kotlinx("coroutines-core-common", coroutinesVersion))
api(kotlinx("serialization-runtime-common", serializationVersion))
api(ktor("http-cio", ktorVersion))
api(ktor("http", ktorVersion))
api(ktor("client-core-jvm", ktorVersion))
api(ktor("client-cio", ktorVersion))
api(ktor("client-core", ktorVersion))
api(ktor("network", ktorVersion))
}
val mirai_console_version: String by project.ext

View File

@ -17,6 +17,7 @@ import net.mamoe.mirai.console.command.CommandManager
import net.mamoe.mirai.console.command.CommandSender
import net.mamoe.mirai.console.command.ConsoleCommandSender
import net.mamoe.mirai.console.command.DefaultCommands
import net.mamoe.mirai.console.core.MiraiCoreLoader
import net.mamoe.mirai.console.plugins.PluginManager
import net.mamoe.mirai.console.plugins.loadAsConfig
import net.mamoe.mirai.console.plugins.withDefaultWrite
@ -82,6 +83,16 @@ object MiraiConsole {
}
start = true
/* 初始化前端 */
this.frontEnd = frontEnd
frontEnd.pushVersion(version, build, "Loading")
logger("Mirai-console now running under $path")
logger("Get news in github: https://github.com/mamoe/mirai")
logger("Mirai为开源项目请自觉遵守开源项目协议")
logger("Powered by Mamoe Technologies and contributors")
MiraiCoreLoader()
/* 加载ECDH */
try {
ECDH()
@ -90,18 +101,8 @@ object MiraiConsole {
//Security.removeProvider("BC")
/* 初始化前端 */
this.frontEnd = frontEnd
frontEnd.pushVersion(version, build, coreVersion)
logger("Mirai-console [$version $build | core version $coreVersion] is still in testing stage, major features are available")
logger("Mirai-console now running under $path")
logger("Get news in github: https://github.com/mamoe/mirai")
logger("Mirai为开源项目请自觉遵守开源项目协议")
logger("Powered by Mamoe Technologies and contributors")
/* 依次启用功能 */
DefaultCommands()
HTTPAPIAdaptar()
pluginManager.loadPlugins()
CommandProcessor.start()
@ -183,36 +184,4 @@ object MiraiConsole {
}
object MiraiProperties {
var config = File("${MiraiConsole.path}/mirai.properties").loadAsConfig()
var HTTP_API_ENABLE: Boolean by config.withDefaultWrite { true }
var HTTP_API_PORT: Int by config.withDefaultWrite { 8080 }
/*
var HTTP_API_AUTH_KEY: String by config.withDefaultWriteSave {
"InitKey" + generateSessionKey()
}*/
}
object HTTPAPIAdaptar {
operator fun invoke() {
/*
if (MiraiProperties.HTTP_API_ENABLE) {
if (MiraiProperties.HTTP_API_AUTH_KEY.startsWith("InitKey")) {
MiraiConsole.logger("请尽快更改初始生成的HTTP API AUTHKEY")
}
MiraiConsole.logger("正在启动HTTPAPI; 端口=" + MiraiProperties.HTTP_API_PORT)
MiraiHttpAPIServer.logger = SimpleLogger("HTTP API") { _, message, e ->
MiraiConsole.logger("[Mirai HTTP API]", 0, message)
}
MiraiHttpAPIServer.start(
MiraiProperties.HTTP_API_PORT,
MiraiProperties.HTTP_API_AUTH_KEY
)
MiraiConsole.logger("HTTPAPI启动完成; 端口= " + MiraiProperties.HTTP_API_PORT)
}*/
}
}

View File

@ -0,0 +1,229 @@
package net.mamoe.mirai.console.core
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.get
import io.ktor.client.request.url
import io.ktor.client.statement.HttpResponse
import io.ktor.http.URLProtocol
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.jvm.javaio.copyTo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import net.mamoe.mirai.console.MiraiConsole
import java.io.File
import java.net.URLClassLoader
import kotlin.math.pow
import kotlin.system.exitProcess
@Suppress("EXPERIMENTAL_API_USAGE")
val Http: HttpClient get() = HttpClient(CIO)
object MiraiCoreLoader {
val coresPath by lazy {
File(System.getProperty("user.dir") + "/core/").also {
if (!it.exists()) {
it.mkdirs()
}
}
}
private fun getProtocolLib():File?{
this.coresPath.listFiles()?.forEach { file ->
if (file != null && file.extension == "jar" && file.name.contains("qqandroid")) {
return file
}
}
return null
}
private fun getCore():File?{
this.coresPath.listFiles()?.forEach { file ->
if (file != null && file.extension == "jar" && file.name.contains("core") && (!file.name.contains("qqandroid"))) {
return file
}
}
return null
}
operator fun invoke():String{
MiraiConsole.logger("Fetching Newest Core Version .. ")
val newest = runBlocking {
getNewestVersion()
}
val current = getCurrentVersion()
MiraiConsole.logger("Local Version: $current | Newest Version: $newest")
if(current != newest){
MiraiConsole.logger("Updating from V$current -> V$newest, this is a force update")
cleanCoreAndLib()
runBlocking {
downloadCoreAndLib(newest)
}
MiraiConsole.logger("Download complete")
}
MiraiConsole.logger("Loading Core")
loadCoreAndLib()
MiraiConsole.logger("Mirai Core Loaded, current core version $newest")
return newest
}
/**
* 使用Protocol Lib判断最新版本
* */
private suspend fun getNewestVersion(): String {
try {
return """>([0-9])*\.([0-9])*\.([0-9])*/""".toRegex().findAll(
Http.get<String> {
url {
protocol = URLProtocol.HTTPS
host = "jcenter.bintray.com"
path("net/mamoe/mirai-core-qqandroid-jvm/")
}
}
).asSequence()
.map { it.value.drop(1).dropLast(1) }
.maxBy {
it.split('.').foldRightIndexed(0) { index: Int, s: String, acc: Int ->
acc + 100.0.pow(index).toInt() + (s.toIntOrNull() ?: 0)
}
}!!
}catch (e:Exception){
MiraiConsole.logger("Failed to fetch newest Core version, please seek for help")
e.printStackTrace()
MiraiConsole.logger("Failed to fetch newest Core version, please seek for help")
exitProcess(1)
}
}
/**
* 使用Protocol Lib判断当前版本
* 如果没有 会返回0.0.0
* */
private fun getCurrentVersion():String{
val file = getProtocolLib()
if(file == null || getCore() == null)return "0.0.0"
val numberVersion = """([0-9])*\.([0-9])*\.([0-9])*""".toRegex().find(file.name)?.value
if(numberVersion != null) {
return numberVersion + file.name.substringAfter(numberVersion).substringBefore(".jar")
}
return "0.0.0"
}
private fun cleanCoreAndLib(){
this.coresPath.listFiles()?.forEach {
if (it != null && it.extension == "jar") {
it.delete()
}
}
}
val lib_jcenter = "https://jcenter.bintray.com/net/mamoe/mirai-core-qqandroid-jvm/{version}/:mirai-core-qqandroid-jvm-{version}.jar"
val lib_aliyun = "https://maven.aliyun.com/nexus/content/repositories/jcenter/net/mamoe/mirai-core-qqandroid-jvm/{version}/mirai-core-qqandroid-jvm-{version}.jar"
val core_jcenter = "https://jcenter.bintray.com/net/mamoe/mirai-core-jvm/{version}/:mirai-core-jvm-{version}.jar"
val core_aliyun = "https://maven.aliyun.com/nexus/content/repositories/jcenter/net/mamoe/mirai-core-jvm/{version}/mirai-core-jvm-{version}.jar"
private suspend fun downloadCoreAndLib(version:String){
var fileStream = File(coresPath.absolutePath + "/" + "mirai-core-qqandroid-jvm-$version.jar").also{
withContext(Dispatchers.IO) {
it.createNewFile()
}
}.outputStream()
suspend fun downloadRequest(url:String, version:String):ByteReadChannel{
return Http.get<HttpResponse>(){
this.url(url.replace("{version}",version))
}.content
}
var stream = try{
MiraiConsole.logger("Downloading newest Protocol lib from Aliyun")
downloadRequest(lib_aliyun,version)
}catch (ignored:Exception){
try{
MiraiConsole.logger("Downloading newest Protocol lib from JCenter")
downloadRequest(lib_jcenter,version)
}catch (e:Exception){
MiraiConsole.logger("Failed to download Protocol lib, please seeking for help")
e.printStackTrace()
MiraiConsole.logger("Failed to download Protocol lib, please seeking for help")
exitProcess(1)
}
}
withContext(Dispatchers.IO) {
stream.copyTo(fileStream)
fileStream.flush()
}
fileStream = File(coresPath.absolutePath + "/" + "mirai-core-jvm-$version.jar").also{
withContext(Dispatchers.IO) {
it.createNewFile()
}
}.outputStream()
stream = try{
MiraiConsole.logger("Downloading newest Mirai Core from Aliyun")
downloadRequest(core_aliyun,version)
}catch (ignored:Exception){
try{
MiraiConsole.logger("Downloading newest Mirai Core from JCenter")
downloadRequest(core_jcenter,version)
}catch (e:Exception){
MiraiConsole.logger("Failed to download Mirai Core, please seeking for help")
e.printStackTrace()
MiraiConsole.logger("Failed to download Mirai Core, please seeking for help")
exitProcess(1)
}
}
withContext(Dispatchers.IO) {
stream.copyTo(fileStream)
fileStream.flush()
}
}
private fun loadCoreAndLib(){
try {
MiraiConsole.logger("Core:" + getCore())
MiraiConsole.logger("Protocol:" + getProtocolLib())
MiraiCoreClassLoader(
(getCore()!!),
this.javaClass.classLoader
)
.loadClass("net.mamoe.mirai.BotFactory")
MiraiCoreClassLoader(
(getProtocolLib()!!),
this.javaClass.classLoader
)
.loadClass("net.mamoe.mirai.qqandroid.QQAndroid")
} catch (e: ClassNotFoundException) {
MiraiConsole.logger("Failed to load core, please seek for help")
e.printStackTrace()
MiraiConsole.logger("Failed to load core, please seek for help")
exitProcess(1)
}
}
}
internal class MiraiCoreClassLoader(file: File, parent: ClassLoader) :
URLClassLoader(arrayOf(file.toURI().toURL()), parent)

View File

@ -37,8 +37,6 @@ abstract class PluginBase(coroutineContext: CoroutineContext) : CoroutineScope {
val dataFolder: File by lazy {
File(_getDataFolder()).also {
it.mkdir()
println(it.absolutePath)
println(pluginName)
}
}
@ -351,7 +349,6 @@ object PluginManager {
val subClass = pluginClass.asSubclass(PluginBase::class.java)
val plugin: PluginBase =
subClass.kotlin.objectInstance ?: subClass.getDeclaredConstructor().newInstance()
println("aaaaaa")
description.loaded = true
logger.info("successfully loaded plugin " + description.name + " version " + description.version + " by " + description.author)
logger.info(description.info)