ソースを参照

Avoid using kotlin.time.Duration for binary compatibility with both Kotlin 1.4.20 and 1.4.30

Him188 5 年 前
コミット
664cbf6d03

+ 2 - 4
mirai-core-api/src/commonMain/kotlin/contact/Exceptions.kt

@@ -1,5 +1,5 @@
 /*
- * Copyright 2019-2020 Mamoe Technologies and contributors.
+ * Copyright 2019-2021 Mamoe Technologies and contributors.
  *
  *  此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  *  Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
@@ -12,9 +12,7 @@
 package net.mamoe.mirai.contact
 
 import net.mamoe.mirai.message.data.Message
-import net.mamoe.mirai.utils.toHumanReadableString
 import kotlin.time.ExperimentalTime
-import kotlin.time.seconds
 
 /**
  * 发送消息时消息过长抛出的异常.
@@ -42,6 +40,6 @@ public class MessageTooLargeException(
 @OptIn(ExperimentalTime::class)
 public class BotIsBeingMutedException(
     public val target: Group
-) : RuntimeException("bot is being muted, remaining ${target.botMuteRemaining.seconds.toHumanReadableString()} seconds")
+) : RuntimeException("bot is being muted, remaining ${target.botMuteRemaining} seconds")
 
 public inline val BotIsBeingMutedException.botMuteRemaining: Int get() = target.botMuteRemaining

+ 8 - 4
mirai-core/src/commonMain/kotlin/AbstractBot.kt

@@ -28,7 +28,6 @@ import net.mamoe.mirai.event.EventPriority.MONITOR
 import net.mamoe.mirai.event.events.BotEvent
 import net.mamoe.mirai.event.events.BotOfflineEvent
 import net.mamoe.mirai.event.events.BotReloginEvent
-import net.mamoe.mirai.internal.message.contextualBugReportException
 import net.mamoe.mirai.internal.network.BotNetworkHandler
 import net.mamoe.mirai.internal.network.DefaultServerList
 import net.mamoe.mirai.internal.network.closeAndJoin
@@ -37,8 +36,9 @@ import net.mamoe.mirai.network.LoginFailedException
 import net.mamoe.mirai.supervisorJob
 import net.mamoe.mirai.utils.*
 import kotlin.coroutines.CoroutineContext
+import kotlin.math.roundToInt
+import kotlin.system.measureTimeMillis
 import kotlin.time.ExperimentalTime
-import kotlin.time.measureTime
 
 internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
     final override val configuration: BotConfiguration,
@@ -159,10 +159,14 @@ internal abstract class AbstractBot<N : BotNetworkHandler> constructor(
 
                 bot.launch {
                     val success: Boolean
-                    val time = measureTime { success = Reconnect().reconnect(event) }
+                    val time = measureTimeMillis { success = Reconnect().reconnect(event) }
 
                     if (success) {
-                        logger.info { "Reconnected successfully in ${time.toHumanReadableString()}" }
+                        if (time >= 1000) {
+                            logger.info { "Reconnected successfully in ${(time * 100.0).roundToInt() / 100.0 / 1000}s" } // 2 s.f.
+                        } else {
+                            logger.info { "Reconnected successfully in ${time}ms" }
+                        }
                     }
                 }
             }

+ 1 - 2
mirai-core/src/commonMain/kotlin/QQAndroidBot.kt

@@ -38,7 +38,6 @@ import net.mamoe.mirai.network.LoginFailedException
 import net.mamoe.mirai.utils.*
 import kotlin.contracts.contract
 import kotlin.coroutines.CoroutineContext
-import kotlin.time.milliseconds
 
 internal fun Bot.asQQAndroidBot(): QQAndroidBot {
     contract {
@@ -103,7 +102,7 @@ internal class QQAndroidBot constructor(
 
     private val friendListSaver by lazy {
         if (!configuration.contactListCache.friendListCacheEnabled) return@lazy null
-            ScheduledJob(coroutineContext, configuration.contactListCache.saveIntervalMillis.milliseconds) {
+            ScheduledJob(coroutineContext, configuration.contactListCache.saveIntervalMillis) {
                 runBIO { saveFriendCache() }
             }
     }

+ 1 - 2
mirai-core/src/commonMain/kotlin/network/ContactListCache.kt

@@ -24,7 +24,6 @@ import net.mamoe.mirai.utils.runBIO
 import java.io.File
 import java.util.concurrent.ConcurrentHashMap
 import java.util.concurrent.ConcurrentLinkedQueue
-import kotlin.time.milliseconds
 
 internal val JsonForCache = Json {
     encodeDefaults = true
@@ -71,7 +70,7 @@ internal class GroupMemberListCaches(
 
     private val changedGroups: MutableCollection<Long> = ConcurrentLinkedQueue()
     private val groupListSaver by lazy {
-        ScheduledJob(bot.coroutineContext, bot.configuration.contactListCache.saveIntervalMillis.milliseconds) {
+        ScheduledJob(bot.coroutineContext, bot.configuration.contactListCache.saveIntervalMillis) {
             runBIO { saveGroupCaches() }
         }
     }

+ 4 - 5
mirai-core/src/commonMain/kotlin/network/handler/QQAndroidBotNetworkHandler.kt

@@ -46,8 +46,7 @@ import java.util.concurrent.ConcurrentLinkedQueue
 import kotlin.contracts.InvocationKind
 import kotlin.contracts.contract
 import kotlin.coroutines.CoroutineContext
-import kotlin.time.minutes
-import kotlin.time.seconds
+import kotlin.math.roundToInt
 
 @Suppress("MemberVisibilityCanBePrivate")
 internal class QQAndroidBotNetworkHandler(coroutineContext: CoroutineContext, bot: QQAndroidBot) : BotNetworkHandler() {
@@ -270,9 +269,9 @@ internal class QQAndroidBotNetworkHandler(coroutineContext: CoroutineContext, bo
         launch {
             while (isActive) {
                 bot.client.wLoginSigInfo.sKey.run {
-                    val delay = (expireTime - creationTime).seconds - 5.minutes
-                    logger.info { "Scheduled key refresh in ${delay.toHumanReadableString()}." }
-                    delay(delay.toLongMilliseconds()) // avoid delay(Duration) to keep binary compatibility
+                    val seconds = (expireTime - creationTime) - 5 * 60
+                    logger.info { "Scheduled key refresh in about ${(seconds / 3600.0).roundToInt()} hours." }
+                    delay(seconds * 1000)
                 }
                 runCatching {
                     refreshKeys()

+ 3 - 3
mirai-core/src/commonMain/kotlin/network/highway/Highway.kt

@@ -36,7 +36,7 @@ import java.util.concurrent.atomic.AtomicReference
 import kotlin.contracts.InvocationKind
 import kotlin.contracts.contract
 import kotlin.math.roundToInt
-import kotlin.time.measureTime
+import kotlin.system.measureTimeMillis
 
 internal object Highway {
 
@@ -139,7 +139,7 @@ internal suspend inline fun <reified R> tryServersUpload(
     }
 
     var resp: R? = null
-    val time = measureTime {
+    val time = measureTimeMillis {
         runCatching {
             resp = implOnEachServer(ip, port)
         }.onFailure {
@@ -151,7 +151,7 @@ internal suspend inline fun <reified R> tryServersUpload(
     }
 
     bot.network.logger.verbose {
-        "[${channelKind}] Uploading $resourceKind: succeed at ${(resourceSize.toDouble() / 1024 / time.inSeconds).roundToInt()} KiB/s"
+        "[${channelKind}] Uploading $resourceKind: succeed at ${(resourceSize.toDouble() / 1024 / (time / 1000.0)).roundToInt()} KiB/s"
     }
 
     resp as R

+ 5 - 6
mirai-core/src/commonMain/kotlin/utils/ScheduledJob.kt

@@ -15,12 +15,11 @@ import kotlinx.coroutines.flow.collect
 import kotlinx.coroutines.flow.receiveAsFlow
 import kotlinx.coroutines.flow.sample
 import kotlin.coroutines.CoroutineContext
-import kotlin.time.Duration
 
 @OptIn(FlowPreview::class)
 internal class ScheduledJob(
     coroutineContext: CoroutineContext,
-    val interval: Duration,
+    private val intervalMillis: Long,
     private val task: suspend () -> Unit
 ) : CoroutineScope by CoroutineScope(coroutineContext + SupervisorJob(coroutineContext[Job])) {
     private val coroutineExceptionHandler =
@@ -33,7 +32,7 @@ internal class ScheduledJob(
     private val channel = Channel<Unit>(Channel.CONFLATED)
 
     fun notice() {
-        if (interval.toLongMilliseconds() != 0L) { // Avoid Duration.ZERO for binary compatibility
+        if (intervalMillis == 0L) {
             launch { task() }
         } else channel.offer(Unit)
     }
@@ -47,11 +46,11 @@ internal class ScheduledJob(
     }
 
     init {
-        if (interval.toLongMilliseconds() != 0L) { // Avoid Duration.ZERO for binary compatibility
+        if (intervalMillis != 0L) {
             launch {
                 channel.receiveAsFlow()
                     .runCatching {
-                        sample(interval.toLongMilliseconds())
+                        sample(intervalMillis)
                     }
                     .fold(
                         onSuccess = { flow ->
@@ -60,7 +59,7 @@ internal class ScheduledJob(
                         onFailure = {
                             // binary change
                             while (isActive) {
-                                delay(interval)
+                                delay(intervalMillis)
                                 task()
                             }
                         }

+ 1 - 2
mirai-core/src/commonTest/kotlin/ScheduledJobTest.kt

@@ -15,7 +15,6 @@ import kotlinx.coroutines.runBlocking
 import org.junit.jupiter.api.Test
 import java.util.concurrent.atomic.AtomicInteger
 import kotlin.test.assertEquals
-import kotlin.time.seconds
 
 internal class ScheduledJobTest {
     @Test
@@ -25,7 +24,7 @@ internal class ScheduledJobTest {
                 throwable.printStackTrace()
             })
             val invoked = AtomicInteger(0)
-            val job = ScheduledJob(scope.coroutineContext, 1.seconds) {
+            val job = ScheduledJob(scope.coroutineContext, 1000) {
                 invoked.incrementAndGet()
             }
             delay(100)