fix: download Bing wallpaper to server disk, auto-clean weekly

- Changed bing-wallpaper endpoint from URL proxy to image downloader
- Saves wallpaper to web/app/wallpapers/YYYY-MM-DD.jpg
- Auto-deletes wallpapers older than 7 days on each request
- Falls back to yesterday's cached file if download fails
- Added Path import for filesystem access

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Your Name
2026-05-31 20:23:55 +08:00
parent e084d90c61
commit 04dda2c419
+51 -9
View File
@@ -7,6 +7,7 @@ Sensitive values are masked in GET responses.
"""
from typing import Optional
from pathlib import Path
import asyncio
import ipaddress
import re
@@ -1263,23 +1264,64 @@ def _retry_to_dict(job: PushRetryJob) -> dict:
}
# ── Bing Daily Wallpaper Proxy (avoids CORS, returns image URL) ──
# ── Bing Daily Wallpaper — download + cache to disk ──
_WALLPAPER_DIR = Path(__file__).resolve().parent.parent.parent / "web" / "app" / "wallpapers"
_WALLPAPER_DIR.mkdir(parents=True, exist_ok=True)
@router.get("/bing-wallpaper", response_model=dict)
async def bing_wallpaper():
"""Proxy the Bing HPImageArchive API and return the daily wallpaper URL.
No auth required — used by the login page."""
"""Download the Bing daily wallpaper, cache to disk, return the local URL.
No auth required — used by the login page.
A cron job or this endpoint itself cleans up wallpapers older than 7 days.
"""
import httpx
from datetime import datetime, timedelta
today = datetime.utcnow().strftime("%Y-%m-%d")
cached = _WALLPAPER_DIR / f"{today}.jpg"
# Return cached version if already downloaded today
if cached.exists() and cached.stat().st_size > 1024:
return {"url": f"/app/wallpapers/{today}.jpg"}
try:
async with httpx.AsyncClient(timeout=8.0) as client:
async with httpx.AsyncClient(timeout=10.0) as client:
# 1. Get today's image metadata
resp = await client.get(
"https://cn.bing.com/HPImageArchive.aspx",
params={"format": "js", "idx": 0, "n": 1, "mkt": "zh-CN"},
)
data = resp.json()
img = (data.get("images") or [{}])[0]
url = img.get("url")
if url:
return {"url": f"https://cn.bing.com{url}"}
img_url = img.get("url")
if not img_url:
raise ValueError("no image url from Bing")
# 2. Download the actual image
img_resp = await client.get(f"https://cn.bing.com{img_url}")
if img_resp.status_code != 200:
raise ValueError(f"Bing returned {img_resp.status_code}")
# 3. Save to disk
cached.write_bytes(img_resp.content)
# 4. Remove wallpapers older than 7 days
cutoff = datetime.utcnow() - timedelta(days=7)
for f in _WALLPAPER_DIR.glob("*.jpg"):
try:
mtime = datetime.utcfromtimestamp(f.stat().st_mtime)
if mtime < cutoff:
f.unlink()
except Exception:
pass
except Exception:
pass
return {"url": None}
# If download fails, try yesterday's cached file
yesterday = (datetime.utcnow() - timedelta(days=1)).strftime("%Y-%m-%d")
yesterday_cached = _WALLPAPER_DIR / f"{yesterday}.jpg"
if yesterday_cached.exists():
return {"url": f"/app/wallpapers/{yesterday}.jpg"}
return {"url": None}
return {"url": f"/app/wallpapers/{today}.jpg"}