From ba2ab0400a8c9bcd2e9c320c03c8eab6faf81020 Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 15 Aug 2026 08:07:27 -0500 Subject: [PATCH] =?UTF-8?q?fix(test1):=20X=E5=8F=91=E5=B8=96=E5=AA=92?= =?UTF-8?q?=E4=BD=93=E6=94=B9=E4=B8=BA=E5=90=8E=E5=8F=B0=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=EF=BC=8C=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D=E5=88=A0S3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit content script 在 x.com 上 fetch S3 会 Failed to fetch;改走 background host_permissions,且 failed 任务保留媒体以便重试。 Co-authored-by: Cursor --- backend/app/x2_db.py | 33 ++++++------ backend/app/x_clips_pipeline.py | 8 +-- extensions/dylive-helper/manifest.json | 2 +- extensions/dylive-helper/package.json | 2 +- extensions/dylive-helper/src/background.ts | 59 ++++++++++++++++++++++ extensions/dylive-helper/src/content.ts | 34 +++++++++++-- 6 files changed, 111 insertions(+), 27 deletions(-) diff --git a/backend/app/x2_db.py b/backend/app/x2_db.py index 8a31796..bd6165e 100644 --- a/backend/app/x2_db.py +++ b/backend/app/x2_db.py @@ -340,23 +340,24 @@ def ingest_payload(body: dict[str, Any]) -> dict[str, Any]: f"{job.get('kind') or 'job'} → {st}", {"job_id": job.get("id"), "status": st, "error": job.get("error")}, ) - # Drop staged S3 media after terminal status - try: - from . import x2_media + # Only drop S3 staging after success/cancel. Keep media on failed so retry can re-fetch. + if st in {"completed", "cancelled"}: + try: + from . import x2_media - params = job.get("params") if isinstance(job.get("params"), dict) else {} - if not params and job_row: - raw = job_row.get("params") if isinstance(job_row.get("params"), dict) else None - if raw: - params = raw - else: - try: - params = json.loads(str(job_row.get("params_json") or "{}")) - except Exception: - params = {} - x2_media.cleanup_job_media(params) - except Exception: - pass + params = job.get("params") if isinstance(job.get("params"), dict) else {} + if not params and job_row: + raw = job_row.get("params") if isinstance(job_row.get("params"), dict) else None + if raw: + params = raw + else: + try: + params = json.loads(str(job_row.get("params_json") or "{}")) + except Exception: + params = {} + x2_media.cleanup_job_media(params) + except Exception: + pass elif event not in {"heartbeat", "accounts.sync"}: add_event(agent_id, event, str(body.get("message") or ""), body) return { diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py index 9cd4730..9b3d93d 100644 --- a/backend/app/x_clips_pipeline.py +++ b/backend/app/x_clips_pipeline.py @@ -488,16 +488,16 @@ class XClipsPipeline: media_key = str(job.get("media_key") or "").strip() clip = str(job.get("clip_path") or "").strip() - # Stage to S3 if needed - if not media_url or not media_key: - if not clip or not Path(clip).is_file(): - raise ValueError("成片文件不存在") + # Prefer re-stage from local clip so retries survive prior S3 cleanup / 404. + if clip and Path(clip).is_file(): staged = await asyncio.to_thread(x2_media.upload_media_file, Path(clip), filename=Path(clip).name) media_url = str(staged.get("url") or "") media_key = str(staged.get("key") or "") if not media_url or not media_key: raise ValueError("S3 暂存失败") x_clips_db.update_x_clip_job(jid, media_url=media_url, media_key=media_key, caption=caption) + elif not media_url or not media_key: + raise ValueError("成片文件不存在且无可用媒体 URL") # Already dispatched? existing_x2 = str(job.get("x2_job_id") or "").strip() diff --git a/extensions/dylive-helper/manifest.json b/extensions/dylive-helper/manifest.json index af91b0a..1e5310d 100644 --- a/extensions/dylive-helper/manifest.json +++ b/extensions/dylive-helper/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "dylive Helper", - "version": "2.2.0", + "version": "2.2.1", "description": "TikTok Cookie + X2 Ops(推送到 dylive /x)", "permissions": ["cookies", "storage", "tabs", "alarms", "scripting", "clipboardWrite"], "host_permissions": [ diff --git a/extensions/dylive-helper/package.json b/extensions/dylive-helper/package.json index 80fb8cd..cbaf0dd 100644 --- a/extensions/dylive-helper/package.json +++ b/extensions/dylive-helper/package.json @@ -1,6 +1,6 @@ { "name": "dylive-helper", - "version": "2.2.0", + "version": "2.2.1", "private": true, "type": "module", "scripts": { diff --git a/extensions/dylive-helper/src/background.ts b/extensions/dylive-helper/src/background.ts index 97b98ac..7a045ef 100644 --- a/extensions/dylive-helper/src/background.ts +++ b/extensions/dylive-helper/src/background.ts @@ -1374,6 +1374,65 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { return false; } + // Content scripts cannot CORS-fetch S3 from x.com — download here with host_permissions. + if (message?.type === "media.fetch") { + void (async () => { + try { + const url = String(message.url || "").trim(); + if (!url) throw new Error("缺少媒体 URL"); + let parsed: URL; + try { + parsed = new URL(url); + } catch { + throw new Error("媒体 URL 无效"); + } + const host = parsed.hostname.toLowerCase(); + const allowed = + host === "s3.nomadro.com" || + host === "feiniu.nomadro.com" || + host.endsWith(".nomadro.com") || + host === "127.0.0.1" || + host === "localhost"; + if (!allowed) throw new Error(`不允许的媒体域名: ${host}`); + if (parsed.protocol !== "https:" && host !== "127.0.0.1" && host !== "localhost") { + throw new Error("仅支持 https 媒体地址"); + } + const res = await fetch(url, { method: "GET", credentials: "omit", cache: "no-store" }); + if (!res.ok) throw new Error(`下载媒体失败 HTTP ${res.status}`); + const mimeHint = String(message.mime || "").trim(); + const nameHint = String(message.name || "").trim() || "media.bin"; + const buf = new Uint8Array(await res.arrayBuffer()); + if (!buf.byteLength) throw new Error("媒体文件为空"); + // ~48MB raw → base64 ~64MB; keep headroom for chrome.runtime messaging + if (buf.byteLength > 48 * 1024 * 1024) { + throw new Error(`媒体过大(${Math.round(buf.byteLength / 1024 / 1024)}MB),请缩短切片`); + } + let binary = ""; + const chunk = 0x8000; + for (let i = 0; i < buf.length; i += chunk) { + const slice = buf.subarray(i, i + chunk); + binary += String.fromCharCode.apply(null, Array.from(slice) as unknown as number[]); + } + const base64 = btoa(binary); + const ctype = + mimeHint || + res.headers.get("content-type")?.split(";")[0]?.trim() || + "application/octet-stream"; + sendResponse({ + ok: true, + base64, + mime: ctype, + name: nameHint, + size: buf.byteLength, + }); + } catch (exc) { + const msg = exc instanceof Error ? exc.message : String(exc); + sendResponse({ ok: false, error: msg || "Failed to fetch" }); + } + })(); + return true; + } + if (message?.type === "content.jobResult") { const jobId = String(message.jobId); const pending = pendingJobs.get(jobId); diff --git a/extensions/dylive-helper/src/content.ts b/extensions/dylive-helper/src/content.ts index ad64b94..0a59f0c 100644 --- a/extensions/dylive-helper/src/content.ts +++ b/extensions/dylive-helper/src/content.ts @@ -1358,11 +1358,35 @@ function base64ToFile(base64: string, mime: string, name: string): File { } async function urlToFile(url: string, mime: string, name: string): Promise { - const res = await fetch(url, { mode: "cors", credentials: "omit" }); - if (!res.ok) throw new Error(`下载媒体失败 HTTP ${res.status}`); - const blob = await res.blob(); - const type = mime || blob.type || "application/octet-stream"; - return new File([blob], name || "media.bin", { type }); + // Must go through background SW: content scripts on x.com are CORS-bound. + const resp = await new Promise<{ + ok?: boolean; + base64?: string; + mime?: string; + name?: string; + error?: string; + }>((resolve, reject) => { + try { + chrome.runtime.sendMessage( + { type: "media.fetch", url, mime, name }, + (r) => { + if (chrome.runtime.lastError) { + reject(new Error(chrome.runtime.lastError.message || "扩展通信失败")); + return; + } + resolve(r || { ok: false, error: "无响应" }); + }, + ); + } catch (e) { + reject(e instanceof Error ? e : new Error(String(e))); + } + }); + if (!resp?.ok || !resp.base64) { + throw new Error(resp?.error || "下载媒体失败(Failed to fetch)"); + } + const type = resp.mime || mime || "application/octet-stream"; + const fname = resp.name || name || "media.bin"; + return base64ToFile(resp.base64, type, fname); } async function resolveMediaFiles(