fix(test1): X发帖媒体改为后台下载,失败不再删S3
content script 在 x.com 上 fetch S3 会 Failed to fetch;改走 background host_permissions,且 failed 任务保留媒体以便重试。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
0e80a5faa1
commit
ba2ab0400a
@ -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 {
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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": [
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dylive-helper",
|
||||
"version": "2.2.0",
|
||||
"version": "2.2.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -1358,11 +1358,35 @@ function base64ToFile(base64: string, mime: string, name: string): File {
|
||||
}
|
||||
|
||||
async function urlToFile(url: string, mime: string, name: string): Promise<File> {
|
||||
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(
|
||||
|
||||
Loading…
Reference in New Issue
Block a user