feat(test1): X发帖支持文字+视频,媒体经S3中转发完删除
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
ec3cfc2c27
commit
f3860cc3ee
@ -918,6 +918,44 @@ async def x2_jobs_create(body: dict[str, Any]) -> dict[str, Any]:
|
||||
return {"ok": True, "job": job}
|
||||
|
||||
|
||||
@app.post("/api/x2/media/upload")
|
||||
async def x2_media_upload(request: Request) -> dict[str, Any]:
|
||||
"""Upload image/video to S3 staging for engage.post; local temp deleted after upload."""
|
||||
from . import x2_media
|
||||
|
||||
form = await request.form()
|
||||
upload = form.get("file")
|
||||
if upload is None:
|
||||
raise HTTPException(400, "缺少 file")
|
||||
filename = str(getattr(upload, "filename", None) or "media.bin")
|
||||
content_type = str(getattr(upload, "content_type", None) or "")
|
||||
try:
|
||||
data = await upload.read() # type: ignore[attr-defined]
|
||||
except Exception as exc:
|
||||
raise HTTPException(400, f"读取文件失败: {exc}") from exc
|
||||
try:
|
||||
return await asyncio.to_thread(
|
||||
x2_media.upload_media_bytes,
|
||||
data,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(500, f"上传失败: {exc}") from exc
|
||||
|
||||
|
||||
@app.post("/api/x2/media/cleanup")
|
||||
async def x2_media_cleanup(body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""Manual cleanup of staged S3 keys (also runs automatically when job ends)."""
|
||||
from . import x2_media
|
||||
|
||||
payload = body if isinstance(body, dict) else {}
|
||||
keys = payload.get("keys") if isinstance(payload.get("keys"), list) else []
|
||||
return x2_media.cleanup_media_keys([str(k) for k in keys])
|
||||
|
||||
|
||||
@app.post("/api/x2/jobs/{job_id}/cancel")
|
||||
async def x2_jobs_cancel(job_id: str) -> dict[str, Any]:
|
||||
from . import x2_db
|
||||
|
||||
@ -108,6 +108,18 @@ def upload_bytes(data: bytes, key: str, content_type: str = "application/octet-s
|
||||
return public_url_for_key(key)
|
||||
|
||||
|
||||
def delete_object(key: str) -> bool:
|
||||
"""Delete an object from the bucket. Returns True if delete was attempted successfully."""
|
||||
k = str(key or "").strip().lstrip("/")
|
||||
if not k or not s3_enabled():
|
||||
return False
|
||||
try:
|
||||
_client().delete_object(Bucket=settings.s3_bucket, Key=k)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def upload_cover(session_id: str, local_path: str | Path) -> str:
|
||||
key = f"covers/{session_id}.jpg"
|
||||
return upload_file(local_path, key, content_type="image/jpeg")
|
||||
|
||||
@ -204,14 +204,23 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
|
||||
account_username = ""
|
||||
if isinstance(result, dict):
|
||||
account_username = str(result.get("account") or "").strip()
|
||||
incoming_params = job.get("params") if isinstance(job.get("params"), dict) else {}
|
||||
if not account_username:
|
||||
params = job.get("params") if isinstance(job.get("params"), dict) else {}
|
||||
account_username = str(params.get("username") or "").strip().lstrip("@")
|
||||
account_username = str(incoming_params.get("username") or "").strip().lstrip("@")
|
||||
now = time.time()
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
ensure_x2_tables(conn)
|
||||
existing = conn.execute("SELECT params_json FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
params_to_store = incoming_params
|
||||
if not params_to_store and existing:
|
||||
try:
|
||||
params_to_store = json.loads(str(existing["params_json"] or "{}"))
|
||||
except Exception:
|
||||
params_to_store = {}
|
||||
if not isinstance(params_to_store, dict):
|
||||
params_to_store = {}
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO x2_jobs(
|
||||
@ -247,7 +256,7 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
|
||||
str(progress.get("message") or ""),
|
||||
str(job.get("error") or "")[:800],
|
||||
_json_dumps(result if result is not None else {}),
|
||||
_json_dumps(job.get("params") or {}),
|
||||
_json_dumps(params_to_store),
|
||||
str(job.get("createdAt") or job.get("created_at") or ""),
|
||||
str(job.get("updatedAt") or job.get("updated_at") or ""),
|
||||
now,
|
||||
@ -257,7 +266,7 @@ def upsert_job(agent_id: str, job: dict[str, Any]) -> dict[str, Any] | None:
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM x2_jobs WHERE id IN (
|
||||
SELECT id FROM x2_jobs ORDER BY received_at DESC LIMIT -1 OFFSET 500
|
||||
SELECT id FROM x2_jobs ORDER BY received_at DESC LIMIT -1 OFFSET 500
|
||||
)
|
||||
"""
|
||||
)
|
||||
@ -331,6 +340,23 @@ 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
|
||||
|
||||
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 {
|
||||
@ -576,6 +602,8 @@ def cancel_job(job_id: str) -> dict[str, Any] | None:
|
||||
if not jid:
|
||||
return None
|
||||
now_iso = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
out: dict[str, Any] | None = None
|
||||
should_cleanup = False
|
||||
with _lock:
|
||||
conn = _connect()
|
||||
try:
|
||||
@ -602,9 +630,18 @@ def cancel_job(job_id: str) -> dict[str, Any] | None:
|
||||
refreshed = _row_to_dict(
|
||||
conn.execute("SELECT * FROM x2_jobs WHERE id = ?", (jid,)).fetchone()
|
||||
)
|
||||
return _job_to_client(refreshed or d)
|
||||
out = _job_to_client(refreshed or d)
|
||||
should_cleanup = True
|
||||
finally:
|
||||
conn.close()
|
||||
if should_cleanup and out:
|
||||
try:
|
||||
from . import x2_media
|
||||
|
||||
x2_media.cleanup_job_media(out.get("params"))
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def list_cancel_requested(agent_id: str = "") -> list[str]:
|
||||
|
||||
121
backend/app/x2_media.py
Normal file
121
backend/app/x2_media.py
Normal file
@ -0,0 +1,121 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""X2 post media staging on S3 — upload then delete after job ends."""
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import re
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from . import s3_storage
|
||||
from .config import settings
|
||||
|
||||
_ALLOWED_PREFIX = "downloads/x2-media/"
|
||||
_MAX_FILES = 4
|
||||
_MAX_BYTES = 180 * 1024 * 1024 # under Caddy 200MB body limit
|
||||
_ALLOWED_MIME_PREFIXES = ("image/", "video/")
|
||||
_SAFE_NAME = re.compile(r"[^a-zA-Z0-9._-]+")
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
base = Path(str(name or "media.bin")).name
|
||||
cleaned = _SAFE_NAME.sub("_", base).strip("._") or "media.bin"
|
||||
return cleaned[:120]
|
||||
|
||||
|
||||
def is_x2_media_key(key: str) -> bool:
|
||||
k = str(key or "").strip().lstrip("/")
|
||||
return k.startswith(_ALLOWED_PREFIX)
|
||||
|
||||
|
||||
def media_keys_from_params(params: Any) -> list[str]:
|
||||
if not isinstance(params, dict):
|
||||
return []
|
||||
keys: list[str] = []
|
||||
for item in params.get("mediaUrls") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
k = str(item.get("key") or "").strip()
|
||||
if is_x2_media_key(k):
|
||||
keys.append(k)
|
||||
for k in params.get("mediaKeys") or []:
|
||||
ks = str(k or "").strip()
|
||||
if is_x2_media_key(ks):
|
||||
keys.append(ks)
|
||||
# dedupe preserve order
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for k in keys:
|
||||
if k not in seen:
|
||||
seen.add(k)
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
def cleanup_media_keys(keys: list[str] | None) -> dict[str, Any]:
|
||||
deleted: list[str] = []
|
||||
failed: list[str] = []
|
||||
for k in keys or []:
|
||||
if not is_x2_media_key(k):
|
||||
failed.append(k)
|
||||
continue
|
||||
if s3_storage.delete_object(k):
|
||||
deleted.append(k)
|
||||
else:
|
||||
failed.append(k)
|
||||
return {"deleted": deleted, "failed": failed, "count": len(deleted)}
|
||||
|
||||
|
||||
def cleanup_job_media(params: Any) -> dict[str, Any]:
|
||||
return cleanup_media_keys(media_keys_from_params(params))
|
||||
|
||||
|
||||
def upload_media_bytes(
|
||||
data: bytes,
|
||||
*,
|
||||
filename: str = "media.bin",
|
||||
content_type: str = "",
|
||||
) -> dict[str, Any]:
|
||||
if not s3_storage.s3_enabled():
|
||||
raise ValueError("S3 未启用")
|
||||
if not data:
|
||||
raise ValueError("空文件")
|
||||
if len(data) > _MAX_BYTES:
|
||||
raise ValueError(f"文件过大(上限 {_MAX_BYTES // (1024 * 1024)} MB)")
|
||||
|
||||
name = _safe_filename(filename)
|
||||
ctype = (content_type or mimetypes.guess_type(name)[0] or "application/octet-stream").strip()
|
||||
if not any(ctype.startswith(p) for p in _ALLOWED_MIME_PREFIXES):
|
||||
raise ValueError(f"不支持的文件类型: {ctype}(仅图片/视频)")
|
||||
|
||||
day = time.strftime("%Y%m%d", time.gmtime())
|
||||
key = f"{_ALLOWED_PREFIX}{day}/{uuid.uuid4().hex[:12]}_{name}"
|
||||
|
||||
# write temp → upload → delete local immediately
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=Path(name).suffix or ".bin") as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
tmp.write(data)
|
||||
url = s3_storage.upload_file(tmp_path, key, content_type=ctype)
|
||||
if not url:
|
||||
raise ValueError("上传 S3 失败")
|
||||
return {
|
||||
"ok": True,
|
||||
"key": key,
|
||||
"url": url,
|
||||
"filename": name,
|
||||
"mime": ctype,
|
||||
"size": len(data),
|
||||
"public_base": (settings.s3_public_base or settings.s3_endpoint or "").rstrip("/"),
|
||||
"bucket": settings.s3_bucket,
|
||||
}
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
@ -20,7 +20,11 @@ Chrome 加载:`extensions/dylive-helper/dist`
|
||||
2. Web `/x` 下发任务 → 插件领取并在 x.com 执行 → 结果回写本站
|
||||
3. 插件 **X** 页签仍可像原来一样本地点按钮跑任务(独立模式)
|
||||
|
||||
## 顶栏
|
||||
## 发帖(文字 + 视频/图)
|
||||
|
||||
- **TikTok**:Cookie 导出
|
||||
- **X**:原 X2 Ops popup
|
||||
1. Web `/x` → 互动 → 发帖:填文案并选媒体
|
||||
2. 媒体先上传到本站 S3(`downloads/x2-media/…`),任务只带 URL
|
||||
3. 插件打开 compose → 拉取 S3 文件 → 挂载后发帖
|
||||
4. 任务结束(成功/失败/取消)后 **自动删除 S3 对象**;浏览器本地选择在上传后清空
|
||||
|
||||
重新加载扩展目录:`extensions/dylive-helper/dist`(v2.2.0+)
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "dylive Helper",
|
||||
"version": "2.1.2",
|
||||
"version": "2.2.0",
|
||||
"description": "TikTok Cookie + X2 Ops(推送到 dylive /x)",
|
||||
"permissions": ["cookies", "storage", "tabs", "alarms", "scripting", "clipboardWrite"],
|
||||
"host_permissions": [
|
||||
@ -10,6 +10,8 @@
|
||||
"https://x.com/*",
|
||||
"https://twitter.com/*",
|
||||
"https://dylive.nomadro.com/*",
|
||||
"https://s3.nomadro.com/*",
|
||||
"https://feiniu.nomadro.com/*",
|
||||
"http://127.0.0.1/*",
|
||||
"http://localhost/*",
|
||||
"http://127.0.0.1:17888/*"
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "dylive-helper",
|
||||
"version": "2.1.0",
|
||||
"version": "2.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@ -175,6 +175,8 @@ export function PopupApp() {
|
||||
const [eLike, setELike] = useState(10);
|
||||
const [eFollow, setEFollow] = useState(5);
|
||||
const [eText, setEText] = useState("");
|
||||
const [eMedia, setEMedia] = useState<File[]>([]);
|
||||
const [ePostBusy, setEPostBusy] = useState(false);
|
||||
const [mLimit, setMLimit] = useState(200);
|
||||
const [sQuery, setSQuery] = useState("");
|
||||
const [sLikers, setSLikers] = useState("");
|
||||
@ -772,18 +774,80 @@ export function PopupApp() {
|
||||
onChange={(e) => setEText(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className="primary"
|
||||
type="button"
|
||||
style={{ width: "100%", marginTop: 8 }}
|
||||
onClick={() => {
|
||||
const text = eText.trim();
|
||||
if (!text) return show("内容为空");
|
||||
void api.createJob("engage.post", { text, export: "none" });
|
||||
}}
|
||||
>
|
||||
发帖
|
||||
</button>
|
||||
<label className="field" style={{ marginTop: 6 }}>
|
||||
<span>附加媒体(S3,发完删)</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,video/*"
|
||||
multiple
|
||||
onChange={(e) => {
|
||||
setEMedia(Array.from(e.target.files || []).slice(0, 4));
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{eMedia.length > 0 ? (
|
||||
<div style={{ fontSize: 11, opacity: 0.75, marginTop: 4 }}>
|
||||
{eMedia.map((f) => f.name).join(" · ")}{" "}
|
||||
<button type="button" className="ghost" style={{ padding: "0 6px" }} onClick={() => setEMedia([])}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
className="primary"
|
||||
type="button"
|
||||
style={{ width: "100%", marginTop: 8 }}
|
||||
disabled={ePostBusy}
|
||||
onClick={() => {
|
||||
void (async () => {
|
||||
const text = eText.trim();
|
||||
if (!text) return show("内容为空");
|
||||
setEPostBusy(true);
|
||||
try {
|
||||
const cfg = await chrome.storage.local.get(["douyinWebhookUrl", "siteOrigin"]);
|
||||
const origin =
|
||||
String(cfg.siteOrigin || "").replace(/\/$/, "") ||
|
||||
String(cfg.douyinWebhookUrl || "")
|
||||
.replace(/\/api\/x2\/ingest.*$/, "")
|
||||
.replace(/\/$/, "") ||
|
||||
"https://dylive.nomadro.com";
|
||||
const mediaUrls: Array<{ url: string; key: string; mime: string; name: string }> = [];
|
||||
for (const f of eMedia.slice(0, 4)) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", f, f.name);
|
||||
const res = await fetch(`${origin}/api/x2/media/upload`, {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
credentials: "include",
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data?.detail || `上传失败 ${res.status}`);
|
||||
mediaUrls.push({
|
||||
url: String(data.url),
|
||||
key: String(data.key),
|
||||
mime: String(data.mime || f.type),
|
||||
name: String(data.filename || f.name),
|
||||
});
|
||||
}
|
||||
setEMedia([]);
|
||||
await api.createJob("engage.post", {
|
||||
text,
|
||||
export: "none",
|
||||
...(mediaUrls.length ? { mediaUrls } : {}),
|
||||
});
|
||||
setEText("");
|
||||
show(mediaUrls.length ? `已入队(${mediaUrls.length} 媒体)` : "已入队");
|
||||
} catch (err) {
|
||||
show(err instanceof Error ? err.message : String(err));
|
||||
} finally {
|
||||
setEPostBusy(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
{ePostBusy ? "上传中…" : "发帖"}
|
||||
</button>
|
||||
<label className="field" style={{ marginTop: 10 }}>
|
||||
<span>推文链接(回复/转推)</span>
|
||||
<input
|
||||
|
||||
@ -1257,7 +1257,7 @@ async function ensureComposerCaption(text: string, token: string): Promise<HTMLE
|
||||
|
||||
async function postTweet(
|
||||
text: string,
|
||||
media?: Array<{ base64: string; mime: string; name: string }>,
|
||||
media?: Array<{ base64?: string; mime: string; name: string; file?: File }>,
|
||||
): Promise<{
|
||||
ok: boolean;
|
||||
text: string;
|
||||
@ -1287,11 +1287,11 @@ async function postTweet(
|
||||
}
|
||||
if (!box) throw new Error("找不到发帖输入框,请手动打开发帖框后重试");
|
||||
|
||||
const mediaList = (media || []).filter((m) => m?.base64 && m?.mime);
|
||||
const mediaList = (media || []).filter((m) => m && (m.base64 || (m as { file?: File }).file) && m.mime);
|
||||
|
||||
// Media FIRST, caption ONCE after — re-pasting after media doubles Draft.js count (shows -46)
|
||||
if (mediaList.length) {
|
||||
await attachComposerMedia(mediaList);
|
||||
await attachComposerMedia(mediaList as Array<{ base64?: string; mime: string; name: string; file?: File }>);
|
||||
await sleep(800);
|
||||
}
|
||||
await ensureComposerCaption(body, token);
|
||||
@ -1357,6 +1357,35 @@ function base64ToFile(base64: string, mime: string, name: string): File {
|
||||
return new File([bytes], name, { type: mime });
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
async function resolveMediaFiles(
|
||||
media?: Array<{ base64?: string; mime?: string; name?: string; url?: string }>,
|
||||
mediaUrls?: Array<{ url?: string; mime?: string; name?: string; key?: string }>,
|
||||
): Promise<Array<{ base64?: string; mime: string; name: string; file?: File }>> {
|
||||
const out: Array<{ base64?: string; mime: string; name: string; file?: File }> = [];
|
||||
for (const m of media || []) {
|
||||
if (m?.base64 && m?.mime) {
|
||||
out.push({ base64: m.base64, mime: m.mime, name: m.name || "media.bin" });
|
||||
}
|
||||
}
|
||||
for (const m of mediaUrls || []) {
|
||||
const url = String(m?.url || "").trim();
|
||||
if (!url) continue;
|
||||
const mime = String(m.mime || "application/octet-stream");
|
||||
const name = String(m.name || "media.bin");
|
||||
const file = await urlToFile(url, mime, name);
|
||||
out.push({ mime: file.type || mime, name: file.name || name, file });
|
||||
}
|
||||
return out.slice(0, 4);
|
||||
}
|
||||
|
||||
async function findComposerFileInput(): Promise<HTMLInputElement | null> {
|
||||
const pick = () =>
|
||||
document.querySelector(
|
||||
@ -1386,12 +1415,16 @@ async function findComposerFileInput(): Promise<HTMLInputElement | null> {
|
||||
}
|
||||
|
||||
async function attachComposerMedia(
|
||||
media: Array<{ base64: string; mime: string; name: string }>,
|
||||
media: Array<{ base64?: string; mime: string; name: string; file?: File }>,
|
||||
): Promise<void> {
|
||||
const input = await findComposerFileInput();
|
||||
if (!input) throw new Error("找不到媒体上传控件(请先打开发帖框)");
|
||||
|
||||
const files = media.slice(0, 4).map((m) => base64ToFile(m.base64, m.mime, m.name));
|
||||
const files = media.slice(0, 4).map((m) => {
|
||||
if (m.file instanceof File) return m.file;
|
||||
if (m.base64) return base64ToFile(m.base64, m.mime, m.name);
|
||||
throw new Error("媒体缺少数据");
|
||||
});
|
||||
const dt = new DataTransfer();
|
||||
for (const f of files) dt.items.add(f);
|
||||
input.files = dt.files;
|
||||
@ -1625,11 +1658,15 @@ async function runJob(
|
||||
case "engage.post": {
|
||||
const text = String(params.text || "");
|
||||
if (!text.trim()) throw new Error("缺少 text");
|
||||
const media = Array.isArray(params.media)
|
||||
? (params.media as Array<{ base64: string; mime: string; name: string }>)
|
||||
const mediaRaw = Array.isArray(params.media)
|
||||
? (params.media as Array<{ base64?: string; mime?: string; name?: string; url?: string }>)
|
||||
: [];
|
||||
const result = await postTweet(text, media);
|
||||
return { ok: true, result };
|
||||
const mediaUrls = Array.isArray(params.mediaUrls)
|
||||
? (params.mediaUrls as Array<{ url?: string; mime?: string; name?: string; key?: string }>)
|
||||
: [];
|
||||
const resolved = await resolveMediaFiles(mediaRaw, mediaUrls);
|
||||
const result = await postTweet(text, resolved as Array<{ base64: string; mime: string; name: string }>);
|
||||
return { ok: true, result: { ...result, mediaKeys: mediaUrls.map((m) => m.key).filter(Boolean) } };
|
||||
}
|
||||
case "engage.reply": {
|
||||
const text = String(params.text || "");
|
||||
|
||||
@ -652,6 +652,8 @@ export function EngagePanel({
|
||||
const [kw, setKw] = useState("");
|
||||
const [followList, setFollowList] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
const [mediaFiles, setMediaFiles] = useState<File[]>([]);
|
||||
const [postBusy, setPostBusy] = useState(false);
|
||||
const [statusUrl, setStatusUrl] = useState("");
|
||||
const [replyText, setReplyText] = useState("");
|
||||
const [quoteText, setQuoteText] = useState("");
|
||||
@ -722,16 +724,74 @@ export function EngagePanel({
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<div className={panel}>
|
||||
<h3 className={title}>✍️ 发帖</h3>
|
||||
<p className={sub}>文字 + 图片/视频(先上 S3,发完自动删)</p>
|
||||
<textarea className={`${field} mt-3 min-h-[100px]`} value={text} onChange={(e) => setText(e.target.value)} placeholder="说点什么…" />
|
||||
<label className={`${label} mt-2`}>
|
||||
附加媒体(最多 4,图片/视频)
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*,video/*"
|
||||
multiple
|
||||
className={`${field} file:mr-2 file:rounded file:border-0 file:bg-white/10 file:px-2 file:py-1 file:text-xs`}
|
||||
onChange={(e) => {
|
||||
const list = Array.from(e.target.files || []).slice(0, 4);
|
||||
setMediaFiles(list);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{mediaFiles.length > 0 ? (
|
||||
<div className="mt-1 flex flex-wrap gap-1 text-[11px] text-slate-400">
|
||||
{mediaFiles.map((f) => (
|
||||
<span key={`${f.name}-${f.size}`} className="rounded border border-white/10 bg-black/30 px-1.5 py-0.5">
|
||||
{f.name} · {(f.size / 1024 / 1024).toFixed(1)}MB
|
||||
</span>
|
||||
))}
|
||||
<button type="button" className="text-rose-300" onClick={() => setMediaFiles([])}>
|
||||
清空
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className={`${primary} mt-2`}
|
||||
disabled={postBusy}
|
||||
className={`${primary} mt-2 disabled:opacity-50`}
|
||||
onClick={() => {
|
||||
if (!text.trim()) return toast("内容为空", "err");
|
||||
void createJob("engage.post", { text: text.trim() });
|
||||
void (async () => {
|
||||
if (!text.trim()) return toast("内容为空", "err");
|
||||
setPostBusy(true);
|
||||
try {
|
||||
const mediaUrls: Array<{ url: string; key: string; mime: string; name: string; size: number }> = [];
|
||||
for (const f of mediaFiles.slice(0, 4)) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", f, f.name);
|
||||
const res = await fetch("/api/x2/media/upload", { method: "POST", body: fd, credentials: "include" });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data?.detail || data?.message || `上传失败 ${res.status}`);
|
||||
mediaUrls.push({
|
||||
url: String(data.url),
|
||||
key: String(data.key),
|
||||
mime: String(data.mime || f.type || "application/octet-stream"),
|
||||
name: String(data.filename || f.name),
|
||||
size: Number(data.size || f.size || 0),
|
||||
});
|
||||
}
|
||||
// clear local selection after S3 upload
|
||||
setMediaFiles([]);
|
||||
await createJob("engage.post", {
|
||||
text: text.trim(),
|
||||
...(mediaUrls.length ? { mediaUrls } : {}),
|
||||
});
|
||||
setText("");
|
||||
} catch (e) {
|
||||
toast((e as Error).message, "err");
|
||||
} finally {
|
||||
setPostBusy(false);
|
||||
}
|
||||
})();
|
||||
}}
|
||||
>
|
||||
发帖
|
||||
{postBusy ? "上传/入队中…" : "发帖"}
|
||||
</button>
|
||||
</div>
|
||||
<div className={panel}>
|
||||
|
||||
Loading…
Reference in New Issue
Block a user