-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
89 lines (73 loc) · 2.76 KB
/
main.py
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
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import FileResponse, HTMLResponse
from starlette.routing import Route
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from helpers import read_config
import api.chat
import api.config
import api.gifts
import dotenv
import os
import pathlib
dotenv.load_dotenv()
class DisableCacheMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
async def serve_index(request):
return FileResponse("static/index.html")
def get_app_name(request: Request):
path_segments = request.url.path.strip("/").split("/")
return path_segments[-1] if path_segments else None
async def serve_static(request: Request):
# Extract the requested path
path = request.path_params.get("path", "")
request
file_path = pathlib.Path("static") / path
# Check if the file exists
if file_path.is_file():
return FileResponse(file_path)
appname = get_app_name(request)
if read_config(f"./prompts/{appname}.toml"):
with open("static/index.html", "r") as file:
html_content = file.read()
page = html_content.replace(
'<meta property="og:url" content="https://adventai.dev/app/">',
f'<meta property="og:url" content="https://adventai.dev/app/{appname}">',
)
page = page.replace(
'<meta property="og:image" content="https://adventai.dev/og/adventai.png">',
f'<meta property="og:image" content="https://adventai.dev/og/{appname}.png">',
)
return HTMLResponse(page)
# Default to serving the index.html
return FileResponse("static/index.html", status_code=404)
# Determine middleware and debug based on environment
middleware = (
[Middleware(DisableCacheMiddleware)]
if os.environ.get("ENVIRONMENT") == "development"
else []
)
debug = os.environ.get("ENVIRONMENT") == "development"
app = Starlette(
debug=debug,
middleware=middleware,
routes=[
Route("/api/chat", api.chat.post, methods=["POST"]),
Route("/api/config", api.config.get, methods=["GET"]),
Route("/api/gifts", api.gifts.get, methods=["GET"]),
Route("/app/{path:path}", serve_static),
Mount(
"/",
StaticFiles(directory="adventai", html=True),
name="adventai",
),
],
)