Newer
Older
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
import http.server
import socketserver
import cgi
from urllib.parse import unquote, parse_qs
import re
import subprocess
PORT = 8000
url_format = re.compile(r"^(?:(?:https://)?platform\.physik\.kit\.edu/codimd/)?(?P<id>[\w_]+)([\?#].*)?$")
class CodiToPdfHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory="/app/html", **kwargs)
# forward get requests
def do_GET(self):
print(self.path)
print(self.headers)
super().do_GET()
return
def do_POST(self):
content_length = int(self.headers["Content-Length"])
_body = self.rfile.read(content_length)
body = unquote(_body.decode("ASCII"))
post_data = parse_qs(body)
pad = post_data["pad"][0]
pad_id = url_format.match(pad).group("id")
subprocess.call(["codimd", "export", "--md", pad_id, "tmp.md"])
subprocess.call(["pandoc", "tmp.md", "-o", "tmp.pdf"])
pdf = open("tmp.pdf", "rb").read()
subprocess.call(["rm", "tmp.md", "tmp.pdf"])
self.send_response(200)
self.send_header("Content-Type", "application/pdf")
self.send_header("Content-Length", str(len(pdf)))
self.end_headers()
self.wfile.write(pdf)
return
with http.server.ThreadingHTTPServer(("", PORT), CodiToPdfHandler) as httpd: