Fix to copy to FileChannel directly

This commit is contained in:
GG Bond authored and Vladimir Dostoyevskiy committed 2023-12-04 20:30:24 +08:00
1 parent 145cd7a7c0
commit 1d2a2a3608
3 files changed
+13 -18

No files matched your search

@@ -24,13 +24,11 @@ import com.hippo.ehviewer.R
import com.hippo.ehviewer.util.AppConfig
import com.hippo.ehviewer.util.FileUtils
import com.hippo.ehviewer.util.StatusCodeException
import com.hippo.ehviewer.util.copyTo
import io.ktor.client.HttpClient
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.isSuccess
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.close
import io.ktor.utils.io.copyTo
import java.io.File
import java.nio.charset.StandardCharsets
import kotlinx.coroutines.CoroutineScope
@@ -183,12 +181,7 @@ object EhTagDatabase : CoroutineScope {
runCatching {
client.prepareGet(url).execute {
if (it.status.isSuccess()) {
val channel = file.writeChannel()
try {
it.bodyAsChannel().copyTo(channel)
} finally {
channel.close()
}
it.bodyAsChannel().copyTo(file)
} else {
throw StatusCodeException(it.status.value)
}
@@ -4,13 +4,11 @@ import com.hippo.ehviewer.BuildConfig
import com.hippo.ehviewer.EhApplication.Companion.ktorClient
import com.hippo.ehviewer.Settings
import com.hippo.ehviewer.client.executeAndParseAs
import com.hippo.ehviewer.util.copyTo
import io.ktor.client.request.header
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.client.statement.bodyAsText
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.close
import io.ktor.utils.io.copyTo
import io.ktor.utils.io.jvm.javaio.toInputStream
import java.io.File
import java.util.zip.ZipInputStream
@@ -81,12 +79,7 @@ object AppUpdater {
}
}
} else {
val channel = file.writeChannel()
try {
response.bodyAsChannel().copyTo(channel)
} finally {
channel.close()
}
response.bodyAsChannel().copyTo(file)
}
}
}
@@ -15,7 +15,10 @@
*/
package com.hippo.ehviewer.util
import io.ktor.utils.io.ByteReadChannel
import io.ktor.utils.io.jvm.nio.copyTo
import java.io.File
import java.io.RandomAccessFile
import java.util.Locale
import kotlin.math.ln
import kotlin.math.pow
@@ -153,3 +156,9 @@ object FileUtils {
return null
}
}
suspend fun ByteReadChannel.copyTo(file: File) {
RandomAccessFile(file, "rw").use {
copyTo(it.channel)
}
}