smr/src/lua/endpoints/index_get.lua

101 lines
2.6 KiB
Lua

local sql = require("lsqlite3")
local cache = require("cache")
local queries = require("queries")
local db = require("db")
local util = require("util")
local config = require("config")
local pages = require("pages")
local libtags = require("tags")
local stmnt_index, stmnt_author, stmnt_author_bio
local oldconfigure = configure
function configure(...)
stmnt_index = assert(db.conn:prepare(queries.select_site_index))
--TODO: actually let authors edit their bio
stmnt_author_bio = assert(db.conn:prepare([[
SELECT authors.biography FROM authors WHERE authors.name = :author;
]]))
stmnt_author = assert(db.conn:prepare(queries.select_author_index))
return oldconfigure(...)
end
local function get_site_home(req)
log(LOG_DEBUG,"Cache miss, rendering site index")
stmnt_index:bind_names{}
local latest = {}
for tagsr, idr, title, iar, dater, author in util.sql_rows(stmnt_index) do
table.insert(latest,{
url = util.encode_id(idr),
title = title,
isanon = tonumber(iar) == 1,
posted = os.date("%B %d %Y",tonumber(dater)),
author = author,
tags = libtags.get(tagsr),
})
end
return pages.index{
domain = config.domain,
stories = latest
}
end
local function get_author_home(req)
local host = http_request_get_host(req)
local subdomain = host:match("([^\\.]+)")
stmnt_author_bio:bind_names{author=subdomain}
local err = util.do_sql(stmnt_author_bio)
if err == sql.DONE then
log(LOG_INFO,"No such author:" .. subdomain)
stmnt_author_bio:reset()
return pages.noauthor{
author = subdomain
}
end
assert(err == sql.ROW,"failed to get author:" .. subdomain .. " error:" .. tostring(err))
local data = stmnt_author_bio:get_values()
local bio = data[1]
stmnt_author_bio:reset()
stmnt_author:bind_names{author=subdomain}
local stories = {}
for id, title, time in util.sql_rows(stmnt_author) do
table.insert(stories,{
url = util.encode_id(id),
title = title,
posted = os.date("%B %d %Y",tonumber(time)),
tags = libtags.get(id),
})
end
return pages.author_index{
domain=config.domain,
author=subdomain,
stories=stories,
bio=bio
}
end
local function index_get(req)
local method = http_method_text(req)
local host = http_request_get_host(req)
local subdomain = host:match("([^\\.]+)")
local text
if host == config.domain then
--Default home page
local cachepath = string.format("%s",config.domain)
text = cache.render(cachepath, function()
return get_site_home(req)
end)
else
--author home page
local cachepath = string.format("%s.%s",subdomain,config.domain)
text = cache.render(cachepath, function()
return get_author_home(req)
end)
end
assert(text)
http_response(req,200,text)
end
return index_get