nocdnbs/app.py
Kumi ce9e34f55e
fix(proxy): correct URL composition for CDNJS
Updated the URL construction within the proxy function to correctly reference CDNJS URLs. Previously the variable name mistakenly suggested an old CDN (jsdelivr), potentially leading to confusion and incorrect URL referencing. This change ensures accuracy and consistency when fetching and streaming resources.
2024-08-03 16:39:46 +02:00

50 lines
1.3 KiB
Python

from flask import Flask, render_template, request, Response, abort
from werkzeug.exceptions import InternalServerError
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.parse import unquote
app = Flask(__name__)
@app.route("/")
def home():
domain = request.url_root
return render_template("index.html", domain=domain)
@app.route("/<path:url>")
def proxy(url):
cdnjs_url = f"https://cdnjs.cloudflare.com/{url}"
def generate():
# Subfunction to allow streaming the data instead of
# downloading all of it at once
try:
with urlopen(unquote(cdnjs_url)) as data:
while True:
chunk = data.read(1024 * 1024)
if not chunk:
break
yield chunk
except HTTPError as e:
abort(e.code)
try:
with urlopen(unquote(cdnjs_url)) as data:
content_type = data.headers["content-type"]
except HTTPError as e:
abort(e.code)
except KeyError:
raise InternalServerError()
headers = dict()
filename = url.split("/")[-1]
headers["Content-Disposition"] = f'attachment; filename="{filename}"'
return Response(generate(), content_type=content_type, headers=headers)
if __name__ == "__main__":
app.run()