73 lines
2.1 KiB
Lua
73 lines
2.1 KiB
Lua
local sql = require("lsqlite3")
|
|
local zlib = require("zlib")
|
|
|
|
local db = require("db")
|
|
local queries = require("queries")
|
|
local util = require("util")
|
|
local pages = require("pages")
|
|
local api = require("hooks")
|
|
|
|
local stmnt_download
|
|
local oldconfigure = configure
|
|
function configure(...)
|
|
stmnt_download = assert(db.conn:prepare(queries.select_download))
|
|
return oldconfigure(...)
|
|
end
|
|
|
|
local oldget = api.get.page_reader
|
|
api.get.page_reader = function(env)
|
|
local ret = oldget(env)
|
|
local button = {
|
|
endpoint = string.format("https://%s/_download",env.domain),
|
|
method = "GET",
|
|
fields = {
|
|
story = env.short,
|
|
},
|
|
text = "Download TXT"
|
|
}
|
|
if env.unlisted then
|
|
button.fields.pwd = env.hashstr
|
|
end
|
|
table.insert(ret,button)
|
|
return ret
|
|
end
|
|
|
|
local function download_get(req)
|
|
local host = http_request_get_host(req)
|
|
local path = http_request_get_path(req)
|
|
http_request_populate_qs(req)
|
|
local story = assert(http_argument_get_string(req,"story"))
|
|
local hashstr = http_argument_get_string(req,"pwd")
|
|
local ihash = hashstr and util.decode_unlisted(hashstr)
|
|
story = util.decodeentities(story)
|
|
local story_id = util.decode_id(story)
|
|
stmnt_download:bind_names{
|
|
postid = story_id
|
|
}
|
|
local err = db.do_sql(stmnt_download)
|
|
if err == sql.DONE then
|
|
--No rows, story not found
|
|
http_response(req,404,pages.nostory{path=story})
|
|
stmnt_download:reset()
|
|
return
|
|
end
|
|
assert(err == sql.ROW, "after doing download sql, result was not a row, was:" .. tostring(err))
|
|
local txt_compressed, title, unlisted, hash = unpack(stmnt_download:get_values())
|
|
unlisted = unlisted == 1
|
|
if unlisted and hash ~= ihash then
|
|
--Unlisted and hash was incorrect, pretend we don't have it
|
|
http_response(req,404,pages.nostory{path=story})
|
|
stmnt_download:reset()
|
|
return
|
|
end
|
|
local text = zlib.decompress(txt_compressed)
|
|
stmnt_download:reset()
|
|
http_response_header(req,"Content-Type","application/octet-stream")
|
|
local nicetitle = title:gsub("%W","_")
|
|
http_response_header(req,"Content-Disposition","attachment; filename=\"" .. nicetitle .. ".txt\"")
|
|
http_response(req,200,text)
|
|
|
|
end
|
|
|
|
return download_get
|