Files
order-notification-automation/extension/worker.js
T

118 lines
6.1 KiB
JavaScript

importScripts('local-config.js', 'capture.js');
const config = globalThis.ORDER_LOCAL_CONFIG;
const state = value => chrome.storage.session.set({ lastExport:value });
let running = false;
async function requestLocal(route, body) {
const response = await fetch(config.endpoint + route, {
method: body ? 'POST' : 'GET',
headers: { 'Content-Type':'application/json', 'X-Order-Token':config.token },
body: body ? JSON.stringify(body) : undefined,
signal: AbortSignal.timeout(10000)
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || '本地导出服务返回错误。');
return result;
}
async function collectAssets(snapshot) {
const allowed = 'https://bpm.skyworthdigital.com';
snapshot.images = [];
const jobs = [
...[...new Set(snapshot.stylesheetUrls || [])].map(url => ({url,kind:'css'})),
...(snapshot.imageUrls || []).map(url => ({url,kind:'image'}))
];
if (jobs.length > 100) throw new Error('页面资源过多,请确认当前标签页是单个订单详情。');
let total = 0;
const collected = await Promise.all(jobs.map(async ({url,kind}) => {
try {
if (kind === 'image' && /^data:image\/(png|jpeg|gif|webp);base64,/i.test(url)) { snapshot.images.push({url,data:url}); return; }
if (new URL(url).origin !== allowed) throw new Error('不属于 BPM 站点');
const response = await fetch(url,{credentials:'include',redirect:'error',signal:AbortSignal.timeout(15000)});
if (!response.ok) throw new Error('读取失败');
const bytes = new Uint8Array(await response.arrayBuffer());
total += bytes.length;
if (bytes.length > 3*1024*1024 || total > 12*1024*1024) throw new Error('资源超过大小限制');
const mime = (response.headers.get('content-type') || '').split(';')[0];
if (kind === 'css') {
if (!/text\/css/i.test(mime)) throw new Error('样式资源格式不匹配');
return {url,css:new TextDecoder('utf-8').decode(bytes)};
} else {
if (!/^image\/(png|jpeg|gif|webp)$/i.test(mime)) throw new Error('图片格式暂不支持');
let binary = '';
for (let i=0;i<bytes.length;i+=32768) binary += String.fromCharCode(...bytes.subarray(i,i+32768));
snapshot.images.push({url,data:`data:${mime};base64,${btoa(binary)}`});
}
} catch {
snapshot.warnings.push(kind === 'css' ? '有一项页面样式未能嵌入,请核对输出排版。' : '有一张图片未能嵌入,请核对图片区域。');
}
}));
const cssByUrl = new Map(collected.filter(Boolean).map(item=>[item.url,item.css]));
snapshot.styles = snapshot.styleSources ? snapshot.styleSources.map(item=>item.url ? cssByUrl.get(item.url) || '' : item.text || '') : [
...(snapshot.stylesheetUrls || []).map(url=>cssByUrl.get(url) || ''), ...snapshot.styles
];
delete snapshot.styleSources;
delete snapshot.stylesheetUrls;
delete snapshot.imageUrls;
snapshot.warnings = [...new Set(snapshot.warnings)];
return snapshot;
}
async function exportTab(tabId) {
if (running) throw new Error('正在导出,请稍候。');
running = true;
try {
await state({status:'running',message:'正在连接本地工具…'});
await requestLocal('/health');
const tab = await chrome.tabs.get(tabId);
if (!tab.url || new URL(tab.url).origin !== 'https://bpm.skyworthdigital.com') throw new Error('请先切换到 BPM 订单详情标签页。');
const results = await chrome.scripting.executeScript({target:{tabId},func:captureOrder});
const snapshot = results[0]?.result;
if (!snapshot) throw new Error('未采集到订单页面,请刷新订单后再试。');
if (snapshot.missing.length) throw new Error('缺少'+snapshot.missing.join('、')+'。请检查是否进入正确的订单详情页。');
await state({status:'running',message:'正在生成 '+snapshot.metadata.order+' 的 PDF…'});
const accepted = await requestLocal('/export', await collectAssets(snapshot));
await state({status:'running',jobId:accepted.jobId,message:'正在排版 '+snapshot.metadata.order+' 的 PDF…'});
let result;
const deadline=Date.now()+120000;
while (Date.now()<deadline) {
result=await requestLocal('/jobs/'+accepted.jobId);
if (result.status!=='running') break;
await new Promise(resolve=>setTimeout(resolve,750));
}
if (!result || result.status==='running') throw new Error('排版用时较长,请检查输出目录,稍后重试。');
if (result.status==='error') throw new Error(result.error);
await state({status:'success',message:'已保存',...result});
await chrome.action.setBadgeText({text:'✓'});
await chrome.action.setBadgeBackgroundColor({color:'#13765b'});
return result;
} catch(error) {
const message = /Failed to fetch|fetch failed|NetworkError/i.test(error.message) ? '无法连接本地工具。请先双击“启动工具.cmd”,保持窗口运行。' : error.message;
await state({status:'error',message});
await chrome.action.setBadgeText({text:'!'});
await chrome.action.setBadgeBackgroundColor({color:'#b44334'});
throw new Error(message);
} finally { running = false; }
}
async function currentState() {
let value=(await chrome.storage.session.get('lastExport')).lastExport;
if (value?.status==='running' && !running) {
try {
if (!value.jobId) throw new Error('上次采集被中断,请检查输出目录后重试。');
const job=await requestLocal('/jobs/'+value.jobId);
if (job.status==='success') value={...job,message:'已保存'};
else if (job.status==='error') value={status:'error',message:job.error};
} catch(error) {value={status:'error',message:error.message};}
await state(value);
}
return value;
}
chrome.runtime.onMessage.addListener((message,sender,sendResponse) => {
if (sender.id !== chrome.runtime.id) return;
if (message.type==='status') {currentState().then(value=>sendResponse({ok:true,value}),error=>sendResponse({ok:false,error:error.message}));return true;}
if (message.type !== 'export') return;
exportTab(message.tabId).then(result=>sendResponse({ok:true,result}),error=>sendResponse({ok:false,error:error.message}));
return true;
});