import{b as r}from"./browser-polyfill-CZ_dLIqp.js";import{n as v,a as k}from"./downloadIntent-Dv31jC2S.js";import{g as d}from"./settings-Bo6W9Drl.js";const C="org.gdown.nativehost";async function L(e){return r.runtime.sendNativeMessage(C,{action:"addUri",...e})}async function I(){return r.runtime.sendNativeMessage(C,{action:"focus"})}const p="history";async function H(){const t=(await r.storage.local.get([p]))[p];return Array.isArray(t)?t:[]}async function M(e){await r.storage.local.set({[p]:e.slice(0,300)})}async function T(e){const t=await H(),n=t.findIndex(o=>o.gid===e.gid);n>=0?t[n]=e:t.unshift(e),await M(t)}const y=8e3,A=7e3,D="gomdown-helper-download-context-menu-option",c=new Map,w=new Map,g=new Map,m=new Map,a=new Map,h=new Map;function l(e){try{const t=new URL(e),n=(t.pathname||"/").replace(/\/+$/,"")||"/";return`${t.protocol}//${t.host}${n}`.toLowerCase()}catch{return String(e||"").toLowerCase()}}function i(e){const t=Date.now();for(const[n,o]of e.entries())o<=t&&e.delete(n)}function R(e){const t=Date.now()+y;w.set(v(e),t),g.set(l(e),t)}function q(e){!Number.isInteger(e)||(e??-1)<0||h.set(e,Date.now()+y)}function N(e){i(w),i(g);const t=v(e);return w.has(t)||g.has(l(e))}function _(e){return i(h),!Number.isInteger(e)||(e??-1)<0?!1:h.has(e)}function E(e){return i(m),m.has(l(e))}function F(e){m.set(l(e),Date.now()+A)}function O(e){return i(a),!!e&&a.has(e)}function P(e){e&&a.set(e,Date.now()+y)}async function $(){try{await I()}catch{}}async function S(e,t=""){if(E(e))return{ok:!1,error:"duplicate transfer suppressed"};const n=await d();if(!n.extensionStatus)return{ok:!1,error:"extension disabled"};if(!n.motrixAPIkey)return{ok:!1,error:"motrixAPIkey is not set"};try{const o=await L({url:e,rpcPort:n.motrixPort,rpcSecret:n.motrixAPIkey,referer:t,split:64});if(!o?.ok)return{ok:!1,error:o?.error||"native host addUri failed"};n.activateAppOnDownload&&await $(),F(e);const s=String(o?.gid||o?.requestId||`pending-${Date.now()}`),U=(()=>{try{return new URL(e).pathname}catch{return""}})().split("/").filter(Boolean).pop()||e;return await T({gid:s,downloader:"native",startTime:new Date().toISOString(),icon:"/images/32.png",name:decodeURIComponent(U),path:null,status:o?.pending?"queued":"downloading",size:0,downloaded:0}),n.enableNotifications&&await r.notifications.create(`gomdown-transfer-${Date.now()}`,{type:"basic",iconUrl:"/images/icon-large.png",title:"Gomdown Helper",message:"Download sent to gdown"}),{ok:!0}}catch(o){return{ok:!1,error:String(o)}}}async function z(e){if(e.type!=="main_frame"||(e.method||"").toUpperCase()!=="GET"||typeof e.statusCode=="number"&&(e.statusCode<200||e.statusCode>299))return!1;const t=await d();if(!t.extensionStatus||!t.motrixAPIkey)return!1;const n=String(Array.isArray(e?.responseHeaders)&&e.responseHeaders.find(s=>String(s?.name||"").toLowerCase()==="content-length")?.value||""),o=Number(n||0);return t.minFileSize>0&&o>0&&o<t.minFileSize*1024*1024?!1:k(e)}async function G(e){if(O(e.requestId)||!await z(e))return;const n=c.get(e.requestId),o=String(n?.documentUrl||n?.originUrl||n?.initiator||n?.url||"");(await S(e.url,o)).ok&&(P(e.requestId),R(e.url),q(e.tabId))}async function u(){const e=r.downloads;if(!e.setShelfEnabled)return;const t=await d();if(!t.extensionStatus)return;const n=t.useNativeHost?!1:!t.hideChromeBar;await e.setShelfEnabled(n)}function b(){r.downloads.onCreated.addListener(async e=>{await u();const t=e,n=t.finalUrl||t.url||"";!N(n)&&!_(t.tabId)||(await r.downloads.cancel(e.id).catch(()=>null),await r.downloads.erase({id:e.id}).catch(()=>null),await r.downloads.removeFile(e.id).catch(()=>null))})}function x(){r.webRequest.onSendHeaders.addListener(e=>{c.set(e.requestId,e)},{urls:["<all_urls>"]},["requestHeaders","extraHeaders"]),r.webRequest.onErrorOccurred.addListener(e=>{c.delete(e.requestId),a.delete(String(e.requestId))},{urls:["<all_urls>"]}),r.webRequest.onCompleted.addListener(e=>{c.delete(e.requestId),a.delete(String(e.requestId))},{urls:["<all_urls>"]}),r.webRequest.onHeadersReceived.addListener(e=>{G(e)},{urls:["<all_urls>"]},["responseHeaders"])}function f(){r.contextMenus.removeAll().then(async()=>{const e=await d();e.showContextOption&&r.contextMenus.create({id:D,title:"Download with Gomdown",visible:e.showContextOption,contexts:["all"]})}),r.contextMenus.onClicked.addListener(async e=>{const t=e.linkUrl||e.srcUrl||e.pageUrl;t&&await S(t)})}r.runtime.onMessage.addListener((e,t)=>{if(e?.type!=="capture-link-download")return;const n=String(e?.url||"").trim();if(!n)return Promise.resolve({ok:!1,error:"url is empty"});const o=Number(t?.tab?.id);return S(n,String(e?.referer||"")).then(s=>(s.ok&&(R(n),q(o)),s))});r.runtime.onInstalled.addListener(()=>{x(),b(),f(),u()});r.runtime.onStartup.addListener(()=>{x(),b(),f(),u()});r.storage.onChanged.addListener((e,t)=>{t==="sync"&&((e.hideChromeBar||e.useNativeHost||e.extensionStatus)&&u(),e.showContextOption&&f())});x();b();f();u();
