File size: 1,249 Bytes
ee05485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from competitions.app import app
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response


FULL_WIDTH_CSS = """
<style>
  main .prose,
  main .markdown-body,
  main [class*="max-w-"],
  main [class*="container"],
  .prose,
  .markdown-body {
    max-width: none !important;
  }

  main {
    max-width: none !important;
  }
</style>
"""


class InjectCssMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        content_type = response.headers.get("content-type", "")
        if "text/html" not in content_type:
            return response

        body = b""
        async for chunk in response.body_iterator:
            body += chunk

        html = body.decode("utf-8", errors="ignore")
        if "</head>" in html and FULL_WIDTH_CSS not in html:
            html = html.replace("</head>", FULL_WIDTH_CSS + "</head>")

        headers = dict(response.headers)
        headers.pop("content-length", None)
        return Response(
            content=html,
            status_code=response.status_code,
            headers=headers,
            media_type=response.media_type,
        )


app.add_middleware(InjectCssMiddleware)