poodledonts/app.py

85 lines
2.3 KiB
Python

from flask import Flask, request, Response, render_template
import requests
import re
import os
app = Flask(__name__)
FONT_STATIC_URL = "https://fonts.gstatic.com"
FONT_API_URL = "https://fonts.googleapis.com"
PATTERN = rb"fonts\.gstatic\.com"
@app.route("/")
def home():
domain = request.url_root
return render_template("index.html", domain=domain)
def create_proxy_response(url, headers=None):
"""
Create a proxy response for the given URL.
Args:
url (str): The URL to proxy
headers (dict, optional): Headers to send with the request
process_content (callable, optional): Function to process response content
Returns:
flask.Response: The proxy response
"""
response = requests.get(url, headers=headers or {}, stream=True)
if response.status_code != 200:
return Response("Not Found", status=404)
content = response.content
# Remove hop-by-hop headers
filtered_headers = {
key: value
for key, value in response.headers.items()
if key.lower()
not in [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
"content-encoding",
"content-length",
]
}
if "text/css" in response.headers.get("Content-Type", ""):
filtered_headers["Content-Type"] = "text/css; charset=utf-8"
content = re.sub(
PATTERN, request.host.encode("utf-8"), content
)
filtered_headers["Content-Length"] = str(len(content))
return Response(content, status=response.status_code, headers=filtered_headers)
@app.route("/s/<path:path>", methods=["GET"])
def proxy_fonts_static(path):
url = f"{FONT_STATIC_URL}/s/{path}"
return create_proxy_response(url)
@app.route("/<path:path>", methods=["GET"])
def proxy_fonts_api(path):
query_string = request.query_string.decode("utf-8")
url = f"{FONT_API_URL}/{path}"
if query_string:
url += f"?{query_string}"
headers = {"Accept-Encoding": ""}
return create_proxy_response(url, headers=headers)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=os.environ.get("PORT", 5678))