lib: Add a tiny GNU readline wrapper
[nit.git] / lib / nitcorn / file_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Jean-Philippe Caissy <jpcaissy@piji.ca>
4 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18 # Provides the `FileServer` action, which is a standard and minimal file server
19 module file_server
20
21 import reactor
22 import sessions
23 import media_types
24 import http_errors
25
26 redef class String
27 # Returns a `String` copy of `self` without any of the prefixed '/'s
28 #
29 # Examples:
30 #
31 # assert "/home/".strip_start_slashes == "home/"
32 # assert "////home/".strip_start_slashes == "home/"
33 # assert "../home/".strip_start_slashes == "../home/"
34 fun strip_start_slashes: String
35 do
36 for i in chars.length.times do if chars[i] != '/' then return substring_from(i)
37 return ""
38 end
39 end
40
41 # A simple file server
42 class FileServer
43 super Action
44
45 # Root folder of `self` file system
46 var root: String
47
48 init
49 do
50 var root = self.root
51
52 # Simplify the root path as each file requested will also be simplified
53 root = root.simplify_path
54
55 # Make sure the root ends with '/', this makes a difference in the security
56 # check on each file access.
57 root = root + "/"
58
59 self.root = root
60 end
61
62 # Error page template for a given `code`
63 fun error_page(code: Int): Writable do return new ErrorTemplate(code)
64
65 # Header of each directory page
66 var header: nullable Writable = null is writable
67
68 # Custom JavaScript code added within a `<script>` block to each page
69 var javascript_header: nullable Writable = null is writable
70
71 # Caching attributes of served files, used as the `cache-control` field in response headers
72 var cache_control = "public, max-age=360" is writable
73
74 redef fun answer(request, turi)
75 do
76 var response
77
78 var local_file = root.join_path(turi.strip_start_slashes)
79 local_file = local_file.simplify_path
80
81 # Is it reachable?
82 #
83 # This make sure that the requested file is within the root folder.
84 if (local_file + "/").has_prefix(root) then
85 # Does it exists?
86 if local_file.file_exists then
87 if local_file.file_stat.is_dir then
88 # If we target a directory without an ending `/`,
89 # redirect to the directory ending with `/`.
90 if not request.uri.is_empty and
91 request.uri.chars.last != '/' then
92 response = new HttpResponse(303)
93 response.header["Location"] = request.uri + "/"
94 return response
95 end
96
97 # Show index file instead of the directory listing
98 # only if `index.html` or `index.htm` is available
99 var index_file = local_file.join_path("index.html")
100 if index_file.file_exists then
101 local_file = index_file
102 else
103 index_file = local_file.join_path("index.htm")
104 if index_file.file_exists then local_file = index_file
105 end
106 end
107
108 response = new HttpResponse(200)
109 if local_file.file_stat.is_dir then
110 # Show the directory listing
111 var title = turi
112 var files = local_file.files
113
114 alpha_comparator.sort files
115
116 var links = new Array[String]
117 if turi.length > 1 then
118 var path = (request.uri + "/..").simplify_path
119 links.add "<a href=\"{path}/\">..</a>"
120 end
121 for file in files do
122 var local_path = local_file.join_path(file).simplify_path
123 var web_path = file.simplify_path
124 if local_path.file_stat.is_dir then web_path = web_path + "/"
125 links.add "<a href=\"{web_path}\">{file}</a>"
126 end
127
128 var header = self.header
129 var header_code
130 if header != null then
131 header_code = header.write_to_string
132 else header_code = ""
133
134 response.body = """
135 <!DOCTYPE html>
136 <head>
137 <meta charset="utf-8">
138 <meta http-equiv="X-UA-Compatible" content="IE=edge">
139 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
140 <script>
141 {{{javascript_header or else ""}}}
142 </script>
143 <title>{{{title}}}</title>
144 </head>
145 <body>
146 {{{header_code}}}
147 <div class="container">
148 <h1>{{{title}}}</h1>
149 <ul>
150 <li>{{{links.join("</li>\n\t\t\t<li>")}}}</li>
151 </ul>
152 </div>
153 </body>
154 </html>"""
155
156 response.header["Content-Type"] = media_types["html"].as(not null)
157 else
158 # It's a single file
159 response.files.add local_file
160
161 var ext = local_file.file_extension
162 if ext != null then
163 var media_type = media_types[ext]
164 if media_type != null then
165 response.header["Content-Type"] = media_type
166 else response.header["Content-Type"] = "application/octet-stream"
167 end
168
169 # Cache control
170 response.header["cache-control"] = cache_control
171 end
172
173 else response = new HttpResponse(404)
174 else response = new HttpResponse(403)
175
176 if response.status_code != 200 then
177 var tmpl = error_page(response.status_code)
178 if header != null and tmpl isa ErrorTemplate then tmpl.header = header
179 response.body = tmpl.to_s
180 end
181
182 return response
183 end
184 end