Cleanup HttpEngineCoroutinizer

This commit is contained in:
tarsin committed 2023-06-18 15:25:19 +08:00
1 parent 0d10899417
commit fe7c979d78
2 files changed
+15 -12

No files matched your search

@@ -27,7 +27,7 @@ val cronetHttpClientExecutor = EhApplication.nonCacheOkHttpClient.dispatcher.exe
class CronetRequest {
lateinit var mConsumer: (UrlResponseInfo, ByteBuffer) -> Unit
lateinit var onResponse: (UrlResponseInfo) -> Unit
lateinit var onResponse: CronetRequest.(UrlResponseInfo) -> Unit
lateinit var request: UrlRequest
lateinit var mCont: Continuation<Boolean>
val callback = object : UrlRequest.Callback {
@@ -36,6 +36,7 @@ class CronetRequest {
}
override fun onResponseStarted(p0: UrlRequest, p1: UrlResponseInfo) {
onResponse(p1)
request.read(buffer)
}
@@ -71,12 +72,12 @@ inline fun cronetRequest(url: String, conf: UrlRequest.Builder.() -> Unit) = Cro
request = cronetHttpClient.newUrlRequestBuilder(url, cronetHttpClientExecutor, callback).apply(conf).build()
}
infix fun CronetRequest.onResponse(callback: (UrlResponseInfo) -> Unit) = apply {
onResponse = callback
infix fun CronetRequest.consumeBody(callback: (UrlResponseInfo, ByteBuffer) -> Unit) = apply {
mConsumer = callback
}
suspend inline infix fun CronetRequest.execute(noinline consumer: (UrlResponseInfo, ByteBuffer) -> Unit): Boolean {
mConsumer = consumer
suspend inline infix fun CronetRequest.execute(noinline callback: CronetRequest.(UrlResponseInfo) -> Unit): Boolean {
onResponse = callback
return suspendCancellableCoroutine { cont ->
cont.invokeOnCancellation { request.cancel() }
mCont = cont
@@ -142,16 +142,18 @@ class SpiderDen(private val mGalleryInfo: GalleryInfo) {
val path = data.toNioPath()
path.deleteIfExists()
@Suppress("BlockingMethodInNonBlockingContext")
FileChannel.open(path, StandardOpenOption.APPEND, StandardOpenOption.CREATE_NEW).use {
FileChannel.open(path, StandardOpenOption.APPEND, StandardOpenOption.CREATE_NEW).use { chan ->
cronetRequest(url) {
referer?.let { addHeader("Referer", it) }
} onResponse {
val type = it.headers.asMap["Content-Type"]?.first()?.toMediaType()?.subtype ?: "jpg"
} execute {
val headers = it.headers.asMap
val type = headers["Content-Type"]?.first()?.toMediaType()?.subtype ?: "jpg"
val length = headers["Content-Length"]!!.first().toLong()
metadata.toFile().writeText(type)
} execute { info, buffer ->
val read = it.write(buffer)
val length = info.headers.asMap["Content-Length"]!!.first().toLong()
notifyProgress(length, info.receivedByteCount, read)
consumeBody { info, buffer ->
val read = chan.write(buffer)
notifyProgress(length, info.receivedByteCount, read)
}
}
}
}