import{MessageItemType as y}from"../api/types.js";import{downloadAndDecryptBuffer as l,downloadPlainCdnBuffer as u}from"../cdn/pic-decrypt.js";import{logger as n}from"../util/logger.js";import{getMimeFromFilename as g}from"./mime.js";import{silkToWav as _}from"./silk-transcode.js";const c=100*1024*1024;async function M(o,f){const{cdnBaseUrl:s,saveMedia:m,log:v,errLog:p,label:a}=f,r={};if(o.type===y.IMAGE){const e=o.image_item;if(!e?.media?.encrypt_query_param)return r;const i=e.aeskey?Buffer.from(e.aeskey,"hex").toString("base64"):e.media.aes_key;n.debug(`${a} image: encrypt_query_param=${e.media.encrypt_query_param.slice(0,40)}... hasAesKey=${!!i} aeskeySource=${e.aeskey?"image_item.aeskey":"media.aes_key"}`);try{const t=i?await l(e.media.encrypt_query_param,i,s,`${a} image`):await u(e.media.encrypt_query_param,s,`${a} image-plain`),d=await m(t,void 0,"inbound",c);r.decryptedPicPath=d.path,n.debug(`${a} image saved: ${d.path}`)}catch(t){n.error(`${a} image download/decrypt failed: ${String(t)}`),p(`weixin ${a} image download/decrypt failed: ${String(t)}`)}}else if(o.type===y.VOICE){const e=o.voice_item;if(!e?.media?.encrypt_query_param||!e.media.aes_key)return r;try{const i=await l(e.media.encrypt_query_param,e.media.aes_key,s,`${a} voice`);n.debug(`${a} voice: decrypted ${i.length} bytes, attempting silk transcode`);const t=await _(i);if(t){const d=await m(t,"audio/wav","inbound",c);r.decryptedVoicePath=d.path,r.voiceMediaType="audio/wav",n.debug(`${a} voice: saved WAV to ${d.path}`)}else{const d=await m(i,"audio/silk","inbound",c);r.decryptedVoicePath=d.path,r.voiceMediaType="audio/silk",n.debug(`${a} voice: silk transcode unavailable, saved raw SILK to ${d.path}`)}}catch(i){n.error(`${a} voice download/transcode failed: ${String(i)}`),p(`weixin ${a} voice download/transcode failed: ${String(i)}`)}}else if(o.type===y.FILE){const e=o.file_item;if(!e?.media?.encrypt_query_param||!e.media.aes_key)return r;try{const i=await l(e.media.encrypt_query_param,e.media.aes_key,s,`${a} file`),t=g(e.file_name??"file.bin"),d=await m(i,t,"inbound",c,e.file_name??void 0);r.decryptedFilePath=d.path,r.fileMediaType=t,n.debug(`${a} file: saved to ${d.path} mime=${t}`)}catch(i){n.error(`${a} file download failed: ${String(i)}`),p(`weixin ${a} file download failed: ${String(i)}`)}}else if(o.type===y.VIDEO){const e=o.video_item;if(!e?.media?.encrypt_query_param||!e.media.aes_key)return r;try{const i=await l(e.media.encrypt_query_param,e.media.aes_key,s,`${a} video`),t=await m(i,"video/mp4","inbound",c);r.decryptedVideoPath=t.path,n.debug(`${a} video: saved to ${t.path}`)}catch(i){n.error(`${a} video download failed: ${String(i)}`),p(`weixin ${a} video download failed: ${String(i)}`)}}return r}export{M as downloadMediaFromItem};
