Migrate EHentaiThrottleManager from Longs to durations

This commit is contained in:
Jobobby04 2021-12-25 12:07:09 -05:00
parent 999e944c34
commit 9e9fa80450
2 changed files with 15 additions and 11 deletions

View File

@ -1,18 +1,21 @@
package exh.eh package exh.eh
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class EHentaiThrottleManager( class EHentaiThrottleManager(
private val max: Int = THROTTLE_MAX, private val max: Duration = THROTTLE_MAX,
private val inc: Int = THROTTLE_INC private val inc: Duration = THROTTLE_INC
) { ) {
private var lastThrottleTime: Long = 0 private var lastThrottleTime = Duration.ZERO
var throttleTime: Long = 0 var throttleTime = Duration.ZERO
private set private set
suspend fun throttle() { suspend fun throttle() {
// Throttle requests if necessary // Throttle requests if necessary
val now = System.currentTimeMillis() val now = System.currentTimeMillis().milliseconds
val timeDiff = now - lastThrottleTime val timeDiff = now - lastThrottleTime
if (timeDiff < throttleTime) { if (timeDiff < throttleTime) {
delay(throttleTime - timeDiff) delay(throttleTime - timeDiff)
@ -22,16 +25,16 @@ class EHentaiThrottleManager(
throttleTime += inc throttleTime += inc
} }
lastThrottleTime = System.currentTimeMillis() lastThrottleTime = System.currentTimeMillis().milliseconds
} }
fun resetThrottle() { fun resetThrottle() {
lastThrottleTime = 0 lastThrottleTime = Duration.ZERO
throttleTime = 0 throttleTime = Duration.ZERO
} }
companion object { companion object {
const val THROTTLE_MAX = 5500 val THROTTLE_MAX = 5.5.seconds
const val THROTTLE_INC = 20 val THROTTLE_INC = 20.milliseconds
} }
} }

View File

@ -39,6 +39,7 @@ import okhttp3.Request
import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy import uy.kohesive.injekt.injectLazy
import kotlin.time.Duration.Companion.seconds
class FavoritesSyncHelper(val context: Context) { class FavoritesSyncHelper(val context: Context) {
private val db: DatabaseHelper by injectLazy() private val db: DatabaseHelper by injectLazy()
@ -426,7 +427,7 @@ class FavoritesSyncHelper(val context: Context) {
} }
companion object { companion object {
private const val THROTTLE_WARN = 1000 private val THROTTLE_WARN = 1.seconds
} }
} }