Remove kotlin.time.Duration usages (#1215)

* Remove kotlin.Duration usages

* Fix build

* update submodule console ref
This commit is contained in:
Him188 2021-04-27 11:49:30 +08:00 committed by GitHub
parent 11b62b9e23
commit 70dc0a4da6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 80 additions and 34 deletions

View File

@ -99,14 +99,18 @@ fun Project.configureKotlinTestSettings() {
}
}
val testExperimentalAnnotations = arrayOf(
"kotlin.ExperimentalUnsignedTypes",
"kotlin.time.ExperimentalTime",
"io.ktor.util.KtorExperimentalAPI",
"kotlin.io.path.ExperimentalPathApi"
)
val experimentalAnnotations = arrayOf(
"kotlin.RequiresOptIn",
"kotlin.contracts.ExperimentalContracts",
"kotlin.experimental.ExperimentalTypeInference",
"kotlin.ExperimentalUnsignedTypes",
"kotlin.time.ExperimentalTime",
"kotlin.io.path.ExperimentalPathApi",
"io.ktor.util.KtorExperimentalAPI",
"kotlinx.serialization.ExperimentalSerializationApi",
@ -135,6 +139,11 @@ fun KotlinSourceSet.configureKotlinExperimentalUsages() {
experimentalAnnotations.forEach { a ->
languageSettings.useExperimentalAnnotation(a)
}
if (name.contains("test", ignoreCase = true)) {
testExperimentalAnnotations.forEach { a ->
languageSettings.useExperimentalAnnotation(a)
}
}
}
fun Project.configureFlattenSourceSets() {

@ -1 +1 @@
Subproject commit 5e95cdd5b0f8969ac05d8924005c35d81d81314b
Subproject commit 94f54b7c6d5b44ba47d2a8a4f306f1c2ecc3956f

View File

@ -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,8 @@
package net.mamoe.mirai.contact
import net.mamoe.mirai.message.data.Message
import net.mamoe.mirai.utils.toHumanReadableString
import net.mamoe.mirai.utils.millisToHumanReadableString
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
/**
* 发送消息时消息过长抛出的异常.
@ -42,6 +41,10 @@ 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.times(1000).millisToHumanReadableString()
} seconds"
)
public inline val BotIsBeingMutedException.botMuteRemaining: Int get() = target.botMuteRemaining

View File

@ -19,6 +19,7 @@ import net.mamoe.mirai.message.data.Message
import net.mamoe.mirai.message.data.isContentEmpty
import net.mamoe.mirai.message.data.toPlainText
import kotlin.time.Duration
import kotlin.time.DurationUnit
import kotlin.time.ExperimentalTime
/**
@ -183,11 +184,12 @@ public val UserOrBot.nameCardOrNick: String
*/
@ExperimentalTime
public suspend inline fun NormalMember.mute(duration: Duration) {
require(duration.inDays <= 30) { "duration must be at most 1 month" }
require(duration.inSeconds > 0) { "duration must be greater than 0 second" }
this.mute(duration.inSeconds.toInt())
require(duration.toDouble(DurationUnit.DAYS) <= 30) { "duration must be at most 1 month" }
require(duration.toDouble(DurationUnit.SECONDS) > 0) { "duration must be greater than 0 second" }
this.mute(duration.toLong(DurationUnit.SECONDS).toInt())
}
@OptIn(ExperimentalTime::class)
@Suppress("unused")
@JvmName("mute-fcu0wV4")
@Deprecated("For binary compatibility", level = DeprecationLevel.HIDDEN)

View File

@ -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.
@ -15,6 +15,7 @@ import kotlin.time.ExperimentalTime
import kotlin.time.toDuration
internal class TimeTest {
@Suppress("DEPRECATION_ERROR")
@ExperimentalTime
@Test
fun testTimeHumanReadable() {
@ -28,4 +29,21 @@ internal class TimeTest {
println(time1.toHumanReadableString())
assertTrue { time1.toHumanReadableString() == "1d 59min 0.0s" }
}
// since 2.7
@OptIn(ExperimentalTime::class)
@Suppress("DEPRECATION_ERROR")
@Test
fun testTimeHumanReadable2() {
val time0 = (1.toDuration(DurationUnit.DAYS) +
20.toDuration(DurationUnit.HOURS) +
15.toDuration(DurationUnit.MINUTES) +
2057.toDuration(DurationUnit.MILLISECONDS)).toLongMilliseconds()
println(time0.millisToHumanReadableString())
assertTrue { time0.millisToHumanReadableString() == "1d 20h 15min 2.057s" }
val time1 = (1.toDuration(DurationUnit.DAYS) + 59.toDuration(DurationUnit.MINUTES)).toLongMilliseconds()
println(time1.millisToHumanReadableString())
assertTrue { time1.millisToHumanReadableString() == "1d 59min 0.0s" }
}
}

View File

@ -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.
@ -83,6 +83,7 @@ public inline val Int.monthsToSeconds: Long
get() = this * 30.daysToSeconds
// @MiraiExperimentalApi
@Deprecated("Do not use unstable API", level = DeprecationLevel.ERROR)
@ExperimentalTime
public fun Duration.toHumanReadableString(): String {
val days = toInt(DurationUnit.DAYS)
@ -96,3 +97,20 @@ public fun Duration.toHumanReadableString(): String {
append("${s}s")
}
}
// since 2.7
public fun Int.millisToHumanReadableString(): String = toLongUnsigned().millisToHumanReadableString()
public fun Long.millisToHumanReadableString(): String {
val days = this / 1000 / 3600 / 24
val hours = this / 1000 / 3600 % 24
val minutes = this / 1000 / 60 % 60
val s = floor(this.toDouble() / 1000 % 60 * 1000) / 1000
return buildString {
if (days != 0L) append("${days}d ")
if (hours != 0L) append("${hours}h ")
if (minutes != 0L) append("${minutes}min ")
append("${s}s")
}
}

View File

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

View File

@ -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: ScheduledJob by lazy {
ScheduledJob(bot.coroutineContext, bot.configuration.contactListCache.saveIntervalMillis.milliseconds) {
ScheduledJob(bot.coroutineContext, bot.configuration.contactListCache.saveIntervalMillis) {
runBIO { saveGroupCaches() }
}
}

View File

@ -47,8 +47,6 @@ 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
@Suppress("MemberVisibilityCanBePrivate")
internal class QQAndroidBotNetworkHandler(coroutineContext: CoroutineContext, bot: QQAndroidBot) : BotNetworkHandler() {
@ -212,8 +210,8 @@ internal class QQAndroidBotNetworkHandler(coroutineContext: CoroutineContext, bo
while (isActive) {
bot.client.wLoginSigInfo.vKey.run {
//由过期时间最短的且不会被skey更换更新的vkey计算重新登录的时间
val delay = (expireTime - creationTime).seconds - 5.minutes
logger.info { "Scheduled refresh login session in ${delay.toHumanReadableString()}." }
val delay = (expireTime - creationTime - 5).times(1000)
logger.info { "Scheduled refresh login session in ${delay.millisToHumanReadableString()}." }
delay(delay)
}
runCatching {
@ -227,8 +225,8 @@ 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()}." }
val delay = (expireTime - creationTime - 5).times(1000)
logger.info { "Scheduled key refresh in ${delay.millisToHumanReadableString()}." }
delay(delay)
}
runCatching {

View File

@ -37,7 +37,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 {
@ -157,7 +157,7 @@ internal suspend inline fun <reified R, reified IP> tryServersUpload(
}
var resp: R? = null
val time = measureTime {
val time = measureTimeMillis {
runCatching {
resp = implOnEachServer(ip, port)
}.onFailure {
@ -169,7 +169,9 @@ internal suspend inline fun <reified R, reified IP> 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.toDouble().div(1000)).roundToInt()
} KiB/s"
}
resp as R

View File

@ -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 == Duration.ZERO) {
if (intervalMillis == 0L) {
launch { task() }
} else channel.offer(Unit)
}
@ -47,11 +46,11 @@ internal class ScheduledJob(
}
init {
if (interval != Duration.ZERO) {
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()
}
}

View File

@ -17,7 +17,6 @@ import net.mamoe.mirai.internal.utils.ScheduledJob
import org.junit.jupiter.api.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.assertEquals
import kotlin.time.seconds
internal class ScheduledJobTest : AbstractTest() {
@Test
@ -27,7 +26,7 @@ internal class ScheduledJobTest : AbstractTest() {
throwable.printStackTrace()
})
val invoked = AtomicInteger(0)
val job = ScheduledJob(scope.coroutineContext, 1.seconds) {
val job = ScheduledJob(scope.coroutineContext, 1 * 1000) {
invoked.incrementAndGet()
}
delay(100)