From 5e4f57a8b360ed0bbd1ffdd3d4dde8e161b0fd6b Mon Sep 17 00:00:00 2001 From: Thomas Sileo Date: Sun, 18 Aug 2019 11:40:57 +0200 Subject: [PATCH] Proxy media that aren't cached --- app.py | 20 ++++++++++++++++++++ utils/template_filters.py | 2 +- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index 4dd1e1b..b50d6c3 100644 --- a/app.py +++ b/app.py @@ -3,8 +3,10 @@ import logging import os import traceback from datetime import datetime +from typing import Any from uuid import uuid4 +import requests from bson.errors import InvalidId from bson.objectid import ObjectId from flask import Flask @@ -226,12 +228,30 @@ def robots_txt(): @app.route("/microblogpub-0.0.jsonld") def microblogpub_jsonld(): + """Returns our AP context (embedded in activities @context).""" return Response( response=json.dumps(jsonld.MICROBLOGPUB), headers={"Content-Type": "application/ld+json"}, ) +@app.route("/p/") +def proxy(url: str) -> Any: + req_headers = { + k: v + for k, v in dict(request.headers).items() + if k.lower() not in ["host", "cookie"] + } + resp = requests.get(url, stream=True, headers=req_headers) + app.logger.info(f"proxied req {url}: {resp!r}") + + def data(): + for chunk in resp.raw.stream(decode_content=False): + yield chunk + + return Response(data(), headers=dict(resp.raw.headers)) + + @app.route("/media/") @noindex def serve_media(media_id): diff --git a/utils/template_filters.py b/utils/template_filters.py index 7eb3701..c31b585 100644 --- a/utils/template_filters.py +++ b/utils/template_filters.py @@ -249,7 +249,7 @@ def _get_file_url(url, size, kind) -> str: # MEDIA_CACHE.cache(url, kind) _logger.error(f"cache not available for {url}/{size}/{kind}") - return url + return f"/p/{url}" @filters.app_template_filter()