diff options
Diffstat (limited to 'src/cache.gleam')
| -rw-r--r-- | src/cache.gleam | 97 |
1 files changed, 53 insertions, 44 deletions
diff --git a/src/cache.gleam b/src/cache.gleam index ccba2a8..7e4ff21 100644 --- a/src/cache.gleam +++ b/src/cache.gleam @@ -4,6 +4,7 @@ import gleam/int import gleam/list import gleam/option.{type Option} import gleam/result +import gleam/string import image import simplifile import wisp @@ -27,53 +28,61 @@ pub fn load_themes() { }, dict.new(), fn(accumulated_themes, theme) { - dict.insert( - accumulated_themes, - theme, - list.range(0, 9) - |> list.fold(dict.new(), fn(accumulated_digits, digit) { - let path = - "./themes/" - <> theme - <> "/" - <> int.to_string(digit) - <> "." - <> case theme { - "gelbooru-h" | "moebooru-h" | "lain" | "garukura" -> "png" - _ -> "gif" - } + dict.insert(accumulated_themes, theme, load_theme(theme)) + }, + ) +} - case simplifile.read_bits(from: path) { - Ok(image_data) -> { - case image.get_image_information(image_data) { - Ok(info) -> - dict.insert( - accumulated_digits, - digit, - CachedImage( - base64: bit_array.base64_encode(image_data, False), - info: info, - ), - ) - Error(_) -> { - wisp.log_error( - "Error getting image information for " <> path, - ) +fn load_theme(theme) -> Dict(Int, CachedImage) { + let theme_directory = "./themes/" <> theme - accumulated_digits - } - } - } - Error(_) -> { - wisp.log_error("Error reading image file " <> path) + case simplifile.read_directory(theme_directory) { + Ok(files) -> + list.fold(files, dict.new(), fn(accumulated_digits, file) { + case parse_digit_filename(file) { + Ok(digit) -> + load_cached_image(theme_directory <> "/" <> file) + |> result.map(dict.insert(accumulated_digits, digit, _)) + |> result.unwrap(accumulated_digits) + Error(_) -> accumulated_digits + } + }) + Error(_) -> { + wisp.log_error("Error reading theme directory " <> theme_directory) - accumulated_digits - } - } - }), - ) - }, - ) + dict.new() + } + } +} + +fn parse_digit_filename(file) { + case string.split(file, ".") { + [digit, _extension] -> int.parse(digit) + _ -> Error(Nil) + } +} + +fn load_cached_image(path) { + case simplifile.read_bits(from: path) { + Ok(image_data) -> + case image.get_image_information(image_data) { + Ok(info) -> + Ok(CachedImage( + base64: bit_array.base64_encode(image_data, False), + info: info, + )) + Error(_) -> { + wisp.log_error("Error getting image information for " <> path) + + Error(Nil) + } + } + Error(_) -> { + wisp.log_error("Error reading image file " <> path) + + Error(Nil) + } + } } pub fn get_image(cache, theme, digit) -> Option(CachedImage) { |