-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
95 lines (81 loc) · 2.08 KB
/
app.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Before filter
before do
# Configuration
@media_path = File.expand_path(File.dirname(__FILE__) + '/media')
# No editing!
request.path_info = request.path_info.gsub(/\/+$/, '') # remove trailing slash
@abs_path = "#{@media_path}#{request.path_info}"
end
# About
get '/about' do
erb :about
end
# Folders and files
get '/*' do |path|
unless File.exists?(@abs_path)
return "#{@abs_path} does not exist!"
end
if (File.directory?(@abs_path)) then
haml :directory, :locals => {:contents => contents(path), :path => path}
else
send_file @abs_path
end
end
def contents(path)
contents = []
Dir.foreach(@abs_path) do |x|
# Skip current directory
next if (x == '.')
# Skip parent directory if at top
next if (x == '..' && @abs_path == @media_path)
# Skip .placeholder
next if (x == '.placeholder')
if (x == '..') then
contents << {
:url => '/' + File.dirname(path).gsub(/^\.$/, ''),
:abs_path => File.basename(@abs_path),
:name => '.. Parent directory',
:rel => 'parent',
:info => 'directory'
}
elsif (File.directory?("#{@abs_path}/#{x}")) then
abs_path = "#{@abs_path}/#{x}"
contents << {
:url => "/" + "#{path}/#{x}".gsub(/^\/*/, ''),
:abs_path => abs_path,
:name => File.basename(abs_path),
:rel => 'directory',
:info => 'directory'
}
else
abs_path = "#{@abs_path}/#{x}"
contents << {
:url => "/" + "#{path}/#{x}".gsub(/^\/*/, ''),
:abs_path => abs_path,
:name => File.basename(abs_path),
:rel => 'file',
:info => file_size(abs_path)
}
end
end
contents = contents.sort! do |x, y|
if (x[:rel] == 'parent') then
-1
elsif (x[:rel] == y[:rel])
x[:name] <=> y[:name]
else
x[:rel] == 'directory' ? -1 : 1
end
end
return contents
end
def file_size(path)
size = File.size(path)
if (size > 1_000_000) then
"#{size / 1_000_000} MB"
elsif (size > 1_000) then
"#{size / 1_000} KB"
else
"#{size} B"
end
end