File size: 10,050 Bytes
73587bf | 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | """Portable WebsiteBench Kanetix / Rates.ca desktop clone server."""
from __future__ import annotations
import json
import mimetypes
import os
import re
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlsplit
from backend.site_backend_integration import open_site_services
SITE_ID = "kanetix-ca"
ROOT = Path(__file__).resolve().parent
PUBLIC = ROOT / "public"
DATA_DIR = Path(os.environ.get("DATA_DIR", str(ROOT.parent / "data"))).resolve()
DATA_DIR.mkdir(parents=True, exist_ok=True)
os.environ.setdefault("WEBSITEBENCH_SITE_BACKEND_DATABASE", str(DATA_DIR / f"{SITE_ID}.sqlite3"))
BACKEND, _AUTH = open_site_services()
def now() -> str:
return datetime.now(UTC).isoformat().replace("+00:00", "Z")
def row_dict(row):
return dict(row) if row is not None else None
def paginate(table: str, page: int, page_size: int, where: str = "", params=(), order: str = "id ASC"):
offset = (page - 1) * page_size
clause = f" WHERE {where}" if where else ""
with BACKEND.lifecycle.connection() as connection:
total = connection.execute(f"SELECT COUNT(*) AS count FROM {table}{clause}", params).fetchone()["count"]
rows = connection.execute(
f"SELECT * FROM {table}{clause} ORDER BY {order} LIMIT ? OFFSET ?",
(*params, page_size, offset),
).fetchall()
return {
"items": [dict(row) for row in rows], "page": page, "page_size": page_size,
"total": total, "pages": max(1, (total + page_size - 1) // page_size),
}
class Handler(BaseHTTPRequestHandler):
server_version = "WebsiteBenchKanetix/1.0"
def log_message(self, _format, *_args):
return
def send_json(self, status: int, value) -> None:
body = json.dumps(value, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def read_json(self):
length = int(self.headers.get("Content-Length", "0"))
if length > 1_000_000:
raise ValueError("Payload too large")
try:
return json.loads(self.rfile.read(length) or b"{}")
except json.JSONDecodeError as exc:
raise ValueError("Invalid JSON") from exc
def serve_file(self, path: Path) -> bool:
try:
resolved = path.resolve(strict=True)
resolved.relative_to(PUBLIC)
except (FileNotFoundError, ValueError):
return False
if not resolved.is_file():
return False
body = resolved.read_bytes()
content_type = mimetypes.guess_type(str(resolved))[0] or "application/octet-stream"
self.send_response(200)
self.send_header("Content-Type", content_type + ("; charset=utf-8" if content_type.startswith("text/") else ""))
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-cache")
self.end_headers()
self.wfile.write(body)
return True
def do_GET(self):
parsed = urlsplit(self.path)
path = parsed.path
query = parse_qs(parsed.query)
if path in {"/api/healthz", "/__websitebench/health"}:
return self.send_json(200, {"ok": True, "site_id": SITE_ID})
if path == "/api/resources":
page = max(1, int(query.get("page", ["1"])[0]))
q = query.get("q", [""])[0].strip()
category = query.get("category", [""])[0].strip()
filters, params = [], []
if q:
filters.append("(title LIKE ? OR summary LIKE ?)")
params.extend((f"%{q}%", f"%{q}%"))
if category:
filters.append("category = ?")
params.append(category)
order = "published_at ASC" if query.get("sort", [""])[0] == "oldest" else "published_at DESC"
return self.send_json(200, paginate("resources", page, 10, " AND ".join(filters), tuple(params), order))
for prefix, table in (("/api/resources/", "resources"), ("/api/cards/", "cards"), ("/api/providers/", "providers")):
if path.startswith(prefix):
with BACKEND.lifecycle.connection() as connection:
row = connection.execute(f"SELECT * FROM {table} WHERE slug=?", (unquote(path[len(prefix):]),)).fetchone()
return self.send_json(200, row_dict(row)) if row else self.send_json(404, {"error": "Item not found"})
if path == "/api/cards":
page = max(1, int(query.get("page", ["1"])[0]))
category = query.get("category", [""])[0].strip()
order = "annual_fee ASC, id ASC" if query.get("sort", [""])[0] == "fee" else "featured DESC, id ASC"
return self.send_json(200, paginate("cards", page, 10, "category = ?" if category else "", (category,) if category else (), order))
if path == "/api/providers":
page = max(1, int(query.get("page", ["1"])[0]))
category = query.get("category", [""])[0].strip()
return self.send_json(200, paginate("providers", page, 12, "category = ?" if category else "", (category,) if category else ()))
relative = "index.html" if path == "/" else path.lstrip("/")
if self.serve_file(PUBLIC / relative):
return
self.serve_file(PUBLIC / "index.html")
def do_POST(self):
path = urlsplit(self.path).path
try:
data = self.read_json()
if path == "/api/quote-drafts":
postal = " ".join(str(data.get("postal_code", "")).upper().split())
if not re.fullmatch(r"[A-Z]\d[A-Z] ?\d[A-Z]\d", postal):
return self.send_json(422, {"error": "Enter a valid Canadian postal code."})
with BACKEND.lifecycle.connection(transaction=True) as connection:
cursor = connection.execute(
"INSERT INTO quote_drafts(product,postal_code,province,status,created_at) VALUES(?,?,?,?,?)",
(str(data.get("product", "car"))[:40], postal, str(data.get("province", ""))[:40], "local-draft", now()),
)
item_id = cursor.lastrowid
return self.send_json(201, {"id": item_id, "status": "local-draft", "message": "Your comparison draft was saved locally. No provider was contacted."})
restore = re.fullmatch(r"/api/quote-drafts/(\d+)/restore", path)
if restore:
item_id = int(restore.group(1))
with BACKEND.lifecycle.connection(transaction=True) as connection:
connection.execute("UPDATE quote_drafts SET deleted_at=NULL,status='local-draft' WHERE id=?", (item_id,))
return self.send_json(200, {"id": item_id, "status": "local-draft"})
if path == "/api/newsletter":
email = str(data.get("email", "")).strip().lower()
if not re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", email):
return self.send_json(422, {"error": "Enter a valid email address."})
with BACKEND.lifecycle.connection(transaction=True) as connection:
cursor = connection.execute(
"INSERT INTO newsletter_outbox(purpose,recipient,payload,status,created_at) VALUES(?,?,?,?,?)",
("newsletter", email, '{"local_only":true}', "sandboxed", now()),
)
return self.send_json(201, {"id": cursor.lastrowid, "status": "sandboxed", "message": "Saved to the local outbox. No email was sent."})
if path == "/api/support":
if not all(data.get(key) for key in ("email", "subject", "message")):
return self.send_json(422, {"error": "Complete all required fields."})
with BACKEND.lifecycle.connection(transaction=True) as connection:
cursor = connection.execute(
"INSERT INTO support_tickets(email,subject,message,status,created_at) VALUES(?,?,?,?,?)",
(str(data["email"])[:200], str(data["subject"])[:200], str(data["message"])[:4000], "local-inbox", now()),
)
return self.send_json(201, {"id": cursor.lastrowid, "status": "local-inbox", "message": "Saved to the local support inbox."})
if path == "/api/reset":
with BACKEND.lifecycle.connection(transaction=True) as connection:
connection.executescript("DELETE FROM quote_drafts; DELETE FROM newsletter_outbox; DELETE FROM support_tickets;")
return self.send_json(200, {"reset": True})
self.send_json(404, {"error": "Not found"})
except ValueError as exc:
self.send_json(413 if str(exc) == "Payload too large" else 400, {"error": str(exc)})
except Exception:
self.send_json(500, {"error": "Local server error"})
def do_DELETE(self):
match = re.fullmatch(r"/api/quote-drafts/(\d+)", urlsplit(self.path).path)
if not match:
return self.send_json(404, {"error": "Not found"})
item_id = int(match.group(1))
with BACKEND.lifecycle.connection(transaction=True) as connection:
connection.execute("UPDATE quote_drafts SET deleted_at=?,status='deleted' WHERE id=?", (now(), item_id))
self.send_json(200, {"id": item_id, "status": "deleted", "undo_available": True})
def main() -> None:
host = os.environ.get("HOST", "127.0.0.1")
port = int(os.environ.get("PORT", "4171"))
server = ThreadingHTTPServer((host, port), Handler)
print(f"{SITE_ID} listening on http://{host}:{port}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()
|