/
KtorSkraperClient.kt
94 lines (87 loc) · 3.17 KB
/
KtorSkraperClient.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* Copyright (c) 2019-present Mikhael Sokolov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.sokomishalov.skraper.client.ktor
import io.ktor.client.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.HttpHeaders.UnsafeHeadersList
import io.ktor.http.HttpMethod
import io.ktor.http.content.*
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.flow.flow
import ru.sokomishalov.skraper.client.HttpRequest
import ru.sokomishalov.skraper.client.HttpResponse
import ru.sokomishalov.skraper.client.SkraperClient
import ru.sokomishalov.skraper.internal.consts.DEFAULT_CONNECTION_TIMEOUT
import ru.sokomishalov.skraper.internal.consts.DEFAULT_READ_TIMEOUT
import ru.sokomishalov.skraper.internal.nio.aWrite
import java.io.File
import io.ktor.client.statement.HttpResponse as KtorHttpResponse
class KtorSkraperClient(
private val client: HttpClient = DEFAULT_CLIENT
) : SkraperClient {
override suspend fun request(request: HttpRequest): HttpResponse {
return request
.call()
.let {
HttpResponse(
status = it.status.value,
headers = it.headers.toMap().mapValues { (_, v) -> v.toString() },
body = it.bodyAsChannel().toByteArray()
)
}
}
override suspend fun download(request: HttpRequest, destFile: File) {
request
.call()
.bodyAsChannel()
.run {
flow {
consumeEachBufferRange { buf, last ->
emit(buf)
!last
}
}
}
.aWrite(destFile)
}
private suspend fun HttpRequest.call(): KtorHttpResponse {
return client.request(urlString = url) {
method = HttpMethod.parse(this@call.method.name)
this@call.headers.filterKeys { it !in UnsafeHeadersList }.forEach { (k, v) -> header(k, v) }
this@call.body?.let {
setBody(ByteArrayContent(
bytes = it,
contentType = headers[HttpHeaders.ContentType]?.let { t -> ContentType.parse(t) }
))
}
}
}
companion object {
@JvmStatic
val DEFAULT_CLIENT: HttpClient = HttpClient {
followRedirects = true
install(HttpTimeout) {
requestTimeoutMillis = DEFAULT_READ_TIMEOUT.toMillis()
connectTimeoutMillis = DEFAULT_CONNECTION_TIMEOUT.toMillis()
}
}
}
}