const e="https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis",t="https://dashscope.aliyuncs.com/api/v1/tasks/",a="https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";function s(e){return e&&e.startsWith("http://")?e.replace(/^http:\/\//i,"https://"):e}chrome.runtime.onInstalled.addListener(()=>{chrome.contextMenus.create({id:"ctx_collect_image",title:"✨ 采集此图片到编辑器",contexts:["image"]})}),chrome.contextMenus.onClicked.addListener((e,t)=>{"ctx_collect_image"===e.menuItemId&&chrome.tabs.sendMessage(t.id,{action:"context_add_image",url:e.srcUrl}).catch(()=>console.log("请刷新页面后重试"))}),chrome.runtime.onMessage.addListener((o,i,n)=>"translate_image"===o.action?(async function(a,o){const{apiKey:i,imageUrl:n,sourceLang:r,targetLang:c}=a;try{const a=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-DashScope-Async":"enable"},body:JSON.stringify({model:"qwen-mt-image",input:{image_url:n,source_lang:r,target_lang:c}})}),m=await a.json();if(m.code)throw new Error(m.message);for(let e=0;e<45;e++){await new Promise(e=>setTimeout(e,2e3));const e=await fetch(`${t}${m.output.task_id}`,{headers:{Authorization:`Bearer ${i}`}}),a=await e.json();if("SUCCEEDED"===a.output.task_status){return void o({success:!0,url:s(a.output.image_url)})}if("FAILED"===a.output.task_status)throw new Error(a.output.message)}throw new Error("翻译超时")}catch(m){o({success:!1,error:m.message})}}(o.data,n),!0):"edit_image"===o.action?(async function(e,t){const{apiKey:o,imageUrl:i,prompt:n,negative_prompt:r,size:c}=e,m={model:"qwen-image-edit-plus",input:{messages:[{role:"user",content:[{image:i},{text:n}]}]},parameters:{n:1,prompt_extend:!0,watermark:!1}};r&&(m.parameters.negative_prompt=r);c&&(m.parameters.size=c);try{const e=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify(m)}),i=await e.json();if(i.code)throw new Error(i.message);if(!(i.output&&i.output.choices&&i.output.choices[0].message.content))throw new Error("API 返回格式异常");{const e=i.output.choices[0].message.content[0].image;t({success:!0,url:s(e)})}}catch(u){t({success:!1,error:u.message})}}(o.data,n),!0):"download_images"===o.action?(function(e,t){const a=e.folder||"AI_Images";e.files.forEach(e=>{chrome.downloads.download({url:s(e.url),filename:`${a}/${e.filename}`,conflictAction:"uniquify"})}),t({success:!0})}(o,n),!0):void 0);
