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) print("Cache miss, rendering index") stmnt_index:bind_names{} local err = util.do_sql(stmnt_index) local latest = {} --err may be sql.ROW or sql.DONE if we don't have any stories yet while err == sql.ROW do local data = stmnt_index:get_values() local storytags = libtags.get(data[1]) table.insert(latest,{ url = util.encode_id(data[1]), title = data[2], isanon = data[3] == 1, posted = os.date("%B %d %Y",tonumber(data[4])), author = data[5], tags = storytags, }) err = stmnt_index:step() end stmnt_index:reset() 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 print("No such author") stmnt_author_bio:reset() return pages.noauthor{ author = subdomain } end print("err:",err) 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() print("Getting author's stories") stmnt_author:bind_names{author=subdomain} err = util.do_sql(stmnt_author) print("err:",err) local stories = {} while err == sql.ROW do local data = stmnt_author:get_values() local id, title, time = unpack(data) local tags = libtags.get(id) table.insert(stories,{ url = util.encode_id(id), title = title, posted = os.date("%B %d %Y",tonumber(time)), tags = tags, }) err = stmnt_author:step() end stmnt_author:reset() 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 path = http_request_get_path(req) --Default home page local subdomain = host:match("([^\\.]+)") local text if host == config.domain then 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