1
1
package org.komputing.fauceth
2
2
3
- import java.net.URI
4
- import java.net.http.HttpClient
5
- import java.net.http.HttpRequest
6
- import java.net.http.HttpResponse
3
+ import kotlinx.coroutines.delay
4
+ import okhttp3.*
5
+ import java.io.IOException
7
6
import java.time.Duration
8
7
9
8
// very crude for now
10
- fun verifyCaptcha (hCaptchaResponse : String , hCaptchaSecret : String ): Boolean {
11
- val body = " response=$hCaptchaResponse &secret=$hCaptchaSecret "
9
+ suspend fun verifyCaptcha (hCaptchaResponse : String , hCaptchaSecret : String ): Boolean {
12
10
13
- val httpClient = HttpClient .newBuilder().connectTimeout(Duration .ofSeconds(5 )).build()
11
+ val client = OkHttpClient .Builder ()
12
+ .connectTimeout(Duration .ofSeconds(5 ))
13
+ .readTimeout(Duration .ofSeconds(10 ))
14
+ .build()
14
15
15
- val request = HttpRequest .newBuilder ()
16
- .uri( URI .create( " https://hcaptcha.com/siteverify" ) )
16
+ val request = Request . Builder ()
17
+ .url( " https://hcaptcha.com/siteverify" )
17
18
.header(" Content-Type" , " application/x-www-form-urlencoded" )
18
- .timeout( Duration .ofSeconds( 10 ))
19
- .POST ( HttpRequest . BodyPublishers .ofString(body)). build()
19
+ .post( FormBody . Builder ().add( " response " , hCaptchaResponse).add( " secret " , hCaptchaSecret).build( ))
20
+ .build()
20
21
21
- val response = httpClient.send(request, HttpResponse .BodyHandlers .ofString())
22
22
23
- return response.statusCode() == 200 && response.body().contains(" \" success\" :true" )
23
+ var attempts = 0
24
+
25
+ while (true ) {
26
+
27
+ try {
28
+ val response = client.newCall(request).execute()
29
+ if (response.code == 200 ) {
30
+ return (response.body?.string()?.contains(" \" success\" :true" ) == true )
31
+ }
32
+ } catch (ioe: IOException ) {
33
+ // can happen - we will retry
34
+ }
35
+
36
+ if (attempts == 3 ) return false
37
+
38
+ attempts++
39
+ delay(500L * attempts)
40
+ }
41
+
24
42
}
0 commit comments