65 lines
2.1 KiB
Kotlin
65 lines
2.1 KiB
Kotlin
package util
|
|
|
|
import java.net.URI
|
|
import java.net.http.HttpClient
|
|
import java.net.http.HttpRequest
|
|
import java.net.http.HttpResponse
|
|
import java.net.HttpCookie
|
|
import java.net.CookieHandler
|
|
import java.net.CookieManager
|
|
import java.net.ConnectException
|
|
import java.time.Duration
|
|
import io.github.cdimascio.dotenv.dotenv
|
|
|
|
class InputDownloader {
|
|
fun getInput(day: Int): String {
|
|
val dotenv = dotenv()
|
|
val sessionCookie = HttpCookie("session", dotenv["AOC_TOKEN"]);
|
|
sessionCookie.path = "/"
|
|
sessionCookie.version = 0
|
|
|
|
val manager = CookieManager()
|
|
manager.getCookieStore().add(URI("https://adventofcode.com"), sessionCookie)
|
|
|
|
val client = HttpClient.newBuilder()
|
|
.cookieHandler(manager)
|
|
.connectTimeout(Duration.ofSeconds(10))
|
|
.build()
|
|
|
|
val request = HttpRequest.newBuilder()
|
|
.uri(URI.create("https://adventofcode.com/2024/day/$day/input"))
|
|
.GET()
|
|
.build()
|
|
|
|
val res = client.send(request, HttpResponse.BodyHandlers.ofString())
|
|
if (res.statusCode() == 403) {
|
|
throw ConnectException("Failed to download input for day $day. Is your session token correct?")
|
|
}
|
|
if (res.statusCode() != ) {
|
|
throw ConnectException("Failed to download input for day $day. Is the day open yet?")
|
|
}
|
|
|
|
return res.body().trim()
|
|
}
|
|
|
|
fun getExample(day: Int): String {
|
|
val client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()
|
|
|
|
val req = HttpRequest.newBuilder()
|
|
.uri(URI("https://adventofcode.com/2024/day/$day"))
|
|
.GET()
|
|
.build()
|
|
|
|
val res = client.send(req, HttpResponse.BodyHandlers.ofString())
|
|
if (res.statusCode() != 200) {
|
|
throw ConnectException("Failed to download example for day $day. Is the day open yet?")
|
|
}
|
|
|
|
val bod = res.body()
|
|
val start = bod.indexOf("<pre><code>")
|
|
val stop = bod.indexOf("</code></pre>")
|
|
val sliced = bod.substring(start + 11..<stop)
|
|
return sliced.trim()
|
|
}
|
|
}
|