Implement caching
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -5,3 +5,4 @@
|
||||
build
|
||||
|
||||
.env
|
||||
.aoc_cache
|
||||
|
@@ -9,10 +9,17 @@ import java.net.CookieHandler
|
||||
import java.net.CookieManager
|
||||
import java.net.ConnectException
|
||||
import java.time.Duration
|
||||
import java.io.File
|
||||
import io.github.cdimascio.dotenv.dotenv
|
||||
import kotlin.text.trim
|
||||
|
||||
class InputDownloader {
|
||||
fun getInput(day: Int): String {
|
||||
val cache = readCache(day, false)
|
||||
if (cache != null) {
|
||||
return cache.trim()
|
||||
}
|
||||
|
||||
val dotenv = dotenv()
|
||||
val sessionCookie = HttpCookie("session", dotenv["AOC_TOKEN"]);
|
||||
sessionCookie.path = "/"
|
||||
@@ -39,10 +46,16 @@ class InputDownloader {
|
||||
throw ConnectException("Failed to download input for day $day. Is the day open yet?")
|
||||
}
|
||||
|
||||
writeCache(day, false, res.body())
|
||||
return res.body().trim()
|
||||
}
|
||||
|
||||
fun getExample(day: Int): String {
|
||||
val cache = readCache(day, true)
|
||||
if (cache != null) {
|
||||
return cache.trim()
|
||||
}
|
||||
|
||||
val client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()
|
||||
|
||||
val req = HttpRequest.newBuilder()
|
||||
@@ -59,6 +72,27 @@ class InputDownloader {
|
||||
val start = bod.indexOf("<pre><code>")
|
||||
val stop = bod.indexOf("</code></pre>")
|
||||
val sliced = bod.substring(start + 11..<stop)
|
||||
writeCache(day, true, sliced)
|
||||
return sliced.trim()
|
||||
}
|
||||
|
||||
fun readCache(day: Int, example: Boolean): String? {
|
||||
val cacheFileName = "./.aoc_cache/day_$day/" + if (example) { "example.txt" } else { "solution.txt" }
|
||||
var cacheFile = File(cacheFileName)
|
||||
if (!cacheFile.exists()) {
|
||||
return null
|
||||
}
|
||||
|
||||
val inputStream = cacheFile.inputStream()
|
||||
val cacheString = inputStream.bufferedReader().use { it.readText() }
|
||||
return cacheString
|
||||
}
|
||||
|
||||
fun writeCache(day: Int, example: Boolean, str: String) {
|
||||
val cacheFileName = "./.aoc_cache/day_$day/"
|
||||
File(cacheFileName).mkdirs()
|
||||
var cacheFile = File(cacheFileName + if (example) { "example.txt" } else { "solution.txt" })
|
||||
|
||||
cacheFile.writeText(str)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user