Skip to content
This repository has been archived by the owner on Oct 20, 2023. It is now read-only.

Commit

Permalink
fix: 修复自动下载资源失败
Browse files Browse the repository at this point in the history
refactor: 修改 ID 格式判断规则
feat: 添加了一些辅助性方法
  • Loading branch information
StarWishsama committed Nov 6, 2020
1 parent 10b4649 commit c68883a
Show file tree
Hide file tree
Showing 14 changed files with 160 additions and 84 deletions.
10 changes: 3 additions & 7 deletions src/main/kotlin/io/github/starwishsama/comet/Comet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import io.github.starwishsama.comet.listeners.ConvertLightAppListener
import io.github.starwishsama.comet.listeners.RepeatListener
import io.github.starwishsama.comet.pushers.*
import io.github.starwishsama.comet.utils.FileUtil
import io.github.starwishsama.comet.utils.StringUtil.getLastingTime
import io.github.starwishsama.comet.utils.StringUtil.isNumeric
import io.github.starwishsama.comet.utils.StringUtil.toFriendly
import io.github.starwishsama.comet.utils.TaskUtil
import io.github.starwishsama.comet.utils.getContext
import io.github.starwishsama.comet.utils.network.NetUtil
Expand All @@ -37,12 +37,10 @@ import net.mamoe.mirai.utils.BotConfiguration
import net.mamoe.mirai.utils.FileCacheStrategy
import net.mamoe.mirai.utils.PlatformLogger
import net.mamoe.mirai.utils.secondsToMillis
import java.time.Duration
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.time.ExperimentalTime
import kotlin.time.toKotlinDuration

