feat(mcp): tmpfiles.org fallback for agent uploads, 6 h slot expiry, DELETE /api/uploads
claude.ai's sandbox can upload to tmpfiles.org but their /dl/ links are signed with a short-lived stamp and 302 to an HTML page once stale, which yt-dlp cannot use. file_hosts.resolve() reads the page and takes the fresh /dl/ link before download. create_upload now tells the agent to try our upload_url first and fall back to tmpfiles.org. Unused slots expire after 6 h (was 24) via _sweep_pending_uploads, and DELETE drops one early.
This commit is contained in:
parent
0a21de29a2
commit
f4c227e624
5 changed files with 150 additions and 15 deletions
47
app.py
47
app.py
|
|
@ -1034,13 +1034,8 @@ async def cleanup_jobs():
|
|||
|
||||
# Agent upload slots: expire with their file (the file sweep below
|
||||
# removes it; a slot whose file is gone or too old is dropped).
|
||||
for uid, slot in list(pending_uploads.items()):
|
||||
if now - slot["created"] > UPLOAD_TTL_SECONDS:
|
||||
pending_uploads.pop(uid, None)
|
||||
try:
|
||||
os.remove(slot["path"])
|
||||
except OSError:
|
||||
pass
|
||||
for uid in _sweep_pending_uploads(now):
|
||||
print(f"🧹 Expired agent upload slot {uid}")
|
||||
|
||||
# Cleanup Uploads
|
||||
for filename in os.listdir(UPLOAD_DIR):
|
||||
|
|
@ -1913,7 +1908,9 @@ LAYOUT_IMPLIES = {
|
|||
# process time so a leaked id cannot start a job on someone else's account.
|
||||
# --------------------------------------------------------------------------- #
|
||||
pending_uploads: Dict[str, Dict] = {}
|
||||
UPLOAD_TTL_SECONDS = int(os.environ.get("UPLOAD_TTL_SECONDS", str(24 * 3600)))
|
||||
# Unconsumed slots are gone after this; a consumed one becomes the job's
|
||||
# input and follows the job's own retention instead.
|
||||
UPLOAD_TTL_SECONDS = int(os.environ.get("UPLOAD_TTL_SECONDS", str(6 * 3600)))
|
||||
|
||||
|
||||
def _upload_url_base(request):
|
||||
|
|
@ -1947,7 +1944,9 @@ async def create_upload(request: Request):
|
|||
"max_mb": MAX_FILE_SIZE_MB,
|
||||
"expires_in": UPLOAD_TTL_SECONDS,
|
||||
"hint": "PUT the raw video bytes to upload_url (e.g. curl -T video.mp4 <upload_url>), "
|
||||
"then call /api/process (or the process_video tool) with this upload_id.",
|
||||
"then call /api/process (or the process_video tool) with this upload_id. "
|
||||
"The slot and file are deleted after expires_in seconds if unused, or "
|
||||
"DELETE this URL to drop them sooner.",
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -1982,6 +1981,36 @@ async def put_upload(upload_id: str, request: Request):
|
|||
"hint": "Now call /api/process with upload_id."}
|
||||
|
||||
|
||||
@app.delete("/api/uploads/{upload_id}")
|
||||
async def delete_upload(upload_id: str, request: Request):
|
||||
"""Drop a slot and its file before it expires (owner only in cloud mode)."""
|
||||
slot = pending_uploads.get(upload_id)
|
||||
if not slot or (BILLING_ENABLED and slot.get("user_id") != await _owner_id(request)):
|
||||
raise HTTPException(status_code=404, detail="Unknown or expired upload_id")
|
||||
pending_uploads.pop(upload_id, None)
|
||||
try:
|
||||
os.remove(slot["path"])
|
||||
except OSError:
|
||||
pass
|
||||
return {"deleted": upload_id}
|
||||
|
||||
|
||||
def _sweep_pending_uploads(now=None):
|
||||
"""Expire agent upload slots older than UPLOAD_TTL_SECONDS (file included).
|
||||
Returns the ids removed. Called from the cleanup loop; pure enough to test."""
|
||||
now = now or time.time()
|
||||
gone = []
|
||||
for uid, slot in list(pending_uploads.items()):
|
||||
if now - slot["created"] > UPLOAD_TTL_SECONDS:
|
||||
pending_uploads.pop(uid, None)
|
||||
try:
|
||||
os.remove(slot["path"])
|
||||
except OSError:
|
||||
pass
|
||||
gone.append(uid)
|
||||
return gone
|
||||
|
||||
|
||||
def _take_pending_upload(upload_id, user_id):
|
||||
"""The completed upload for this caller, or an HTTPException."""
|
||||
slot = pending_uploads.get(upload_id)
|
||||
|
|
|
|||
64
file_hosts.py
Normal file
64
file_hosts.py
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
"""Resolvers for throwaway file hosts agents upload to when they cannot reach
|
||||
our own upload endpoint (claude.ai's sandbox could reach tmpfiles.org but not
|
||||
0x0.st, for instance).
|
||||
|
||||
tmpfiles.org: the `/dl/<stamp>.<sig>/<id>/<name>` link an upload returns is
|
||||
signed with a short-lived stamp. Once stale it 302s to the HTML page
|
||||
`/<id>/<name>`, whose Download button carries a freshly signed `/dl/` link;
|
||||
yt-dlp then chokes on the HTML. Resolving through the page first gives the
|
||||
live link every time. Files there expire 60 minutes after upload.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import urllib.request
|
||||
from urllib.parse import urlparse
|
||||
|
||||
_TMPFILES_HOSTS = ("tmpfiles.org", "www.tmpfiles.org")
|
||||
_DL_RE = re.compile(r'href="(https://tmpfiles\.org/dl/[^"]+)"')
|
||||
|
||||
|
||||
def is_tmpfiles(url: str) -> bool:
|
||||
try:
|
||||
return urlparse(url).hostname in _TMPFILES_HOSTS
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _page_url(url: str) -> str:
|
||||
parsed = urlparse(url)
|
||||
parts = [p for p in parsed.path.split("/") if p]
|
||||
if parts and parts[0] == "dl":
|
||||
# /dl/<stamp>/<id>/<name> -> /<id>/<name>
|
||||
parts = parts[2:] if len(parts) >= 3 else parts[1:]
|
||||
return f"https://tmpfiles.org/{'/'.join(parts)}"
|
||||
|
||||
|
||||
def resolve_tmpfiles(url: str, fetch=None) -> str:
|
||||
"""The currently valid direct-download URL for a tmpfiles.org link.
|
||||
|
||||
``fetch(url) -> str`` is injectable for tests. Falls back to the input
|
||||
on any failure so the caller's normal error path still runs."""
|
||||
fetch = fetch or _fetch
|
||||
try:
|
||||
html = fetch(_page_url(url))
|
||||
m = _DL_RE.search(html)
|
||||
return m.group(1) if m else url
|
||||
except Exception:
|
||||
return url
|
||||
|
||||
|
||||
def resolve(url: str) -> str:
|
||||
"""Swap a known temp-host link for one yt-dlp can download, else return it."""
|
||||
if is_tmpfiles(url):
|
||||
fresh = resolve_tmpfiles(url)
|
||||
if fresh != url:
|
||||
print("🔗 tmpfiles.org link refreshed for download")
|
||||
return fresh
|
||||
return url
|
||||
|
||||
|
||||
def _fetch(url: str) -> str:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (OpenShorts)"})
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
return r.read(200_000).decode("utf-8", "ignore")
|
||||
4
main.py
4
main.py
|
|
@ -691,6 +691,10 @@ def download_youtube_video(url, output_dir="."):
|
|||
# before handing the URL to yt-dlp.
|
||||
from security_utils import assert_public_url
|
||||
assert_public_url(url)
|
||||
# Throwaway hosts agents fall back to (tmpfiles.org) hand out short-lived
|
||||
# signed links; refresh through the host's page so yt-dlp gets the file.
|
||||
import file_hosts
|
||||
url = file_hosts.resolve(url)
|
||||
|
||||
print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}")
|
||||
print("📥 Downloading video from YouTube...")
|
||||
|
|
|
|||
|
|
@ -76,8 +76,9 @@ TOOLS = [
|
|||
"source_url": {
|
||||
"type": "string",
|
||||
"description": "Public video URL, passed through exactly as the user gave it "
|
||||
"(YouTube watch/short/live URL, or a direct video file URL). "
|
||||
"The server does the downloading. Omit when using upload_id.",
|
||||
"(YouTube watch/short/live URL, a direct video file URL, or a "
|
||||
"tmpfiles.org link from the create_upload fallback). The server "
|
||||
"does the downloading. Omit when using upload_id.",
|
||||
},
|
||||
"upload_id": {
|
||||
"type": "string",
|
||||
|
|
@ -144,10 +145,14 @@ TOOLS = [
|
|||
"Use when the user hands you a video FILE instead of a link. Returns "
|
||||
"an upload_url: send the file's raw bytes to it with an HTTP PUT "
|
||||
"(for example `curl -T video.mp4 <upload_url>`), then call "
|
||||
"process_video with the returned upload_id. The slot expires after "
|
||||
"24 hours; max size is returned as max_mb. If you cannot make HTTP "
|
||||
"requests from your environment, ask the user to run the curl "
|
||||
"command or to share a public link instead."
|
||||
"process_video with the returned upload_id. Unused slots are "
|
||||
"deleted after expires_in seconds (6 h); max size is max_mb. "
|
||||
"FALLBACK if your sandbox cannot reach upload_url: upload the file "
|
||||
"to tmpfiles.org (`curl -F file=@video.mp4 https://tmpfiles.org/api/v1/upload`), "
|
||||
"and pass the returned url to process_video as source_url right "
|
||||
"away (their files expire after 60 minutes; the server refreshes "
|
||||
"the signed download link itself). Otherwise ask the user to run "
|
||||
"the curl command or to share a public link."
|
||||
),
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
|
|
|
|||
|
|
@ -108,3 +108,36 @@ def test_unknown_or_unfinished_upload_id(dirs):
|
|||
slot = _tool_payload(_mcp("create_upload", {}))
|
||||
payload = _tool_payload(_mcp("process_video", {"upload_id": slot["upload_id"], "confirm_rights": True}))
|
||||
assert "PUT" in payload["error"]
|
||||
|
||||
|
||||
def test_sweep_expires_old_slots(dirs, monkeypatch):
|
||||
slot = _tool_payload(_mcp("create_upload", {}))
|
||||
path = app_module.pending_uploads[slot["upload_id"]]["path"]
|
||||
open(path, "wb").write(b"x")
|
||||
assert slot["upload_id"] not in app_module._sweep_pending_uploads(now=__import__("time").time() + 1)
|
||||
gone = app_module._sweep_pending_uploads(now=__import__("time").time() + app_module.UPLOAD_TTL_SECONDS + 1)
|
||||
assert slot["upload_id"] in gone and not os.path.exists(path)
|
||||
|
||||
|
||||
def test_delete_upload(dirs):
|
||||
slot = _tool_payload(_mcp("create_upload", {}))
|
||||
async def _del():
|
||||
async with _client() as c:
|
||||
return await c.delete(f"/api/uploads/{slot['upload_id']}")
|
||||
assert asyncio.run(_del()).status_code == 200
|
||||
assert slot["upload_id"] not in app_module.pending_uploads
|
||||
|
||||
|
||||
def test_tmpfiles_link_is_refreshed_through_the_page():
|
||||
import file_hosts
|
||||
stale = "https://tmpfiles.org/dl/1787841143.abc/wAwNGnPW0lXW/video.mp4"
|
||||
fresh = "https://tmpfiles.org/dl/1787841582.def/wAwNGnPW0lXW/video.mp4"
|
||||
seen = {}
|
||||
def fetch(url):
|
||||
seen["page"] = url
|
||||
return f'<a href="{fresh}">Download</a>'
|
||||
assert file_hosts.resolve_tmpfiles(stale, fetch=fetch) == fresh
|
||||
assert seen["page"] == "https://tmpfiles.org/wAwNGnPW0lXW/video.mp4"
|
||||
assert file_hosts.resolve_tmpfiles("https://tmpfiles.org/wAwNGnPW0lXW/video.mp4", fetch=fetch) == fresh
|
||||
assert file_hosts.resolve_tmpfiles(stale, fetch=lambda u: "<html>no link</html>") == stale
|
||||
assert not file_hosts.is_tmpfiles("https://youtube.com/watch?v=x")
|
||||
|
|
|
|||
Loading…
Reference in a new issue