Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
370 lines (333 loc) · 14.2 KB
/
Copy pathcontent.js
File metadata and controls
370 lines (333 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
(function initializeVCGHelper() {
"use strict";
if (window.VCGVisionHelperLoaded) return;
window.VCGVisionHelperLoaded = true;
const SELECTORS = {
titleInput: [
'input[placeholder*="一句话描述作品"]',
"input.right-form-title",
'input[placeholder*="标题"]',
],
keywordInput: [
'textarea[placeholder*="请添加5~35个关键词"]',
'textarea[placeholder*="关键词"]',
],
textModeCandidates: "button, [role='button'], span",
};
let activeTask = null;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request?.action !== "vcg:start") return false;
if (!Array.isArray(request.records) || request.records.length === 0) {
sendResponse({ ok: false, message: "没有可处理的数据" });
return false;
}
if (activeTask && ["running", "paused", "stopping"].includes(activeTask.state)) {
sendResponse({ ok: false, message: "已有任务正在运行,请先完成或停止" });
return false;
}
activeTask = createTask(request.records);
createConsole(activeTask);
runTask(activeTask).catch((error) => {
if (error?.name !== "AbortError") console.error("VCG 上传助手任务异常", error);
});
sendResponse({ ok: true, taskId: activeTask.id });
return false;
});
function createTask(records) {
return {
id: typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}`,
state: "running",
records,
index: 0,
results: [],
controller: new AbortController(),
pauseWaiters: [],
};
}
function isVisible(element) {
if (!(element instanceof HTMLElement)) return false;
const style = getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;
}
function findVisible(selectors) {
for (const selector of selectors) {
const match = Array.from(document.querySelectorAll(selector)).find(isVisible);
if (match) return match;
}
return null;
}
function findFileElement(fileName) {
return Array.from(document.querySelectorAll("[title]")).find(
(element) => element.getAttribute("title") === fileName && isVisible(element),
);
}
function findTextModeButton() {
const candidate = Array.from(document.querySelectorAll(SELECTORS.textModeCandidates)).find(
(element) => isVisible(element) && element.textContent?.trim() === "文本模式",
);
return candidate?.closest("button, [role='button']") || candidate || null;
}
function abortError() {
return new DOMException("任务已停止", "AbortError");
}
function throwIfAborted(task) {
if (task.controller.signal.aborted) throw abortError();
}
function delay(task, min = 450, max = 850) {
throwIfAborted(task);
const duration = Math.round(Math.random() * (max - min) + min);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
task.controller.signal.removeEventListener("abort", onAbort);
resolve();
}, duration);
function onAbort() {
clearTimeout(timer);
reject(abortError());
}
task.controller.signal.addEventListener("abort", onAbort, { once: true });
});
}
async function checkpoint(task) {
throwIfAborted(task);
while (task.state === "paused") {
await new Promise((resolve) => task.pauseWaiters.push(resolve));
throwIfAborted(task);
}
}
function releasePause(task) {
task.pauseWaiters.splice(0).forEach((resolve) => resolve());
}
async function waitForVisible(task, selectors, timeout = 8000) {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
await checkpoint(task);
const element = findVisible(selectors);
if (element) return element;
await delay(task, 100, 180);
}
return null;
}
function setNativeValue(element, value) {
element.focus();
const prototype = element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
if (setter) setter.call(element, value);
else element.value = value;
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: value }));
element.dispatchEvent(new Event("change", { bubbles: true }));
if (element.value !== value) throw new Error("网页未接受输入值");
}
function pressEnter(element) {
const options = {
key: "Enter",
code: "Enter",
keyCode: 13,
which: 13,
charCode: 13,
bubbles: true,
cancelable: true,
};
element.dispatchEvent(new KeyboardEvent("keydown", options));
element.dispatchEvent(new KeyboardEvent("keypress", options));
element.dispatchEvent(new KeyboardEvent("keyup", options));
}
async function processRecord(task, record) {
const fileElement = findFileElement(record.file_name);
if (!fileElement) return { status: "skipped", reason: "当前页面未找到同名图片" };
const card = fileElement.closest(".card, .ant-card, [data-testid*='card']") || fileElement.parentElement;
if (!card) return { status: "failed", reason: "无法定位图片卡片" };
card.click();
await delay(task, 900, 1300);
await checkpoint(task);
const titleInput = await waitForVisible(task, SELECTORS.titleInput);
if (!titleInput) return { status: "failed", reason: "未找到标题输入框" };
setNativeValue(titleInput, record.title);
await delay(task);
await checkpoint(task);
let keywordInput = findVisible(SELECTORS.keywordInput);
if (!keywordInput) {
const textModeButton = findTextModeButton();
if (!textModeButton) return { status: "failed", reason: "未找到文本模式按钮" };
textModeButton.click();
await delay(task, 400, 700);
keywordInput = await waitForVisible(task, SELECTORS.keywordInput);
}
if (!keywordInput) return { status: "failed", reason: "未找到关键词输入框" };
setNativeValue(keywordInput, record.keywords);
await delay(task, 350, 600);
pressEnter(keywordInput);
await delay(task, 800, 1200);
keywordInput.blur();
return { status: "success", reason: "已填写并触发关键词分词" };
}
async function runTask(task) {
updateConsole(task, "准备处理", "正在检查当前页面");
try {
for (let index = 0; index < task.records.length; index += 1) {
task.index = index;
await checkpoint(task);
const record = task.records[index];
updateConsole(task, `正在处理 ${record.file_name}`, `${index + 1} / ${task.records.length}`);
try {
const result = await processRecord(task, record);
task.results.push({ file_name: record.file_name, ...result });
} catch (error) {
if (error?.name === "AbortError") throw error;
console.error(`处理 ${record.file_name} 失败`, error);
task.results.push({
file_name: record.file_name,
status: "failed",
reason: error instanceof Error ? error.message : "未知错误",
});
}
updateConsole(task, resultSummary(task), `${index + 1} / ${task.records.length}`);
if (index < task.records.length - 1) await delay(task, 700, 1100);
}
task.state = "done";
updateConsole(task, "处理完成", resultSummary(task));
} catch (error) {
if (error?.name !== "AbortError") throw error;
task.state = "stopped";
updateConsole(task, "任务已停止", resultSummary(task));
} finally {
finishConsole(task);
}
}
function resultSummary(task) {
const success = task.results.filter((item) => item.status === "success").length;
const failed = task.results.filter((item) => item.status === "failed").length;
const skipped = task.results.filter((item) => item.status === "skipped").length;
return `成功 ${success},失败 ${failed},跳过 ${skipped}`;
}
function ensureStyles() {
if (document.getElementById("vcgh-style")) return;
const style = document.createElement("style");
style.id = "vcgh-style";
style.textContent = `
#vcgh-console { position: fixed; top: 20px; right: 20px; width: 300px; z-index: 2147483647; color: #edf2f8; background: #172033; border: 1px solid #3a4760; border-radius: 16px; box-shadow: 0 16px 48px rgba(15, 23, 42, .32); font-family: "Segoe UI Variable", "Segoe UI", "Microsoft YaHei UI", sans-serif; overflow: hidden; }
#vcgh-console * { box-sizing: border-box; }
.vcgh-head { display: flex; justify-content: space-between; align-items: center; padding: 15px 16px 10px; }
.vcgh-brand { font-size: 14px; font-weight: 750; }
.vcgh-close { display: none; width: 28px; height: 28px; padding: 0; border: 1px solid #526077; border-radius: 9px; color: #edf2f8; background: transparent; cursor: pointer; }
.vcgh-body { padding: 0 16px 16px; }
.vcgh-title { margin: 0; color: #edf2f8; font-size: 13px; line-height: 1.45; overflow-wrap: anywhere; }
.vcgh-detail { margin: 6px 0 0; color: #b3bfd1; font-size: 12px; line-height: 1.45; }
.vcgh-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 14px; }
.vcgh-button { min-height: 36px; border: 1px solid #526077; border-radius: 11px; color: #edf2f8; background: #222d42; cursor: pointer; font-weight: 700; }
.vcgh-button:hover:not(:disabled) { border-color: #6f96ef; }
.vcgh-button:active:not(:disabled) { transform: translateY(1px); }
.vcgh-button:disabled { cursor: not-allowed; opacity: .5; }
.vcgh-primary { color: #101725; border-color: #6f96ef; background: #6f96ef; }
.vcgh-export { display: none; width: 100%; margin-top: 8px; }
.vcgh-note { margin: 12px 0 0; color: #93a3bb; font-size: 10px; line-height: 1.45; }
@media (prefers-reduced-motion: reduce) { #vcgh-console * { transition: none !important; } }
`;
document.documentElement.appendChild(style);
}
function createConsole(task) {
ensureStyles();
document.getElementById("vcgh-console")?.remove();
const container = document.createElement("section");
container.id = "vcgh-console";
container.setAttribute("aria-label", "VCG 上传助手控制台");
const head = document.createElement("div");
head.className = "vcgh-head";
const brand = document.createElement("div");
brand.className = "vcgh-brand";
brand.textContent = "VCG 上传助手";
const close = document.createElement("button");
close.className = "vcgh-close";
close.type = "button";
close.textContent = "×";
close.setAttribute("aria-label", "关闭控制台");
close.addEventListener("click", () => container.remove());
head.append(brand, close);
const body = document.createElement("div");
body.className = "vcgh-body";
const title = document.createElement("p");
title.className = "vcgh-title";
title.setAttribute("aria-live", "polite");
const detail = document.createElement("p");
detail.className = "vcgh-detail";
const actions = document.createElement("div");
actions.className = "vcgh-actions";
const pause = document.createElement("button");
pause.type = "button";
pause.className = "vcgh-button vcgh-primary";
pause.textContent = "暂停";
pause.addEventListener("click", () => togglePause(task));
const stop = document.createElement("button");
stop.type = "button";
stop.className = "vcgh-button";
stop.textContent = "停止";
stop.addEventListener("click", () => stopTask(task));
actions.append(pause, stop);
const exportButton = document.createElement("button");
exportButton.type = "button";
exportButton.className = "vcgh-button vcgh-export";
exportButton.textContent = "导出处理报告";
exportButton.addEventListener("click", () => exportReport(task));
const note = document.createElement("p");
note.className = "vcgh-note";
note.textContent = "扩展只填写字段,不会自动提交。";
body.append(title, detail, actions, exportButton, note);
container.append(head, body);
document.body.appendChild(container);
task.ui = { container, title, detail, pause, stop, exportButton, close };
}
function updateConsole(task, title, detail) {
if (!task.ui?.container.isConnected) return;
task.ui.title.textContent = title;
task.ui.detail.textContent = detail;
}
function togglePause(task) {
if (task.state === "running") {
task.state = "paused";
task.ui.pause.textContent = "继续";
updateConsole(task, "任务已暂停", `${task.index + 1} / ${task.records.length}`);
} else if (task.state === "paused") {
task.state = "running";
task.ui.pause.textContent = "暂停";
releasePause(task);
updateConsole(task, "任务已继续", `${task.index + 1} / ${task.records.length}`);
}
}
function stopTask(task) {
if (!["running", "paused"].includes(task.state)) return;
task.state = "stopping";
task.ui.pause.disabled = true;
task.ui.stop.disabled = true;
updateConsole(task, "正在停止", resultSummary(task));
releasePause(task);
task.controller.abort();
}
function finishConsole(task) {
if (!task.ui?.container.isConnected) return;
task.ui.pause.disabled = true;
task.ui.stop.disabled = true;
task.ui.close.style.display = "block";
if (task.results.length > 0) task.ui.exportButton.style.display = "block";
}
function csvCell(value) {
let text = String(value ?? "");
if (/^[=+\-@]/.test(text)) text = `'${text}`;
return `"${text.replaceAll('"', '""')}"`;
}
function exportReport(task) {
const lines = [["file_name", "status", "reason"].map(csvCell).join(",")];
task.results.forEach((result) => {
lines.push([result.file_name, result.status, result.reason].map(csvCell).join(","));
});
const blob = new Blob(["\uFEFF", lines.join("\r\n")], { type: "text/csv;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `VCG处理报告-${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
})();