aboutsummaryrefslogtreecommitdiff
path: root/blog_experiment/blog.py
blob: 54013ccf340a54ae72723510c0ce09f6d333782a (plain)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import datetime
import itertools
import logging
import pathlib
import re
import subprocess
import textwrap

import htmlgenerator as h

import bicephalus
from bicephalus import main as bicephalus_main
from bicephalus import otel
from bicephalus import ssl


def tidy(s):
    p = subprocess.run(
        ["tidy", "--indent", "yes", "-q", "-wrap", "160"],
        input=s,
        stdout=subprocess.PIPE,
        encoding="UTF8",
    )
    return p.stdout


def html_template(*content):
    return tidy(
        h.render(
            h.HTML(
                h.HEAD(h.TITLE("El blog es mío")),
                h.BODY(
                    h.H1("El blog es mío"),
                    h.H2("Hay otros como él, pero este es el mío"),
                    *content,
                ),
            ),
            {},
        )
    )


class BasePage:
    def __init__(self, request):
        self.request = request

    def response(self):
        if self.request.proto == bicephalus.Proto.GEMINI:
            status, content_type, content = self.get_gemini_content()
        elif self.request.proto == bicephalus.Proto.HTTP:
            status, content_type, content = self.get_http_content()
        else:
            assert False, f"unknown protocol {self.request.proto}"

        return bicephalus.Response(
            content=content.encode("utf8"),
            content_type=content_type,
            status=bicephalus.Status.OK,
        )


class Entry:
    def __init__(self, path: pathlib.Path):
        assert path.is_relative_to(pathlib.Path("content")), f"bad path {path}"
        self.path = path
        self.content = path.read_text()

    @property
    def title(self):
        return self.content.splitlines()[0][2:]

    @property
    def posted(self):
        return datetime.date.fromisoformat(self.content.splitlines()[1])

    @property
    def uri(self):
        return f"/{self.path.parts[1]}/{self.path.parts[2]}/{self.path.stem}/"


class Root(BasePage):
    def entries(self):
        entries = map(Entry, pathlib.Path("content").glob("*/*/*.gmi"))
        return sorted(entries, key=lambda e: e.posted, reverse=True)

    def get_gemini_content(self):
        posts = "\n".join([f"=> {e.uri} {e.posted} {e.title}" for e in self.entries()])
        content = (
            textwrap.dedent(
                """\
                # El blog es mío

                ## Hay otros como él, pero este es el mío

                ____
                """
            )
            + posts
        )
        return bicephalus.Status.OK, "text/gemini", content

    def get_http_content(self):
        posts = [
            (h.H3(h.A(f"{e.title} ({e.posted})", href=e.uri))) for e in self.entries()
        ]
        return (
            bicephalus.Status.OK,
            "text/html",
            html_template(*itertools.chain(posts)),
        )


class EntryPage(BasePage):
    def __init__(self, request, path):
        super().__init__(request)
        self.path = path
        self.entry = Entry(path)

    def get_gemini_content(self):
        return bicephalus.Status.OK, "text/gemini", self.entry.content

    def get_http_content(self):
        return (
            bicephalus.Status.OK,
            "text/html",
            html_template(
                h.PRE(self.entry.content),
            ),
        )


class NotFound(BasePage):
    def get_gemini_content(self):
        # TODO: does not work!
        return (
            bicephalus.Status.NOT_FOUND,
            "text/gemini",
            f"{self.request.path} not found",
        )

    def get_http_content(self):
        return (
            bicephalus.Status.NOT_FOUND,
            "text/html",
            f"{self.request.path} not found",
        )


def handler(request: bicephalus.Request) -> bicephalus.Response:
    if request.path == "/":
        return Root(request).response()
    if re.match(r"/\d{4}/\d{2}/.*/", request.path):
        blog_file = pathlib.Path("content") / (request.path[1:-1] + ".gmi")
        if blog_file.exists():
            return EntryPage(request, blog_file).response()
    return NotFound(request).response()


def main():
    otel.configure_logging(logging.INFO)
    with ssl.temporary_ssl_context("localhost") as ssl_context:
        bicephalus_main.main(handler, ssl_context, 8000)


if __name__ == "__main__":
    main()