Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
documentation: Move OpenGraph description updating out of middleware.
Alex Vandiver1424a2e7480f
diff --git a/zerver/lib/cache.py b/zerver/lib/cache.pyindex 52d8c9934ce..5e0a2c36b13 100644--- a/zerver/lib/cache.py+++ b/zerver/lib/cache.py@@ -26,7 +26,6 @@ from django.conf import settingsfrom django.core.cache import cachesfrom django.core.cache.backends.base import BaseCachefrom django.db.models import Q-from django.http import HttpRequestfrom django_stubs_ext import QuerySetAnyfrom typing_extensions import ParamSpec@@ -684,10 +683,8 @@ def to_dict_cache_key(message: "Message", realm_id: Optional[int] = None) -> strreturn to_dict_cache_key_id(message.id)-def open_graph_description_cache_key(content: bytes, request: HttpRequest) -> str:- return "open_graph_description_path:{}".format(- hashlib.sha1(request.META["PATH_INFO"].encode()).hexdigest()- )+def open_graph_description_cache_key(content: bytes, request_url: str) -> str:+ return f"open_graph_description_path:{hashlib.sha1(request_url.encode()).hexdigest()}"def flush_message(*, instance: "Message", **kwargs: object) -> None:diff --git a/zerver/lib/html_to_text.py b/zerver/lib/html_to_text.pyindex 7094bc05525..8e328ccdb63 100644--- a/zerver/lib/html_to_text.py+++ b/zerver/lib/html_to_text.py@@ -1,7 +1,6 @@from typing import Mapping, Unionfrom bs4 import BeautifulSoup-from django.http import HttpRequestfrom django.utils.html import escapefrom zerver.lib.cache import cache_with_key, open_graph_description_cache_key@@ -35,5 +34,5 @@ def html_to_text(content: Union[str, bytes], tags: Mapping[str, str] = {"p": " |@cache_with_key(open_graph_description_cache_key, timeout=3600 * 24)-def get_content_description(content: bytes, request: HttpRequest) -> str:+def get_content_description(content: bytes, request_url: str) -> str:return html_to_text(content)diff --git a/zerver/lib/request.py b/zerver/lib/request.pyindex c3a41ee66ad..b37d8d90ca7 100644--- a/zerver/lib/request.py+++ b/zerver/lib/request.py@@ -66,7 +66,6 @@ class RequestNotes(BaseNotes[HttpRequest, "RequestNotes"]):ratelimits_applied: List[rate_limiter.RateLimitResult] = field(default_factory=list)query: Optional[str] = Noneerror_format: Optional[str] = None- placeholder_open_graph_description: Optional[str] = Nonesaved_response: Optional[HttpResponse] = Nonetornado_handler_id: Optional[int] = Noneprocessed_parameters: Set[str] = field(default_factory=set)diff --git a/zerver/middleware.py b/zerver/middleware.pyindex 6244389d926..1ecee116520 100644--- a/zerver/middleware.py+++ b/zerver/middleware.py@@ -28,7 +28,6 @@ from zerver.lib.cache import get_remote_cache_requests, get_remote_cache_timefrom zerver.lib.db import reset_queriesfrom zerver.lib.debug import maybe_tracemalloc_listenfrom zerver.lib.exceptions import ErrorCode, JsonableError, MissingAuthenticationError, WebhookError-from zerver.lib.html_to_text import get_content_descriptionfrom zerver.lib.markdown import get_markdown_requests, get_markdown_timefrom zerver.lib.per_request_cache import flush_per_request_cachesfrom zerver.lib.rate_limiter import RateLimitResult@@ -669,28 +668,6 @@ class DetectProxyMisconfiguration(MiddlewareMixin):raise ProxyMisconfigurationError(proxy_state_header)-def alter_content(request: HttpRequest, content: bytes) -> bytes:- first_paragraph_text = get_content_description(content, request)- placeholder_open_graph_description = RequestNotes.get_notes(- request- ).placeholder_open_graph_description- assert placeholder_open_graph_description is not None- return content.replace(- placeholder_open_graph_description.encode(),- first_paragraph_text.encode(),- )---class FinalizeOpenGraphDescription(MiddlewareMixin):- def process_response(- self, request: HttpRequest, response: HttpResponseBase- ) -> HttpResponseBase:- if RequestNotes.get_notes(request).placeholder_open_graph_description is not None:- assert isinstance(response, HttpResponse)- response.content = alter_content(request, response.content)- return response--def validate_scim_bearer_token(request: HttpRequest) -> bool:"""This function verifies the request is allowed to make SCIM requests on this subdomain,diff --git a/zerver/views/documentation.py b/zerver/views/documentation.pyindex a690f4f6f0d..c0f51e5c3d6 100644--- a/zerver/views/documentation.py+++ b/zerver/views/documentation.py@@ -3,11 +3,12 @@ import randomimport refrom collections import OrderedDictfrom dataclasses import dataclass-from typing import Any, Dict, Optional+from typing import Any, Callable, Dict, List, Optionalfrom django.conf import settingsfrom django.http import HttpRequest, HttpResponse, HttpResponseNotFoundfrom django.template import loader+from django.template.response import TemplateResponsefrom django.views.generic import TemplateViewfrom lxml import htmlfrom lxml.etree import Element, SubElement, XPath, _Element@@ -16,6 +17,7 @@ from typing_extensions import overridefrom zerver.context_processors import zulip_default_contextfrom zerver.decorator import add_google_analytics_context+from zerver.lib.html_to_text import get_content_descriptionfrom zerver.lib.integrations import (CATEGORIES,INTEGRATIONS,@@ -24,7 +26,7 @@ from zerver.lib.integrations import (WebhookIntegration,get_all_event_types_for_integration,)-from zerver.lib.request import REQ, RequestNotes, has_request_variables+from zerver.lib.request import REQ, has_request_variablesfrom zerver.lib.subdomains import get_subdomainfrom zerver.lib.templates import render_markdown_pathfrom zerver.models import Realm@@ -81,6 +83,15 @@ class MarkdownDirectoryView(ApiURLView):help_view = Falseapi_doc_view = False+ def __init__(self, **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._post_render_callbacks: List[Callable[[HttpResponse], Optional[HttpResponse]]] = []++ def add_post_render_callback(+ self, callback: Callable[[HttpResponse], Optional[HttpResponse]]+ ) -> None:+ self._post_render_callbacks.append(callback)+def get_path(self, article: str) -> DocumentationArticle:http_status = 200if article == "":@@ -223,11 +234,22 @@ class MarkdownDirectoryView(ApiURLView):context["PAGE_TITLE"] = f"{article_title} | {title_base}"else:context["PAGE_TITLE"] = title_base- request_notes = RequestNotes.get_notes(self.request)- request_notes.placeholder_open_graph_description = (+ placeholder_open_graph_description = (f"REPLACEMENT_PAGE_DESCRIPTION_{int(2**24 * random.random())}")- context["PAGE_DESCRIPTION"] = request_notes.placeholder_open_graph_description+ context["PAGE_DESCRIPTION"] = placeholder_open_graph_description++ def update_description(response: HttpResponse) -> None:+ if placeholder_open_graph_description.encode() in response.content:+ first_paragraph_text = get_content_description(+ response.content, context["PAGE_METADATA_URL"]+ )+ response.content = response.content.replace(+ placeholder_open_graph_description.encode(),+ first_paragraph_text.encode(),+ )++ self.add_post_render_callback(update_description)# An "article" might require the api_url_context to be renderedapi_url_context: Dict[str, Any] = {}@@ -283,6 +305,9 @@ class MarkdownDirectoryView(ApiURLView):documentation_article = self.get_path(article)http_status = documentation_article.article_http_statusresult = super().get(request, article=article)+ assert isinstance(result, TemplateResponse)+ for callback in self._post_render_callbacks:+ result.add_post_render_callback(callback)if http_status != 200:result.status_code = http_statusreturn resultdiff --git a/zproject/computed_settings.py b/zproject/computed_settings.pyindex c440c848154..13111e7f012 100644--- a/zproject/computed_settings.py+++ b/zproject/computed_settings.py@@ -178,8 +178,6 @@ MIDDLEWARE = [# Make sure 2FA middlewares come after authentication middleware."django_otp.middleware.OTPMiddleware", # Required by two factor auth."two_factor.middleware.threadlocals.ThreadLocals", # Required by Twilio- # Needs to be after CommonMiddleware, which sets Content-Length- "zerver.middleware.FinalizeOpenGraphDescription",]AUTH_USER_MODEL = "zerver.UserProfile"