Allowing user edit in Nitiwiki (not finished).
[nit.git] / contrib / nitiwiki / src / wiki_edit.nit
1 import nitcorn
2 import markdown
3
4 fun html_document(body: String): String do
5 return """
6 <!DOCTYPE html>
7 <head>
8 <meta charset="utf-8">
9 <title>Nitiwiki Edit</title>
10 </head>
11 <body>
12 """ + body + """
13 </body>
14 </html>"""
15 end
16
17 class EditMarkdownAction
18 super Action
19
20 redef fun answer(http_request, turi)
21 do
22 var response = new HttpResponse(200)
23 var file_path = turi.substring(1, turi.length)
24 var md_file = new FileReader.open(file_path)
25 response.body = html_document("""
26 <form method="POST" action="/preview">
27 You may edit the file. When you are done, click on "Submit".<br/>
28 <textarea name="content" rows="30" cols="80" style="font-family: Courier">""" + md_file.read_all + """</textarea><br/>
29 <input type="submit" name="action" value="Preview">
30 <input type="submit" name="action" value="Submit">
31 <input type="hidden" name="filepath" value="""" + file_path + """">
32 </form>""")
33 md_file.close
34 return response
35 end
36 end
37
38 class PreviewMarkdown2HTMLAction
39 super Action
40
41 redef fun answer(http_request, turi)
42 do
43 var response = new HttpResponse(200)
44 var content = http_request.post_args["content"]
45 var action = http_request.post_args["action"]
46 var file_path = http_request.post_args["filepath"]
47 if action == "Preview" then
48 response.body = html_document("""
49 <p>
50 """ + content.md_to_html.to_s + """
51 </p>
52 """)
53 else if action == "Submit" then
54 var md_file = new FileWriter.open(file_path)
55 md_file.write(content)
56 response.body = html_document("""
57 <p>Updated file!</p>
58 """)
59 md_file.close
60 end
61 return response
62 end
63 end
64
65 var vh = new VirtualHost("localhost:8080")
66
67 # Serve Markdown editing
68 vh.routes.add new Route("/edit", new EditMarkdownAction)
69 vh.routes.add new Route("/preview", new PreviewMarkdown2HTMLAction)
70
71 # Serve everything else with a standard `FileServer`
72 vh.routes.add new Route(null, new FileServer("/var/www/"))
73
74 var factory = new HttpFactory.and_libevent
75 factory.config.virtual_hosts.add vh
76 factory.run