object Comet {
@ExperimentalTime
Expand Down Expand Up @@ -153,7 +151,7 @@ object Comet {
InfoCommand(),
MusicCommand(),
MuteCommand(),
PictureSearch(),
PictureSearchCommand(),
R6SCommand(),
RConCommand(),
KickCommand(),
Expand Down Expand Up @@ -183,9 +181,7 @@ object Comet {
startUpTask()
startAllPusher(bot)

val duration = Duration.between(startTime, LocalDateTime.now())

logger.info("彗星 Bot 启动成功, 耗时 ${duration.toKotlinDuration().toFriendly()}")
logger.info("彗星 Bot 启动成功, 耗时 ${startTime.getLastingTime()}")

Runtime.getRuntime().addShutdownHook(Thread {
logger.info("[Bot] 正在关闭 Bot...")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import io.github.starwishsama.comet.sessions.Session
import io.github.starwishsama.comet.sessions.SessionManager
import io.github.starwishsama.comet.utils.BotUtil
import io.github.starwishsama.comet.utils.StringUtil.convertToChain
import io.github.starwishsama.comet.utils.StringUtil.getLastingTime
import io.github.starwishsama.comet.utils.debugS
import io.github.starwishsama.comet.utils.network.NetUtil
import net.mamoe.mirai.Bot
Expand All @@ -19,13 +20,10 @@ import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.message.GroupMessageEvent
import net.mamoe.mirai.message.MessageEvent
import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.utils.asHumanReadable
import java.time.Duration
import java.time.LocalDateTime
import java.util.*
import kotlin.time.DurationUnit
import java.util.concurrent.TimeUnit
import kotlin.time.ExperimentalTime
import kotlin.time.toKotlinDuration

/**
* 彗星 Bot 命令处理器
Expand Down Expand Up @@ -107,8 +105,8 @@ object CommandExecutor {

if (isCommand) {
BotVariables.logger.debugS(
"[命令] 命令执行耗时 ${Duration.between(executedTime, LocalDateTime.now()).toKotlinDuration().asHumanReadable}" +
if (result.result.isNotEmpty()) ", 执行结果: ${result.result}" else ""
"[命令] 命令执行耗时 ${executedTime.getLastingTime(builtInMethod = true)}" +
if (result.result.isNotEmpty()) ", 执行结果: ${result.result}" else ""
)
}
}
Expand Down Expand Up @@ -225,10 +223,8 @@ object CommandExecutor {
}
}

val usedTime = Duration.between(time, LocalDateTime.now())
BotVariables.logger.debug(
"[会话] 处理会话耗时 ${usedTime.toKotlinDuration().toLong(DurationUnit.SECONDS)}s${usedTime.toKotlinDuration()
.toLong(DurationUnit.MILLISECONDS)}ms"
"[会话] 处理会话耗时 ${time.getLastingTime(unit = TimeUnit.SECONDS, msMode = true)}"
)
return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import io.github.starwishsama.comet.BotVariables.logger
import io.github.starwishsama.comet.enums.R6Rank
import io.github.starwishsama.comet.objects.pojo.rainbowsix.R6Player
import io.github.starwishsama.comet.utils.BotUtil
import io.github.starwishsama.comet.utils.IDGuidelineType
import io.github.starwishsama.comet.utils.StringUtil
import io.github.starwishsama.comet.utils.network.NetUtil
import java.text.NumberFormat
Expand Down Expand Up @@ -49,7 +50,7 @@ object R6TabApi {

fun getR6SInfo(player: String): String {
try {
if (StringUtil.isLegitId(player)) {
if (StringUtil.isLegitId(player, IDGuidelineType.UBISOFT)) {
val p: R6Player? = searchPlayer(player)
if (p != null && p.found) {
var response = String.format(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,15 @@ class ArkNightCommand : ChatCommand {
event.reply("请稍等...")
val list = pool.getArkDrawResult(user)
if (list.isNotEmpty()) {
val gachaImage = withContext(Dispatchers.Default) { DrawUtil.combineArkOpImage(list).upload(event.subject) }
val result = DrawUtil.combineArkOpImage(list)
event.quoteReply(BotUtil.sendMessage("由于缺失资源文件, 以下干员无法显示 :(\n" +
buildString {
result.lostOps.forEach {
append("${it.name},")
}
removeSuffix(",")
}))
val gachaImage = withContext(Dispatchers.Default) { result.image.upload(event.subject) }
gachaImage.asMessageChain()
} else {
DrawUtil.overTimeMessage.convertToChain()
Expand All @@ -48,7 +56,15 @@ class ArkNightCommand : ChatCommand {
event.reply("请稍等...")
val list: List<ArkNightOperator> = pool.getArkDrawResult(user, 10)
if (list.isNotEmpty()) {
val gachaImage = withContext(Dispatchers.Default) { DrawUtil.combineArkOpImage(list).upload(event.subject) }
val result = DrawUtil.combineArkOpImage(list)
event.quoteReply(BotUtil.sendMessage("由于缺失资源文件, 以下干员无法显示 :(\n" +
buildString {
result.lostOps.forEach {
append("${it.name},")
}
removeSuffix(",")
}))
val gachaImage = withContext(Dispatchers.Default) { result.image.upload(event.subject) }
gachaImage.asMessageChain()
} else {
DrawUtil.overTimeMessage.convertToChain()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import io.github.starwishsama.comet.api.thirdparty.youtube.YoutubeApi
import io.github.starwishsama.comet.enums.UserLevel
import io.github.starwishsama.comet.file.DataSetup
import io.github.starwishsama.comet.objects.BotUser
import io.github.starwishsama.comet.objects.draw.items.ArkNightOperator
import io.github.starwishsama.comet.pushers.HitokotoUpdater
import io.github.starwishsama.comet.pushers.TweetUpdateChecker
import io.github.starwishsama.comet.pushers.YoutubeStreamingChecker
Expand Down Expand Up @@ -143,6 +144,20 @@ class DebugCommand : ChatCommand, UnDisableableCommand {
""".trimIndent().convertToChain()
}
"panic" -> throw RuntimeException("")
"ark" -> {
var op: ArkNightOperator? = null

if (args.size > 1) {
BotVariables.arkNight.parallelStream().forEach {
if (args[1] == it.name) {
op = it
return@forEach
}
}
}

return op.toString().convertToChain()
}
"twpic" -> {
if (args.isEmpty()) return "/debug twpic [Tweet ID]".convertToChain()
else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import net.mamoe.mirai.message.data.queryUrl
import java.util.*

@CometCommand
class PictureSearch : ChatCommand, SuspendCommand {
class PictureSearchCommand : ChatCommand, SuspendCommand {
override suspend fun execute(event: MessageEvent, args: List<String>, user: BotUser): MessageChain {
if (BotUtil.hasNoCoolDown(event.sender.id)) {
if (args.isEmpty() || SessionManager.isValidSessionById(event.sender.id)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import io.github.starwishsama.comet.enums.UserLevel
import io.github.starwishsama.comet.objects.BotUser
import io.github.starwishsama.comet.utils.BotUtil
import io.github.starwishsama.comet.utils.BotUtil.hasNoCoolDown
import io.github.starwishsama.comet.utils.IDGuidelineType
import io.github.starwishsama.comet.utils.StringUtil.isLegitId
import net.mamoe.mirai.message.GroupMessageEvent
import net.mamoe.mirai.message.MessageEvent
Expand All @@ -30,7 +31,7 @@ class R6SCommand : ChatCommand {
val result = getR6SInfo(account)
event.sender.at() + ("\n" + result)
} else {
if (isLegitId(args[1])) {
if (isLegitId(args[1], IDGuidelineType.UBISOFT)) {
event.reply(BotUtil.sendMessage("查询中..."))
val result = getR6SInfo(args[1])
event.sender.at() + ("\n" + result)
Expand All @@ -41,7 +42,7 @@ class R6SCommand : ChatCommand {
}
"bind", "绑定" ->
if (args[1].isNotEmpty() && args.size > 1) {
if (isLegitId(args[1])) {
if (isLegitId(args[1], IDGuidelineType.UBISOFT)) {
val botUser1 = BotUser.getUser(event.sender.id)
if (botUser1 != null) {
botUser1.r6sAccount = args[1]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import io.github.starwishsama.comet.BotVariables
import io.github.starwishsama.comet.BotVariables.arkNight
import io.github.starwishsama.comet.BotVariables.cfg
import io.github.starwishsama.comet.BotVariables.daemonLogger
import io.github.starwishsama.comet.BotVariables.gson
Expand Down Expand Up @@ -76,8 +77,9 @@ object DataSetup {
}

if (arkNightData.exists()) {
BotVariables.arkNight = gson.fromJson(arkNightData.getContext())
daemonLogger.info("成功载入明日方舟游戏数据, 共 ${BotVariables.arkNight.size}")
arkNight = gson.fromJson(arkNightData.getContext())

daemonLogger.info("成功载入明日方舟游戏数据, 共 ${arkNight.size}")
if (cfg.arkDrawUseImage) {
DrawUtil.downloadArkNightsFile()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ import java.util.stream.Collectors
class ArkNightPool(override val name: String = "标准寻访") : GachaPool() {
override val tenjouCount: Int = -1
override val tenjouRare: Int = -1
override val poolItems: MutableList<ArkNightOperator> =
BotVariables.arkNight.parallelStream().filter {
it.obtain.contains("标准寻访") && it.obtain.contains("限定寻访")
}.collect(Collectors.toList())
override val poolItems: MutableList<ArkNightOperator> = BotVariables.arkNight

override fun doDraw(time: Int): List<ArkNightOperator> {
val result = mutableListOf<ArkNightOperator>()
Expand Down
61 changes: 44 additions & 17 deletions src/main/kotlin/io/github/starwishsama/comet/utils/DrawUtil.kt
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package io.github.starwishsama.comet.utils

import cn.hutool.core.net.URLEncoder
import io.github.starwishsama.comet.BotVariables.arkNight
import io.github.starwishsama.comet.BotVariables.daemonLogger
import io.github.starwishsama.comet.enums.UserLevel
import io.github.starwishsama.comet.exceptions.ApiException
import io.github.starwishsama.comet.objects.BotUser
import io.github.starwishsama.comet.objects.draw.items.ArkNightOperator
import io.github.starwishsama.comet.utils.StringUtil.getLastingTime
import io.github.starwishsama.comet.utils.network.NetUtil
import java.awt.Image
import java.awt.image.BufferedImage
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
import java.time.LocalDateTime
import javax.imageio.ImageIO

object DrawUtil {
Expand All @@ -21,46 +26,44 @@ object DrawUtil {
"命令条数现在每小时会恢复100次, 封顶1000次"

// 干员名称/干员名称.png
const val resourceUrl = "https://cdn.jsdelivr.net/gh/godofhuaye/arknight-assets@master/cg/"
private const val resourceUrl = "https://cdn.jsdelivr.net/gh/godofhuaye/arknight-assets@master/cg"

/**
* 根据抽卡结果合成图片
*/
fun combineArkOpImage(ops: List<ArkNightOperator>): BufferedImage {
fun combineArkOpImage(ops: List<ArkNightOperator>): CombinedResult {
require(ops.isNotEmpty()) { "传入的干员列表不能为空!" }

/**
* 缩小图片大小,减少流量消耗
*/
val zoom = 2
val lostOperators = mutableListOf<ArkNightOperator>()

val picSize = 180

val newBufferedImage = BufferedImage(picSize * ops.size, picSize, BufferedImage.TYPE_INT_RGB)

val createGraphics = newBufferedImage.createGraphics()

var newBufferedImageWidth = 0
val newBufferedImageHeight = 0

for (i in ops) {
val file = File(FileUtil.getResourceFolder().getChildFolder("ark"), i.name + ".png")

if (!file.exists()) {
lostOperators.plusAssign(i)
daemonLogger.warning("明日方舟: 干员 ${i.name} 的图片不存在")
} else {
val inStream: InputStream = file.inputStream()

val bufferedImage: BufferedImage = ImageIO.read(inStream)

val imageWidth = bufferedImage.width / zoom
val imageHeight = bufferedImage.height / zoom
val imageWidth = bufferedImage.width
val imageHeight = bufferedImage.height

createGraphics.drawImage(
bufferedImage.getScaledInstance(
imageWidth,
imageHeight,
Image.SCALE_SMOOTH
), newBufferedImageWidth, newBufferedImageHeight, imageWidth, imageHeight, null
), newBufferedImageWidth, 0, imageWidth, imageHeight, null
)

newBufferedImageWidth += imageWidth
Expand All @@ -70,10 +73,15 @@ object DrawUtil {

createGraphics.dispose()

return newBufferedImage
return CombinedResult(newBufferedImage, lostOperators)

}

data class CombinedResult(
val image: BufferedImage,
val lostOps: List<ArkNightOperator>
)

fun getStar(rare: Int): String = StringBuilder().apply {
for (i in 0 until rare) {
append("")
Expand All @@ -84,18 +92,37 @@ object DrawUtil {
(user.commandTime >= time || user.compareLevel(UserLevel.ADMIN)) && time <= 10000

fun downloadArkNightsFile() {
if (FileUtil.getResourceFolder().getChildFolder("ark").isEmpty()) {
if (FileUtil.getResourceFolder().getChildFolder("ark").filesCount() < arkNight.size) {
val startTime = LocalDateTime.now()
daemonLogger.info("正在下载 明日方舟图片资源文件")

val arkLoc = FileUtil.getResourceFolder().getChildFolder("ark")

var successCount = 0

arkNight.forEach {
val fileName = "${it.name}.png"
val pathName = URLEncoder.createDefault().encode("${it.name}/$fileName", Charset.forName("UTF-8"))
try {
NetUtil.downloadFile(FileUtil.getResourceFolder().getChildFolder("ark"), "$resourceUrl$it.name/$fileName", fileName)
} catch (e: RuntimeException) {
daemonLogger.warning("下载 $fileName 时出现了意外", e)
return
val file = File(arkLoc, fileName)
if (!file.exists()) {
val result = TaskUtil.executeWithRetry(3) {
NetUtil.downloadFile(arkLoc, "$resourceUrl/$pathName", fileName)
successCount++
}
if (result != null) throw result
}
} catch (e: Exception) {
if (e !is ApiException)
daemonLogger.warning("下载 $fileName 时出现了意外", e)
return@forEach
} finally {
if (successCount > 0 && successCount % 10 == 0) {
daemonLogger.info("明日方舟 > 已下载 $successCount/${arkNight.size}")
}
}
}
daemonLogger.info("下载明日方舟资源文件完成!")
daemonLogger.info("明日方舟 > 资源文件下载成功, 耗时 ${startTime.getLastingTime()}")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,14 @@ fun File.isEmpty(): Boolean {
return files.isEmpty()
}

fun File.filesCount(): Int {
if (!isDirectory) return -1

val files = listFiles() ?: return -1

return files.size
}

object FileUtil {
private val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")

Expand Down
Loading

0 comments on commit c68883a

Please sign in to comment.