| 1 |
%% Feel free to use, reuse and abuse the code in this file. |
| 2 |
|
| 3 |
%% @doc Directory handler. |
| 4 |
-module(directory_h). |
| 5 |
|
| 6 |
%% REST Callbacks |
| 7 |
-export([init/2]). |
| 8 |
-export([allowed_methods/2]). |
| 9 |
-export([resource_exists/2]). |
| 10 |
-export([content_types_provided/2]). |
| 11 |
-export([charsets_provided/2]). |
| 12 |
|
| 13 |
%% Callback Callbacks |
| 14 |
-export([list_json/2]). |
| 15 |
-export([list_html/2]). |
| 16 |
|
| 17 |
init(Req, Paths) -> |
| 18 |
{cowboy_rest, Req, Paths}. |
| 19 |
|
| 20 |
allowed_methods(Req, State) -> |
| 21 |
{[<<"GET">>], Req, State}. |
| 22 |
|
| 23 |
resource_exists(Req, {ReqPath, FilePath}) -> |
| 24 |
case file:list_dir(FilePath) of |
| 25 |
{ok, Fs} -> {true, Req, {ReqPath, lists:sort(Fs)}}; |
| 26 |
_Err -> {false, Req, {ReqPath, FilePath}} |
| 27 |
end. |
| 28 |
|
| 29 |
content_types_provided(Req, State) -> |
| 30 |
{[ |
| 31 |
{{<<"text">>, <<"html">>, []}, list_html}, |
| 32 |
{{<<"application">>, <<"json">>, []}, list_json} |
| 33 |
], Req, State}. |
| 34 |
|
| 35 |
charsets_provided(Req, State) -> |
| 36 |
{[<<"utf-8">>], Req, State}. |
| 37 |
|
| 38 |
list_json(Req, {Path, Fs}) -> |
| 39 |
Files = [unicode:characters_to_binary(F) || F <- Fs], |
| 40 |
{json:encode(Files), Req, Path}. |
| 41 |
|
| 42 |
list_html(Req, {Path, Fs}) -> |
| 43 |
Body = [[links(Path, unicode:characters_to_binary(F)) || F <- [".."|Fs]]], |
| 44 |
HTML = [<<"<!DOCTYPE html><html><head><title>Index</title></head>", |
| 45 |
"<body>">>, Body, <<"</body></html>\n">>], |
| 46 |
{HTML, Req, Path}. |
| 47 |
|
| 48 |
links(<<>>, "..") -> |
| 49 |
"<a href='/..'>..</a><br>\n"; |
| 50 |
links(Prefix, "..") -> |
| 51 |
Tokens = string:tokens(binary_to_list(Prefix), "/"), |
| 52 |
Back = lists:join("/", lists:reverse(tl(lists:reverse(Tokens)))), |
| 53 |
["<a href='/../", Back, "'>..</a><br>\n"]; |
| 54 |
links(<<>>, File) -> |
| 55 |
["<a href='/", File, "'>", File, "</a><br>\n"]; |
| 56 |
links(Prefix, File) -> |
| 57 |
["<a href='/", Prefix, File, "'>", File, "</a><br>\n"]. |