comparison mod_http_dir_listing2/mod_http_dir_listing2.lua @ 3001:1108a40c3118

mod_http_dir_listing2: Copy of mod_http_dir_listing
author Kim Alvefur <zash@zash.se>
date Mon, 16 Apr 2018 21:03:13 +0200
parents mod_http_dir_listing/http_dir_listing/mod_http_dir_listing.lua@7dbde05b48a9
children c91c9b87929e
comparison
equal deleted inserted replaced
3000:02fc3b64cbb7 3001:1108a40c3118
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 mime = module:shared("/*/http_files/mime");
18
19 local function get_resource(resource)
20 local fh = assert(module:load_resource(resource));
21 local data = fh:read"*a";
22 fh:close();
23 return data;
24 end
25
26 local dir_index_template = template(get_resource("resources/template.html"));
27 local style = get_resource("resources/style.css"):gsub("url%((.-)%)", function(url)
28 --module:log("debug", "Inlineing %s", url);
29 return "url(data:image/png;base64,"..base64_encode(get_resource("resources/"..url))..")";
30 end);
31
32 local function generate_directory_index(path, full_path)
33 local filelist = tag("ul", { class = "filelist" } ):text"\n";
34 if path ~= "/" then
35 filelist:tag("li", { class = "parent directory" })
36 :tag("a", { href = "..", rel = "up" }):text("Parent Directory"):up():up():text"\n"
37 end
38 local mime_map = mime.types;
39 for file in lfs.dir(full_path) do
40 if file:sub(1,1) ~= "." then
41 local attr = stat(full_path..file) or {};
42 local path = { file };
43 local file_ext = file:match"%.([^.]+)$";
44 local type = attr.mode == "file" and file_ext and mime_map and mime_map[file_ext] or nil;
45 local class = table.concat({ attr.mode or "unknown", file_ext, type and type:match"^[^/]+" }, " ");
46 path.is_directory = attr.mode == "directory";
47 filelist:tag("li", { class = class })
48 :tag("a", { href = build_path(path), type = type }):text(file):up()
49 :up():text"\n";
50 end
51 end
52 return "<!DOCTYPE html>\n"..tostring(dir_index_template.apply{
53 path = path,
54 style = style,
55 filelist = filelist,
56 footer = "Prosody "..prosody.version,
57 });
58 end
59
60 module:hook_object_event(server, "directory-index", function (event)
61 local ok, data = pcall(generate_directory_index, event.path, event.full_path);
62 if ok then return data end
63 module:log("warn", data);
64 end);