2024-06-05 23:06:46 +00:00
|
|
|
-- parse "metadata.calibre" files
|
|
|
|
local lj = require("lunajson")
|
2024-06-06 21:56:59 +00:00
|
|
|
local rapidjson = require("rapidjson")
|
2021-01-24 12:47:52 +00:00
|
|
|
|
2024-06-05 23:06:46 +00:00
|
|
|
local array_fields = {
|
|
|
|
authors = true,
|
|
|
|
tags = true,
|
|
|
|
series = true,
|
|
|
|
}
|
2021-01-24 12:47:52 +00:00
|
|
|
|
2024-06-05 23:06:46 +00:00
|
|
|
local required_fields = {
|
|
|
|
authors = true,
|
|
|
|
last_modified = true,
|
|
|
|
lpath = true,
|
|
|
|
series = true,
|
|
|
|
series_index = true,
|
|
|
|
size = true,
|
|
|
|
tags = true,
|
|
|
|
title = true,
|
|
|
|
uuid = true,
|
|
|
|
}
|
2021-01-24 12:47:52 +00:00
|
|
|
|
2024-06-05 23:06:46 +00:00
|
|
|
local field
|
|
|
|
local t = {}
|
|
|
|
local function append(v)
|
|
|
|
-- Some fields *may* be arrays, so check whether we ran through startarray first or not
|
|
|
|
if t[field] then
|
|
|
|
table.insert(t[field], v)
|
2021-01-24 12:47:52 +00:00
|
|
|
else
|
2024-06-05 23:06:46 +00:00
|
|
|
t[field] = v
|
|
|
|
field = nil
|
2021-01-24 12:47:52 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-06-05 23:06:46 +00:00
|
|
|
local depth = 0
|
2024-06-06 21:56:59 +00:00
|
|
|
local result = rapidjson.array({})
|
2024-06-05 23:06:46 +00:00
|
|
|
local sax = {
|
|
|
|
startobject = function()
|
|
|
|
depth = depth + 1
|
|
|
|
end,
|
|
|
|
endobject = function()
|
|
|
|
if depth == 1 then
|
2024-06-06 21:56:59 +00:00
|
|
|
table.insert(result, rapidjson.object(t))
|
2024-06-05 23:06:46 +00:00
|
|
|
t = {}
|
|
|
|
end
|
|
|
|
depth = depth - 1
|
|
|
|
end,
|
|
|
|
startarray = function()
|
|
|
|
if array_fields[field] then
|
2024-06-06 21:56:59 +00:00
|
|
|
t[field] = rapidjson.array({})
|
2024-06-05 23:06:46 +00:00
|
|
|
end
|
|
|
|
end,
|
|
|
|
endarray = function()
|
|
|
|
if field then
|
|
|
|
field = nil
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
key = function(s)
|
|
|
|
if required_fields[s] then
|
|
|
|
field = s
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
string = function(s)
|
|
|
|
if field then
|
|
|
|
append(s)
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
number = function(n)
|
|
|
|
if field then
|
|
|
|
append(n)
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
boolean = function(b)
|
|
|
|
if field then
|
|
|
|
append(b)
|
|
|
|
end
|
|
|
|
end,
|
|
|
|
}
|
2021-01-24 12:47:52 +00:00
|
|
|
|
2024-06-05 23:06:46 +00:00
|
|
|
local function parse_unsafe(path)
|
|
|
|
local p = lj.newfileparser(path, sax)
|
|
|
|
p.run()
|
|
|
|
end
|
2021-01-24 12:47:52 +00:00
|
|
|
|
|
|
|
local parser = {}
|
|
|
|
|
|
|
|
function parser.parseFile(file)
|
2024-06-06 21:56:59 +00:00
|
|
|
result = rapidjson.array({})
|
2024-06-05 23:06:46 +00:00
|
|
|
local ok, err = pcall(parse_unsafe, file)
|
|
|
|
field = nil
|
|
|
|
if not ok then
|
|
|
|
return nil, err
|
2021-01-24 12:47:52 +00:00
|
|
|
end
|
2024-06-05 23:06:46 +00:00
|
|
|
return result
|
2021-01-24 12:47:52 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
return parser
|