35 lines
1.4 KiB
Python
35 lines
1.4 KiB
Python
"""Stufe 2: Rechnungs-PDF per Direktlink laden (Stripe, Paddle, ThriveCart, *.pdf, Tracker-Links z.B. OpenAI)."""
|
|
|
|
import re
|
|
import urllib.request
|
|
from typing import Optional
|
|
from urllib.parse import urlsplit
|
|
|
|
from backend.routers.emails import DIRECT_LINK, TRACKERS
|
|
|
|
MAX_BYTES = 20 * 1024 * 1024
|
|
UA = {"User-Agent": "Mozilla/5.0 (C-Stone Invoice Picker)"}
|
|
STRIPE_HOSTED = re.compile(r"^https://invoice\.stripe\.com/i/(acct_\w+)/(\w+)", re.I)
|
|
|
|
|
|
def pdf_url(url: str) -> str:
|
|
"""Stripe-Rechnungsseite (HTML) -> PDF-Download-URL; alles andere unverändert."""
|
|
m = STRIPE_HOSTED.match(url)
|
|
if not m:
|
|
return url
|
|
q = urlsplit(url).query
|
|
return f"https://pay.stripe.com/invoice/{m[1]}/{m[2]}/pdf" + (f"?{q}" if q else "")
|
|
|
|
|
|
def fetch_pdf(url: str, timeout: int = 30) -> Optional[bytes]:
|
|
"""-> PDF-Bytes oder None (kein PDF, z.B. HTML-Login-Seite)."""
|
|
if TRACKERS.match(url): # nur Weiterleitung auflösen, Ziel muss wieder auf der Allowlist stehen
|
|
with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=timeout) as r:
|
|
url = r.geturl()
|
|
if not DIRECT_LINK.search(url):
|
|
return None
|
|
with urllib.request.urlopen(urllib.request.Request(pdf_url(url), headers=UA), timeout=timeout) as r:
|
|
data = r.read(MAX_BYTES + 1)
|
|
if len(data) > MAX_BYTES or not data.startswith(b"%PDF-"):
|
|
return None
|
|
return data
|