Mercurial > prosody-modules
comparison mod_http_dir_index/http_dir_index/mod_http_dir_index.lua @ 886:1647b4fac445
mod_http_dir_index: Add. Handle generation of directory listings for mod_http_files. Included icons from the Tango project are Public Domain
| author | Kim Alvefur <zash@zash.se> |
|---|---|
| date | Sun, 23 Dec 2012 15:36:33 +0100 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 885:292ea8df7267 | 886:1647b4fac445 |
|---|---|
| 1 -- Prosody IM | |
| 2 -- Copyright (C) 2012 Kim Alvefur | |
| 3 -- | |
| 4 -- This project is MIT/X11 licensed. Please see the | |
| 5 -- COPYING file in the source package for more information. | |
| 6 -- | |
| 7 | |
| 8 module:set_global(); | |
| 9 local server = require"net.http.server"; | |
| 10 local lfs = require "lfs"; | |
| 11 local stat = lfs.attributes; | |
| 12 local build_path = require"socket.url".build_path; | |
| 13 local base64_encode = require"util.encodings".base64.encode; | |
| 14 local tag = require"util.stanza".stanza; | |
| 15 local template = require"util.template"; | |
| 16 | |
| 17 local function get_resource(resource) | |
| 18 local fh = assert(module:load_resource(resource)); | |
| 19 local data = fh:read"*a"; | |
| 20 fh:close(); | |
| 21 return data; | |
| 22 end | |
| 23 | |
| 24 local dir_index_template = template(get_resource("resources/template.html")); | |
| 25 local style = get_resource("resources/style.css"):gsub("url%((.-)%)", function(url) | |
| 26 --module:log("debug", "Inlineing %s", url); | |
| 27 return "url(data:image/png;base64,"..base64_encode(get_resource("resources/"..url))..")"; | |
| 28 end); | |
| 29 | |
| 30 local function generate_directory_index(path, full_path) | |
| 31 local filelist = tag("ul", { class = "filelist" } ):text"\n"; | |
| 32 if path ~= "/" then | |
| 33 filelist:tag("li", { class = "parent directory" }) | |
| 34 :tag("a", { href = "..", rel = "up" }):text("Parent Directory"):up():up():text"\n" | |
| 35 end | |
| 36 for file in lfs.dir(full_path) do | |
| 37 if file:sub(1,1) ~= "." then | |
| 38 local attr = stat(full_path..file) or {}; | |
| 39 local path = { file }; | |
| 40 path.is_directory = attr.mode == "directory"; | |
| 41 filelist:tag("li", { class = attr.mode }) | |
| 42 :tag("a", { href = build_path(path) }):text(file):up() | |
| 43 :up():text"\n"; | |
| 44 end | |
| 45 end | |
| 46 return "<!DOCTYPE html>\n"..tostring(dir_index_template.apply{ | |
| 47 path = path, | |
| 48 style = style, | |
| 49 filelist = filelist, | |
| 50 footer = "Prosody "..prosody.version, | |
| 51 }); | |
| 52 end | |
| 53 | |
| 54 module:hook_object_event(server, "directory-index", function (event) | |
| 55 local ok, data = pcall(generate_directory_index, event.path, event.full_path); | |
| 56 if ok then return data end | |
| 57 module:log("warn", data); | |
| 58 end); |
