Use json builder in src/library.cr instead of json mapping

This commit is contained in:
Alex Ling 2020-03-14 23:58:49 +00:00
parent 8c7ced87f1
commit 82fb45b242

View File

@ -14,7 +14,7 @@ struct Image
end
class Entry
JSON.mapping zip_path: String, book_title: String, title: String,
property zip_path : String, book_title : String, title : String,
size : String, pages : Int32, cover_url : String, id : String,
title_id : String, encoded_path : String, encoded_title : String,
mtime : Time
@ -37,6 +37,19 @@ class Entry
@cover_url = "/api/page/#{@title_id}/#{@id}/1"
@mtime = File.info(@zip_path).modification_time
end
def to_json(json : JSON::Builder)
json.object do
{% for str in ["zip_path", "book_title", "title", "size",
"cover_url", "id", "title_id", "encoded_path",
"encoded_title"] %}
json.field {{str}}, @{{str.id}}
{% end %}
json.field "pages" {json.number @pages}
json.field "mtime" {json.number @mtime.to_unix}
end
end
def read_page(page_num)
Zip::File.open @zip_path do |file|
page = file.entries
@ -60,10 +73,11 @@ class Entry
end
class Title
JSON.mapping dir: String, titles: Array(Title), entries: Array(Entry),
property dir : String, titles : Array(Title), entries : Array(Entry),
title : String, id : String, encoded_title : String, mtime : Time,
logger : MLogger
def initialize(dir : String, storage, @logger : MLogger)
@dir = dir
@id = storage.get_id @dir, true
@ -96,6 +110,22 @@ class Title
mtimes += @titles.map{|e| e.mtime}
@mtime = mtimes.max
end
def to_json(json : JSON::Builder)
json.object do
{% for str in ["dir", "title", "id", "encoded_title"] %}
json.field {{str}}, @{{str.id}}
{% end %}
json.field "mtime" {json.number @mtime.to_unix}
json.field "titles" do
json.raw @titles.to_json
end
json.field "entries" do
json.raw @entries.to_json
end
end
end
# When downloading from MangaDex, the zip/cbz file would not be valid
# before the download is completed. If we scan the zip file,
# Entry.new would throw, so we use this method to check before
@ -187,7 +217,7 @@ class TitleInfo
end
class Library
JSON.mapping dir: String, titles: Array(Title), scan_interval: Int32,
property dir : String, titles : Array(Title), scan_interval : Int32,
logger : MLogger, storage : Storage
def initialize(@dir, @scan_interval, @logger, @storage)
@ -206,6 +236,14 @@ class Library
end
end
end
def to_json(json : JSON::Builder)
json.object do
json.field "dir", @dir
json.field "titles" do
json.raw @titles.to_json
end
end
end
def get_title(tid)
# top level
title = @titles.find { |t| t.id == tid }