-module(cowboy_dirindex_handler).
-export([init/2, handle/2, terminate/3]).
-define(ROOT_DIR, "public"). % Can be overridden by application environment
init(_Req, State) ->
{cowboy_rest, undefined, State}.
handle(Req, State) ->
% Retrieve root directory from application environment
{ok, RootDir} = application:get_env(cowboy_dirindex, root_dir),
{ok, Path} = cowboy_req:binding(path, Req),
FullPath = filename:join(RootDir, Path),
case is_valid_path(FullPath, RootDir) of
true ->
case filelib:is_dir(FullPath) of
true ->
Files = get_directory_listing(FullPath, Path),
Html = generate_html(Files, Path),
{ok, Req2} = cowboy_req:reply(200,
#{<<"content-type">> => <<"text/html; charset=utf-8">>},
Html,
Req),
{ok, Req2, State};
false ->
% Serve static file
{ok, Req2} = cowboy_req:reply(200,
#{<<"content-type">> => mime_type(FullPath)},
{file, FullPath},
Req),
{ok, Req2, State}
end;
false ->
{ok, Req2} = cowboy_req:reply(403,
#{},
<<"Forbidden">>,
Req),
{ok, Req2, State}
end.
terminate(_Reason, _Req, _State) ->
ok.
is_valid_path(Path, RootDir) ->
% Normalize paths and ensure Path is within RootDir
NormPath = filename:absname(Path),
NormRootDir = filename:absname(RootDir),
lists:prefix(NormRootDir, NormPath).
get_directory_listing(FullPath, Path) ->
case file:list_dir(FullPath) of
{ok, Entries} ->
% Sort entries, put directories first
{Dirs, Files} = lists:partition(fun(E) ->
filelib:is_dir(filename:join(FullPath, E))
end, Entries),
lists:sort(Dirs) ++ lists:sort(Files);
{error, _} -> []
end.
generate_html(Files, Path) ->
Header = [
<<"<!DOCTYPE html>">>,
<<"<html><head>">>,
<<"<title>Index of ">>, Path, <<"</title>">>,
<<"<style>">>,
<<"body { font-family: monospace; }">>,
<<"a { text-decoration: none; color: blue; }">>,
<<"a:hover { text-decoration: underline; }">>,
<<"</style>">>,
<<"</head><body>">>,
<<"<h1>Index of ">>, Path, <<"</h1>">>,
<<"<hr/>">>
],
FileLinks = lists:map(fun(File) ->
LinkPath = filename:join(Path, File),
[
<<"<a href='/">>, LinkPath, <<"'>">>,
File,
<<"</a><br/>">>
]
end, Files),
Footer = [
<<"<hr/>">>,
<<"<small>Powered by Cowboy Directory Index</small>">>,
<<"</body></html>">>
],
iolist_to_binary([Header, FileLinks, Footer]).
mime_type(Path) ->
% Basic MIME type detection
Ext = filename:extension(Path),
case Ext of
".html" -> <<"text/html">>;
".txt" -> <<"text/plain">>;
".css" -> <<"text/css">>;
".js" -> <<"application/javascript">>;
".json" -> <<"application/json">>;
".png" -> <<"image/png">>;
".jpg" -> <<"image/jpeg">>;
".gif" -> <<"image/gif">>;
_ -> <<"application/octet-stream">>
end.