import{config,hooks,http,lifecycle,log}from"motrix:plugin-api";var ARCHIVE_LINK_RE=/<a[^>]+href="([^"]+\.(?:zip|tar\.gz|tgz|rar|7z|exe|dmg|iso|pkg))"/i;function findArchiveLink(html,baseUrl){let match=ARCHIVE_LINK_RE.exec(html);if(!match?.[1])return null;try{return new URL(match[1],baseUrl).toString()}catch{return null}}var DEFAULT_MAX_BODY=524288;async function isEnabled(){return await config.get("enabled")!==!1}async function readMaxBody(){let v=await config.get("maxBodyBytes");return typeof v=="number"&&v>0?v:DEFAULT_MAX_BODY}hooks.beforeCreate(async ctx=>{if(ctx.type!=="http"||!await isEnabled())return ctx;let url=ctx.uris[0];if(!url)return ctx;try{if(!((await http.request({method:"HEAD",url,responseType:"text",timeoutMs:5e3})).headers.find(h=>h.name.toLowerCase()==="content-type")?.value??"").includes("text/html"))return ctx;let maxBody=await readMaxBody(),res=await http.request({method:"GET",url,responseType:"text",timeoutMs:1e4,maxBodyBytes:maxBody}),archiveUrl=findArchiveLink(res.body,url);archiveUrl&&(log.info("scraper rewrote URL",{from:url,to:archiveUrl}),ctx.update({uris:[archiveUrl]}))}catch(e){log.warn("scraper failed",{err:String(e)})}return ctx});lifecycle.onDeactivate(async()=>{log.info("shutting down scraper-hook")});
