Skip to content

Commit

Permalink
Optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
LittleMengBot committed Apr 8, 2023
1 parent f484fef commit d094fca
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 27 deletions.
65 changes: 43 additions & 22 deletions src/main/kotlin/command/download/GifDownload.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import com.github.kotlintelegrambot.entities.Update
import com.github.kotlintelegrambot.entities.files.Animation
import com.github.kotlintelegrambot.entities.files.Document
import dsl.edit
import dsl.execListener
import dsl.replyToText
import file.FileUtils
import mu.KotlinLogging
Expand Down Expand Up @@ -99,29 +98,51 @@ fun getAnimationCommand(bot: Bot, update: Update) {

fun toGif(tempByteArray: ByteArray, suffix: String): ByteArray? {
val vFile = FileUtils.convertToTemp(tempByteArray, "gif", suffix)
val ffmpegStatus = Runtime.getRuntime().exec(
"${configCache!!.ffmpeg_path} -i " +
"${vFile.absolutePath} ${vFile.absolutePath}.gif"
).execListener()!!
return if (ffmpegStatus.contains("Invalid")) {
val ffmpegPath = configCache!!.ffmpeg_path // FFmpeg 路径

// 转换文件为 GIF 格式
val gifFile = convertFileToGif(vFile, ffmpegPath)
if (gifFile == null || !gifFile.exists()) {
vFile.delete()
null
} else {
val ret = File("${vFile.absolutePath}.gif")
val size = ret.length()
try {
if (size < 20971520) {
Files.readAllBytes(ret.toPath())
} else {
null
}
} catch (e: IOException) {
logger.error(e.toString())
null
} finally {
ret.delete()
vFile.delete()
return null
}

// 读取 GIF 文件内容
val gifData = readFile(gifFile)
gifFile.delete()
vFile.delete()

return gifData
}

private fun convertFileToGif(sourceFile: File, ffmpegPath: String): File? {
val gifFile = File(sourceFile.absolutePath + ".gif")
val cmd = "$ffmpegPath -i ${sourceFile.absolutePath} ${gifFile.absolutePath}"

try {
val process = Runtime.getRuntime().exec(cmd)
process.waitFor()
if (process.exitValue() != 0) {
return null
}
return gifFile
} catch (e: IOException) {
logger.error("Failed to execute FFmpeg: ${e.message}")
return null
} catch (e: InterruptedException) {
logger.error("FFmpeg execution interrupted: ${e.message}")
return null
}
}

private fun readFile(file: File): ByteArray? {
if (!file.exists() || !file.isFile || file.length() > 20971520) {
return null
}
return try {
Files.readAllBytes(file.toPath())
} catch (e: IOException) {
logger.error("Failed to read file: ${e.message}")
null
}
}
2 changes: 1 addition & 1 deletion src/main/kotlin/command/download/VideoDownload.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fun downloadVideo(videoUrl: String): String? {
videoByte = re.findAll(it).toList()[0].value.split(" ")[0].toInt()
// 判断视频是否小于20MB,20971520 = 20 * 20 * 1024
if (videoByte < 20971520) {
println("video < 20MB")
logger.info("video < 20MB")
val tempFile = File.createTempFile("video", "")
Runtime.getRuntime().exec(
"${configCache!!.youget_path} --no-caption " +
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/command/net/ShotCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ suspend fun shotWeb(url: String, w: Int, h: Int): ByteArray? {
}

fun checkUrl(url: String?): Boolean {
return url?.matches("[a-zA-z]+://[^\\s]*".toRegex()) ?: false
return url?.matches("[a-zA-z]+://\\S*".toRegex()) ?: false
}

suspend fun shotCommand(bot: Bot, update: Update, args: List<String>) {
Expand Down Expand Up @@ -100,7 +100,7 @@ suspend fun shotCommand(bot: Bot, update: Update, args: List<String>) {
replyMarkup = deleteButton(message.from!!.id)
).fold({}, {
it.exception?.printStackTrace()
println(it.errorBody)
logger.error(it.errorBody.toString())
})
bot.deleteMessage(chatId = ChatId.fromId(message.chat.id), messageId = editMessageId)
StatusLock.freeze(lockCode)
Expand Down
1 change: 0 additions & 1 deletion src/main/kotlin/command/rawtext/LunarCommand.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ object LunarCommand {
}

fun lunarHandler(bot: Bot, update: Update) {
// println(lunarInfo())
bot.sendMessage(
chatId = ChatId.fromId(update.message!!.chat.id),
text = lunarInfo(),
Expand Down
5 changes: 4 additions & 1 deletion src/main/kotlin/main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ import io.ktor.server.routing.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import mu.KotlinLogging
import kotlin.system.exitProcess

private val logger = KotlinLogging.logger {}

// ANTI WINDOWS AND FUCK MICROSOFT
fun init(): Boolean {
return EnvironmentStatus.check()
Expand Down Expand Up @@ -101,7 +104,7 @@ fun main() {
callbackQuery { CoroutineScope(Dispatchers.IO).launch { callbackMethod(bot, this@callbackQuery.update) } }

telegramError {
println(error.getErrorMessage())
logger.error(error.getErrorMessage())
}
}
}
Expand Down

0 comments on commit d094fca

Please sign in to comment.