Add tradeOffer image field, tweak image generation to only fire once per tradeOffer, even with simultaneous requests

This commit is contained in:
badblocks 2025-03-29 15:13:57 -07:00
parent 138a929da6
commit 2d826734a0
9 changed files with 127 additions and 80 deletions

View file

@ -599,81 +599,86 @@ class TradeAcceptanceUpdateView(LoginRequiredMixin, FriendCodeRequiredMixin, Upd
class TradeOfferPNGView(View):
"""
Generate a PNG screenshot of the rendered trade offer detail page using Playwright.
This view loads the SVG representation generated by the trade_offer_svg template tag,
wraps it in a minimal HTML document, and converts it to PNG using Playwright.
This view uses PostgreSQL advisory locks to ensure that only one generation process
runs at a time for a given TradeOffer. The generated PNG is then cached in the
TradeOffer model's `image` field (assumed to be an ImageField).
"""
def get_lock_key(self, trade_offer_id):
# Use the trade_offer_id as the lock key; adjust if needed.
return trade_offer_id
def get(self, request, *args, **kwargs):
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.core.files.base import ContentFile
trade_offer = get_object_or_404(TradeOffer, pk=kwargs['pk'])
from trades.templatetags import trade_offer_tags
# Generate context for the SVG template tag.
tag_context = trade_offer_tags.render_trade_offer_png(
{'request': request}, trade_offer, show_friend_code=True
)
# If the image is already generated and stored, serve it directly.
if trade_offer.image:
trade_offer.image.open()
print(f"Serving cached image for trade offer {trade_offer.pk}")
return HttpResponse(trade_offer.image.read(), content_type="image/png")
# Use provided dimensions from the context
image_width = tag_context.get('image_width')
image_height = tag_context.get('image_height')
html = render_to_string("templatetags/trade_offer_png.html", tag_context)
# If there's a query parameter 'debug' set to true, render the HTML to the response.
if request.GET.get('debug'):
return HttpResponse(html, content_type="text/html")
css = render_to_string("static/css/dist/styles.css")
# Launch Playwright to render the HTML and capture a screenshot.
with sync_playwright() as p:
print("Launching browser")
browser = p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-accelerated-2d-canvas",
"--disable-gpu",
#"--single-process",
"--no-zygote",
"--disable-audio-output",
#"--disable-software-rasterizer",
"--disable-webgl",
#"--disable-web-security",
#"--disable-features=LazyFrameLoading",
#"--disable-features=IsolateOrigins",
#"--disable-background-networking",
"--no-first-run",
]
# Acquire PostgreSQL advisory lock to prevent concurrent generation.
from django.db import connection
lock_key = self.get_lock_key(trade_offer.pk)
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_lock(%s)", [lock_key])
try:
# Double-check if the image was generated while waiting for the lock.
trade_offer.refresh_from_db()
if trade_offer.image:
trade_offer.image.open()
print(f"Serving recently-cached image for trade offer {trade_offer.pk}")
return HttpResponse(trade_offer.image.read(), content_type="image/png")
print(f"Generating PNG for trade offer {trade_offer.pk}")
# Generate PNG using Playwright as before.
from trades.templatetags import trade_offer_tags
tag_context = trade_offer_tags.render_trade_offer_png(
{'request': request}, trade_offer, show_friend_code=True
)
print("Launched browser, creating context")
context_browser = browser.new_context(viewport={"width": image_width, "height": image_height})
print("Created context, creating page")
page = context_browser.new_page()
print("Created page, setting content")
# Listen for all console logs, errors, and warnings
page.on("console", lambda msg: print(f"Console {msg.type}: {msg.text}"))
page.on("pageerror", lambda err: print(f"Page error: {err}"))
# Listen specifically for failed resource loads
page.on("requestfailed", lambda request: print(f"Failed to load: {request.url} - {request.failure.error_text}"))
# # Instead of using a link tag, let's inject the CSS directly
# css = render_to_string("static/css/dist/styles.css")
# page.add_style_tag(content=css)
page.set_content(html, wait_until="domcontentloaded")
print("Set content, waiting for element")
element = page.wait_for_selector(".trade-offer-card-screenshot")
print("Found element, capturing screenshot")
screenshot_bytes = element.screenshot(type="png", omit_background=True)
print("Captured screenshot, closing browser")
browser.close()
print("Closed browser, returning screenshot")
image_width = tag_context.get('image_width')
image_height = tag_context.get('image_height')
if not image_width or not image_height:
raise ValueError("Could not determine image dimensions from tag_context")
html = render_to_string("templatetags/trade_offer_png.html", tag_context)
return HttpResponse(screenshot_bytes, content_type="image/png")
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(
headless=True,
args=[
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-accelerated-2d-canvas",
"--disable-gpu",
"--no-zygote",
"--disable-audio-output",
"--disable-webgl",
"--no-first-run",
]
)
context_browser = browser.new_context(viewport={"width": image_width, "height": image_height})
page = context_browser.new_page()
page.on("console", lambda msg: print(f"Console {msg.type}: {msg.text}"))
page.on("pageerror", lambda err: print(f"Page error: {err}"))
page.on("requestfailed", lambda req: print(f"Failed to load: {req.url} - {req.failure.error_text}"))
page.set_content(html, wait_until="domcontentloaded")
element = page.wait_for_selector(".trade-offer-card-screenshot")
screenshot_bytes = element.screenshot(type="png", omit_background=True)
browser.close()
# Save the generated PNG to the TradeOffer model (requires an ImageField named `image`).
filename = f"trade_offer_{trade_offer.pk}.png"
trade_offer.image.save(filename, ContentFile(screenshot_bytes))
trade_offer.save(update_fields=["image"])
return HttpResponse(screenshot_bytes, content_type="image/png")
finally:
# Release the advisory lock.
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_unlock(%s)", [lock_key])
class TradeOfferCreateConfirmView(LoginRequiredMixin, View):
"""