From 88394d4636a73d1054e2566f94151f753f7067b2 Mon Sep 17 00:00:00 2001 From: Alex Ling Date: Thu, 10 Sep 2020 13:16:10 +0000 Subject: [PATCH] Expose page ratios through API --- shard.lock | 4 ++++ shard.yml | 2 ++ src/library/entry.cr | 27 +++++++++++++++++++++++++++ src/routes/api.cr | 23 +++++++++++++++++++++++ 4 files changed, 56 insertions(+) diff --git a/shard.lock b/shard.lock index 10cf827..3476d56 100644 --- a/shard.lock +++ b/shard.lock @@ -32,6 +32,10 @@ shards: github: mamantoha/http_proxy version: 0.7.1 + image_size: + github: hkalexling/image_size.cr + version: 0.1.1 + kemal: github: kemalcr/kemal version: 0.26.1 diff --git a/shard.yml b/shard.yml index 3563d7a..8e9dd71 100644 --- a/shard.yml +++ b/shard.yml @@ -34,3 +34,5 @@ dependencies: github: kostya/myhtml http_proxy: github: mamantoha/http_proxy + image_size: + github: hkalexling/image_size.cr diff --git a/src/library/entry.cr b/src/library/entry.cr index ba4b84a..1f06e70 100644 --- a/src/library/entry.cr +++ b/src/library/entry.cr @@ -1,3 +1,5 @@ +require "image_size" + class Entry property zip_path : String, book : Title, title : String, size : String, pages : Int32, id : String, encoded_path : String, @@ -99,6 +101,31 @@ class Entry img end + def page_aspect_ratios + ratios = [] of Float64 + ArchiveFile.open @zip_path do |file| + file.entries + .select { |e| + SUPPORTED_IMG_TYPES.includes? \ + MIME.from_filename? e.filename + } + .sort { |a, b| + compare_numerically a.filename, b.filename + } + .each_with_index do |e, i| + begin + data = file.read_entry(e).not_nil! + size = ImageSize.get data + ratios << size.height / size.width + rescue + Logger.warn "Failed to read page #{i} of entry #{@id}" + ratios << 1_f64 + end + end + end + ratios + end + def next_entry(username) entries = @book.sorted_entries username idx = entries.index self diff --git a/src/routes/api.cr b/src/routes/api.cr index a6fb51a..b8bd5db 100644 --- a/src/routes/api.cr +++ b/src/routes/api.cr @@ -332,5 +332,28 @@ class APIRouter < Router }.to_json end end + + get "/api/ratios/:tid/:eid" do |env| + begin + tid = env.params.url["tid"] + eid = env.params.url["eid"] + + title = @context.library.get_title tid + raise "Title ID `#{tid}` not found" if title.nil? + entry = title.get_entry eid + raise "Entry ID `#{eid}` of `#{title.title}` not found" if entry.nil? + + ratios = entry.page_aspect_ratios + send_json env, { + "success" => true, + "ratios" => ratios, + }.to_json + rescue e + send_json env, { + "success" => false, + "error" => e.message, + }.to_json + end + end end end