lib/nitcorn: intro the attribute `FileServer::javascript_header`
[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 redef fun answer(request, turi)
72 do
73 var response
74
75 var local_file = root.join_path(turi.strip_start_slashes)
76 local_file = local_file.simplify_path
77
78 # Is it reachable?
79 #
80 # This make sure that the requested file is within the root folder.
81 if (local_file + "/").has_prefix(root) then
82 # Does it exists?
83 if local_file.file_exists then
84 if local_file.file_stat.is_dir then
85 # If we target a directory without an ending `/`,
86 # redirect to the directory ending with `/`.
87 if not request.uri.is_empty and
88 request.uri.chars.last != '/' then
89 response = new HttpResponse(303)
90 response.header["Location"] = request.uri + "/"
91 return response
92 end
93
94 # Show index file instead of the directory listing
95 # only if `index.html` or `index.htm` is available
96 var index_file = local_file.join_path("index.html")
97 if index_file.file_exists then
98 local_file = index_file
99 else
100 index_file = local_file.join_path("index.htm")
101 if index_file.file_exists then local_file = index_file
102 end
103 end
104
105 response = new HttpResponse(200)
106 if local_file.file_stat.is_dir then
107 # Show the directory listing
108 var title = turi
109 var files = local_file.files
110
111 var links = new Array[String]
112 if turi.length > 1 then
113 var path = (request.uri + "/..").simplify_path
114 links.add "<a href=\"{path}/\">..</a>"
115 end
116 for file in files do
117 var local_path = local_file.join_path(file).simplify_path
118 var web_path = file.simplify_path
119 if local_path.file_stat.is_dir then web_path = web_path + "/"
120 links.add "<a href=\"{web_path}\">{file}</a>"
121 end
122
123 var header = self.header
124 var header_code
125 if header != null then
126 header_code = header.write_to_string
127 else header_code = ""
128
129 response.body = """
130 <!DOCTYPE html>
131 <head>
132 <meta charset="utf-8">
133 <meta http-equiv="X-UA-Compatible" content="IE=edge">
134 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
135 <script>
136 {{{javascript_header or else ""}}}
137 </script>
138 <title>{{{title}}}</title>
139 </head>
140 <body>
141 {{{header_code}}}
142 <div class="container">
143 <h1>{{{title}}}</h1>
144 <ul>
145 <li>{{{links.join("</li>\n\t\t\t<li>")}}}</li>
146 </ul>
147 </div>
148 </body>
149 </html>"""
150
151 response.header["Content-Type"] = media_types["html"].as(not null)
152 else
153 # It's a single file
154 response.files.add local_file
155
156 var ext = local_file.file_extension
157 if ext != null then
158 var media_type = media_types[ext]
159 if media_type != null then
160 response.header["Content-Type"] = media_type
161 else response.header["Content-Type"] = "application/octet-stream"
162 end
163 end
164
165 else response = new HttpResponse(404)
166 else response = new HttpResponse(403)
167
168 if response.status_code != 200 then
169 var tmpl = error_page(response.status_code)
170 if header != null and tmpl isa ErrorTemplate then tmpl.header = header
171 response.body = tmpl.to_s
172 end
173
174 return response
175 end
176 end